improve comment
[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 // template-based folder for simple primitive constants like ConstantInt, and
16 // the special case hackery that we use to symbolically evaluate expressions
17 // that use ConstantExprs.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "ConstantFold.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/GetElementPtrTypeIterator.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <limits>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 //                ConstantFold*Instruction Implementations
37 //===----------------------------------------------------------------------===//
38
39 /// BitCastConstantVector - Convert the specified ConstantVector node to the
40 /// specified vector type.  At this point, we know that the elements of the
41 /// input vector constant are all simple integer or FP values.
42 static Constant *BitCastConstantVector(ConstantVector *CV,
43                                        const VectorType *DstTy) {
44   // If this cast changes element count then we can't handle it here:
45   // doing so requires endianness information.  This should be handled by
46   // Analysis/ConstantFolding.cpp
47   unsigned NumElts = DstTy->getNumElements();
48   if (NumElts != CV->getNumOperands())
49     return 0;
50   
51   // Check to verify that all elements of the input are simple.
52   for (unsigned i = 0; i != NumElts; ++i) {
53     if (!isa<ConstantInt>(CV->getOperand(i)) &&
54         !isa<ConstantFP>(CV->getOperand(i)))
55       return 0;
56   }
57
58   // Bitcast each element now.
59   std::vector<Constant*> Result;
60   const Type *DstEltTy = DstTy->getElementType();
61   for (unsigned i = 0; i != NumElts; ++i)
62     Result.push_back(ConstantExpr::getBitCast(CV->getOperand(i), DstEltTy));
63   return ConstantVector::get(Result);
64 }
65
66 /// This function determines which opcode to use to fold two constant cast 
67 /// expressions together. It uses CastInst::isEliminableCastPair to determine
68 /// the opcode. Consequently its just a wrapper around that function.
69 /// @brief Determine if it is valid to fold a cast of a cast
70 static unsigned
71 foldConstantCastPair(
72   unsigned opc,          ///< opcode of the second cast constant expression
73   const ConstantExpr*Op, ///< the first cast constant expression
74   const Type *DstTy      ///< desintation type of the first cast
75 ) {
76   assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
77   assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
78   assert(CastInst::isCast(opc) && "Invalid cast opcode");
79   
80   // The the types and opcodes for the two Cast constant expressions
81   const Type *SrcTy = Op->getOperand(0)->getType();
82   const Type *MidTy = Op->getType();
83   Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
84   Instruction::CastOps secondOp = Instruction::CastOps(opc);
85
86   // Let CastInst::isEliminableCastPair do the heavy lifting.
87   return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
88                                         Type::Int64Ty);
89 }
90
91 static Constant *FoldBitCast(Constant *V, const Type *DestTy) {
92   const Type *SrcTy = V->getType();
93   if (SrcTy == DestTy)
94     return V; // no-op cast
95   
96   // Check to see if we are casting a pointer to an aggregate to a pointer to
97   // the first element.  If so, return the appropriate GEP instruction.
98   if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
99     if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
100       if (PTy->getAddressSpace() == DPTy->getAddressSpace()) {
101         SmallVector<Value*, 8> IdxList;
102         IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
103         const Type *ElTy = PTy->getElementType();
104         while (ElTy != DPTy->getElementType()) {
105           if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
106             if (STy->getNumElements() == 0) break;
107             ElTy = STy->getElementType(0);
108             IdxList.push_back(Constant::getNullValue(Type::Int32Ty));
109           } else if (const SequentialType *STy = 
110                      dyn_cast<SequentialType>(ElTy)) {
111             if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
112             ElTy = STy->getElementType();
113             IdxList.push_back(IdxList[0]);
114           } else {
115             break;
116           }
117         }
118         
119         if (ElTy == DPTy->getElementType())
120           return ConstantExpr::getGetElementPtr(V, &IdxList[0], IdxList.size());
121       }
122   
123   // Handle casts from one vector constant to another.  We know that the src 
124   // and dest type have the same size (otherwise its an illegal cast).
125   if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
126     if (const VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
127       assert(DestPTy->getBitWidth() == SrcTy->getBitWidth() &&
128              "Not cast between same sized vectors!");
129       // First, check for null.  Undef is already handled.
130       if (isa<ConstantAggregateZero>(V))
131         return Constant::getNullValue(DestTy);
132       
133       if (ConstantVector *CV = dyn_cast<ConstantVector>(V))
134         return BitCastConstantVector(CV, DestPTy);
135     }
136   }
137   
138   // Finally, implement bitcast folding now.   The code below doesn't handle
139   // bitcast right.
140   if (isa<ConstantPointerNull>(V))  // ptr->ptr cast.
141     return ConstantPointerNull::get(cast<PointerType>(DestTy));
142   
143   // Handle integral constant input.
144   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
145     if (DestTy->isInteger())
146       // Integral -> Integral. This is a no-op because the bit widths must
147       // be the same. Consequently, we just fold to V.
148       return V;
149     
150     if (DestTy->isFloatingPoint()) {
151       assert((DestTy == Type::DoubleTy || DestTy == Type::FloatTy) && 
152              "Unknown FP type!");
153       return ConstantFP::get(APFloat(CI->getValue()));
154     }
155     // Otherwise, can't fold this (vector?)
156     return 0;
157   }
158   
159   // Handle ConstantFP input.
160   if (const ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
161     // FP -> Integral.
162     if (DestTy == Type::Int32Ty) {
163       return ConstantInt::get(FP->getValueAPF().convertToAPInt());
164     } else {
165       assert(DestTy == Type::Int64Ty && "only support f32/f64 for now!");
166       return ConstantInt::get(FP->getValueAPF().convertToAPInt());
167     }
168   }
169   return 0;
170 }
171
172
173 Constant *llvm::ConstantFoldCastInstruction(unsigned opc, const Constant *V,
174                                             const Type *DestTy) {
175   if (isa<UndefValue>(V)) {
176     // zext(undef) = 0, because the top bits will be zero.
177     // sext(undef) = 0, because the top bits will all be the same.
178     // [us]itofp(undef) = 0, because the result value is bounded.
179     if (opc == Instruction::ZExt || opc == Instruction::SExt ||
180         opc == Instruction::UIToFP || opc == Instruction::SIToFP)
181       return Constant::getNullValue(DestTy);
182     return UndefValue::get(DestTy);
183   }
184   // No compile-time operations on this type yet.
185   if (V->getType() == Type::PPC_FP128Ty || DestTy == Type::PPC_FP128Ty)
186     return 0;
187
188   // If the cast operand is a constant expression, there's a few things we can
189   // do to try to simplify it.
190   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
191     if (CE->isCast()) {
192       // Try hard to fold cast of cast because they are often eliminable.
193       if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
194         return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
195     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
196       // If all of the indexes in the GEP are null values, there is no pointer
197       // adjustment going on.  We might as well cast the source pointer.
198       bool isAllNull = true;
199       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
200         if (!CE->getOperand(i)->isNullValue()) {
201           isAllNull = false;
202           break;
203         }
204       if (isAllNull)
205         // This is casting one pointer type to another, always BitCast
206         return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
207     }
208   }
209
210   // We actually have to do a cast now. Perform the cast according to the
211   // opcode specified.
212   switch (opc) {
213   case Instruction::FPTrunc:
214   case Instruction::FPExt:
215     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
216       APFloat Val = FPC->getValueAPF();
217       Val.convert(DestTy == Type::FloatTy ? APFloat::IEEEsingle :
218                   DestTy == Type::DoubleTy ? APFloat::IEEEdouble :
219                   DestTy == Type::X86_FP80Ty ? APFloat::x87DoubleExtended :
220                   DestTy == Type::FP128Ty ? APFloat::IEEEquad :
221                   APFloat::Bogus,
222                   APFloat::rmNearestTiesToEven);
223       return ConstantFP::get(Val);
224     }
225     return 0; // Can't fold.
226   case Instruction::FPToUI: 
227   case Instruction::FPToSI:
228     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
229       const APFloat &V = FPC->getValueAPF();
230       uint64_t x[2]; 
231       uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
232       (void) V.convertToInteger(x, DestBitWidth, opc==Instruction::FPToSI,
233                                 APFloat::rmTowardZero);
234       APInt Val(DestBitWidth, 2, x);
235       return ConstantInt::get(Val);
236     }
237     if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
238       std::vector<Constant*> res;
239       const VectorType *DestVecTy = cast<VectorType>(DestTy);
240       const Type *DstEltTy = DestVecTy->getElementType();
241       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
242         res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
243                                                   DstEltTy));
244       return ConstantVector::get(DestVecTy, res);
245     }
246     return 0; // Can't fold.
247   case Instruction::IntToPtr:   //always treated as unsigned
248     if (V->isNullValue())       // Is it an integral null value?
249       return ConstantPointerNull::get(cast<PointerType>(DestTy));
250     return 0;                   // Other pointer types cannot be casted
251   case Instruction::PtrToInt:   // always treated as unsigned
252     if (V->isNullValue())       // is it a null pointer value?
253       return ConstantInt::get(DestTy, 0);
254     return 0;                   // Other pointer types cannot be casted
255   case Instruction::UIToFP:
256   case Instruction::SIToFP:
257     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
258       APInt api = CI->getValue();
259       const uint64_t zero[] = {0, 0};
260       APFloat apf = APFloat(APInt(DestTy->getPrimitiveSizeInBits(),
261                                   2, zero));
262       (void)apf.convertFromAPInt(api, 
263                                  opc==Instruction::SIToFP,
264                                  APFloat::rmNearestTiesToEven);
265       return ConstantFP::get(apf);
266     }
267     if (const ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
268       std::vector<Constant*> res;
269       const VectorType *DestVecTy = cast<VectorType>(DestTy);
270       const Type *DstEltTy = DestVecTy->getElementType();
271       for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
272         res.push_back(ConstantFoldCastInstruction(opc, V->getOperand(i),
273                                                   DstEltTy));
274       return ConstantVector::get(DestVecTy, res);
275     }
276     return 0;
277   case Instruction::ZExt:
278     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
279       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
280       APInt Result(CI->getValue());
281       Result.zext(BitWidth);
282       return ConstantInt::get(Result);
283     }
284     return 0;
285   case Instruction::SExt:
286     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
287       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
288       APInt Result(CI->getValue());
289       Result.sext(BitWidth);
290       return ConstantInt::get(Result);
291     }
292     return 0;
293   case Instruction::Trunc:
294     if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
295       uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
296       APInt Result(CI->getValue());
297       Result.trunc(BitWidth);
298       return ConstantInt::get(Result);
299     }
300     return 0;
301   case Instruction::BitCast:
302     return FoldBitCast(const_cast<Constant*>(V), DestTy);
303   default:
304     assert(!"Invalid CE CastInst opcode");
305     break;
306   }
307
308   assert(0 && "Failed to cast constant expression");
309   return 0;
310 }
311
312 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
313                                               const Constant *V1,
314                                               const Constant *V2) {
315   if (const ConstantInt *CB = dyn_cast<ConstantInt>(Cond))
316     return const_cast<Constant*>(CB->getZExtValue() ? V1 : V2);
317
318   if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
319   if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
320   if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
321   if (V1 == V2) return const_cast<Constant*>(V1);
322   return 0;
323 }
324
325 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
326                                                       const Constant *Idx) {
327   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
328     return UndefValue::get(cast<VectorType>(Val->getType())->getElementType());
329   if (Val->isNullValue())  // ee(zero, x) -> zero
330     return Constant::getNullValue(
331                           cast<VectorType>(Val->getType())->getElementType());
332   
333   if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
334     if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
335       return CVal->getOperand(CIdx->getZExtValue());
336     } else if (isa<UndefValue>(Idx)) {
337       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
338       return CVal->getOperand(0);
339     }
340   }
341   return 0;
342 }
343
344 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
345                                                      const Constant *Elt,
346                                                      const Constant *Idx) {
347   const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
348   if (!CIdx) return 0;
349   APInt idxVal = CIdx->getValue();
350   if (isa<UndefValue>(Val)) { 
351     // Insertion of scalar constant into vector undef
352     // Optimize away insertion of undef
353     if (isa<UndefValue>(Elt))
354       return const_cast<Constant*>(Val);
355     // Otherwise break the aggregate undef into multiple undefs and do
356     // the insertion
357     unsigned numOps = 
358       cast<VectorType>(Val->getType())->getNumElements();
359     std::vector<Constant*> Ops; 
360     Ops.reserve(numOps);
361     for (unsigned i = 0; i < numOps; ++i) {
362       const Constant *Op =
363         (idxVal == i) ? Elt : UndefValue::get(Elt->getType());
364       Ops.push_back(const_cast<Constant*>(Op));
365     }
366     return ConstantVector::get(Ops);
367   }
368   if (isa<ConstantAggregateZero>(Val)) {
369     // Insertion of scalar constant into vector aggregate zero
370     // Optimize away insertion of zero
371     if (Elt->isNullValue())
372       return const_cast<Constant*>(Val);
373     // Otherwise break the aggregate zero into multiple zeros and do
374     // the insertion
375     unsigned numOps = 
376       cast<VectorType>(Val->getType())->getNumElements();
377     std::vector<Constant*> Ops; 
378     Ops.reserve(numOps);
379     for (unsigned i = 0; i < numOps; ++i) {
380       const Constant *Op =
381         (idxVal == i) ? Elt : Constant::getNullValue(Elt->getType());
382       Ops.push_back(const_cast<Constant*>(Op));
383     }
384     return ConstantVector::get(Ops);
385   }
386   if (const ConstantVector *CVal = dyn_cast<ConstantVector>(Val)) {
387     // Insertion of scalar constant into vector constant
388     std::vector<Constant*> Ops; 
389     Ops.reserve(CVal->getNumOperands());
390     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
391       const Constant *Op =
392         (idxVal == i) ? Elt : cast<Constant>(CVal->getOperand(i));
393       Ops.push_back(const_cast<Constant*>(Op));
394     }
395     return ConstantVector::get(Ops);
396   }
397
398   return 0;
399 }
400
401 /// GetVectorElement - If C is a ConstantVector, ConstantAggregateZero or Undef
402 /// return the specified element value.  Otherwise return null.
403 static Constant *GetVectorElement(const Constant *C, unsigned EltNo) {
404   if (const ConstantVector *CV = dyn_cast<ConstantVector>(C))
405     return CV->getOperand(EltNo);
406   
407   const Type *EltTy = cast<VectorType>(C->getType())->getElementType();
408   if (isa<ConstantAggregateZero>(C))
409     return Constant::getNullValue(EltTy);
410   if (isa<UndefValue>(C))
411     return UndefValue::get(EltTy);
412   return 0;
413 }
414
415 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
416                                                      const Constant *V2,
417                                                      const Constant *Mask) {
418   // Undefined shuffle mask -> undefined value.
419   if (isa<UndefValue>(Mask)) return UndefValue::get(V1->getType());
420   
421   unsigned NumElts = cast<VectorType>(V1->getType())->getNumElements();
422   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
423   
424   // Loop over the shuffle mask, evaluating each element.
425   SmallVector<Constant*, 32> Result;
426   for (unsigned i = 0; i != NumElts; ++i) {
427     Constant *InElt = GetVectorElement(Mask, i);
428     if (InElt == 0) return 0;
429     
430     if (isa<UndefValue>(InElt))
431       InElt = UndefValue::get(EltTy);
432     else if (ConstantInt *CI = dyn_cast<ConstantInt>(InElt)) {
433       unsigned Elt = CI->getZExtValue();
434       if (Elt >= NumElts*2)
435         InElt = UndefValue::get(EltTy);
436       else if (Elt >= NumElts)
437         InElt = GetVectorElement(V2, Elt-NumElts);
438       else
439         InElt = GetVectorElement(V1, Elt);
440       if (InElt == 0) return 0;
441     } else {
442       // Unknown value.
443       return 0;
444     }
445     Result.push_back(InElt);
446   }
447   
448   return ConstantVector::get(&Result[0], Result.size());
449 }
450
451 Constant *llvm::ConstantFoldExtractValueInstruction(const Constant *Agg,
452                                                     const unsigned *Idxs,
453                                                     unsigned NumIdx) {
454   // Base case: no indices, so return the entire value.
455   if (NumIdx == 0)
456     return const_cast<Constant *>(Agg);
457
458   if (isa<UndefValue>(Agg))  // ev(undef, x) -> undef
459     return UndefValue::get(ExtractValueInst::getIndexedType(Agg->getType(),
460                                                             Idxs,
461                                                             Idxs + NumIdx));
462
463   if (isa<ConstantAggregateZero>(Agg))  // ev(0, x) -> 0
464     return
465       Constant::getNullValue(ExtractValueInst::getIndexedType(Agg->getType(),
466                                                               Idxs,
467                                                               Idxs + NumIdx));
468
469   // Otherwise recurse.
470   return ConstantFoldExtractValueInstruction(Agg->getOperand(*Idxs),
471                                              Idxs+1, NumIdx-1);
472 }
473
474 Constant *llvm::ConstantFoldInsertValueInstruction(const Constant *Agg,
475                                                    const Constant *Val,
476                                                    const unsigned *Idxs,
477                                                    unsigned NumIdx) {
478   // Base case: no indices, so replace the entire value.
479   if (NumIdx == 0)
480     return const_cast<Constant *>(Val);
481
482   if (isa<UndefValue>(Agg)) {
483     // Insertion of constant into aggregate undef
484     // Optimize away insertion of undef
485     if (isa<UndefValue>(Val))
486       return const_cast<Constant*>(Agg);
487     // Otherwise break the aggregate undef into multiple undefs and do
488     // the insertion
489     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
490     unsigned numOps;
491     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
492       numOps = AR->getNumElements();
493     else
494       numOps = cast<StructType>(AggTy)->getNumElements();
495     std::vector<Constant*> Ops(numOps); 
496     for (unsigned i = 0; i < numOps; ++i) {
497       const Type *MemberTy = AggTy->getTypeAtIndex(i);
498       const Constant *Op =
499         (*Idxs == i) ?
500         ConstantFoldInsertValueInstruction(UndefValue::get(MemberTy),
501                                            Val, Idxs+1, NumIdx-1) :
502         UndefValue::get(MemberTy);
503       Ops[i] = const_cast<Constant*>(Op);
504     }
505     if (isa<StructType>(AggTy))
506       return ConstantStruct::get(Ops);
507     else
508       return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
509   }
510   if (isa<ConstantAggregateZero>(Agg)) {
511     // Insertion of constant into aggregate zero
512     // Optimize away insertion of zero
513     if (Val->isNullValue())
514       return const_cast<Constant*>(Agg);
515     // Otherwise break the aggregate zero into multiple zeros and do
516     // the insertion
517     const CompositeType *AggTy = cast<CompositeType>(Agg->getType());
518     unsigned numOps;
519     if (const ArrayType *AR = dyn_cast<ArrayType>(AggTy))
520       numOps = AR->getNumElements();
521     else
522       numOps = cast<StructType>(AggTy)->getNumElements();
523     std::vector<Constant*> Ops(numOps);
524     for (unsigned i = 0; i < numOps; ++i) {
525       const Type *MemberTy = AggTy->getTypeAtIndex(i);
526       const Constant *Op =
527         (*Idxs == i) ?
528         ConstantFoldInsertValueInstruction(Constant::getNullValue(MemberTy),
529                                            Val, Idxs+1, NumIdx-1) :
530         Constant::getNullValue(MemberTy);
531       Ops[i] = const_cast<Constant*>(Op);
532     }
533     if (isa<StructType>(AggTy))
534       return ConstantStruct::get(Ops);
535     else
536       return ConstantArray::get(cast<ArrayType>(AggTy), Ops);
537   }
538   if (isa<ConstantStruct>(Agg) || isa<ConstantArray>(Agg)) {
539     // Insertion of constant into aggregate constant
540     std::vector<Constant*> Ops(Agg->getNumOperands());
541     for (unsigned i = 0; i < Agg->getNumOperands(); ++i) {
542       const Constant *Op =
543         (*Idxs == i) ?
544         ConstantFoldInsertValueInstruction(Agg->getOperand(i),
545                                            Val, Idxs+1, NumIdx-1) :
546         Agg->getOperand(i);
547       Ops[i] = const_cast<Constant*>(Op);
548     }
549     Constant *C;
550     if (isa<StructType>(Agg->getType()))
551       C = ConstantStruct::get(Ops);
552     else
553       C = ConstantArray::get(cast<ArrayType>(Agg->getType()), Ops);
554     return C;
555   }
556
557   return 0;
558 }
559
560 /// EvalVectorOp - Given two vector constants and a function pointer, apply the
561 /// function pointer to each element pair, producing a new ConstantVector
562 /// constant. Either or both of V1 and V2 may be NULL, meaning a
563 /// ConstantAggregateZero operand.
564 static Constant *EvalVectorOp(const ConstantVector *V1, 
565                               const ConstantVector *V2,
566                               const VectorType *VTy,
567                               Constant *(*FP)(Constant*, Constant*)) {
568   std::vector<Constant*> Res;
569   const Type *EltTy = VTy->getElementType();
570   for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
571     const Constant *C1 = V1 ? V1->getOperand(i) : Constant::getNullValue(EltTy);
572     const Constant *C2 = V2 ? V2->getOperand(i) : Constant::getNullValue(EltTy);
573     Res.push_back(FP(const_cast<Constant*>(C1),
574                      const_cast<Constant*>(C2)));
575   }
576   return ConstantVector::get(Res);
577 }
578
579 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
580                                               const Constant *C1,
581                                               const Constant *C2) {
582   // No compile-time operations on this type yet.
583   if (C1->getType() == Type::PPC_FP128Ty)
584     return 0;
585
586   // Handle UndefValue up front
587   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
588     switch (Opcode) {
589     case Instruction::Xor:
590       if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
591         // Handle undef ^ undef -> 0 special case. This is a common
592         // idiom (misuse).
593         return Constant::getNullValue(C1->getType());
594       // Fallthrough
595     case Instruction::Add:
596     case Instruction::Sub:
597       return UndefValue::get(C1->getType());
598     case Instruction::Mul:
599     case Instruction::And:
600       return Constant::getNullValue(C1->getType());
601     case Instruction::UDiv:
602     case Instruction::SDiv:
603     case Instruction::FDiv:
604     case Instruction::URem:
605     case Instruction::SRem:
606     case Instruction::FRem:
607       if (!isa<UndefValue>(C2))                    // undef / X -> 0
608         return Constant::getNullValue(C1->getType());
609       return const_cast<Constant*>(C2);            // X / undef -> undef
610     case Instruction::Or:                          // X | undef -> -1
611       if (const VectorType *PTy = dyn_cast<VectorType>(C1->getType()))
612         return ConstantVector::getAllOnesValue(PTy);
613       return ConstantInt::getAllOnesValue(C1->getType());
614     case Instruction::LShr:
615       if (isa<UndefValue>(C2) && isa<UndefValue>(C1))
616         return const_cast<Constant*>(C1);           // undef lshr undef -> undef
617       return Constant::getNullValue(C1->getType()); // X lshr undef -> 0
618                                                     // undef lshr X -> 0
619     case Instruction::AShr:
620       if (!isa<UndefValue>(C2))
621         return const_cast<Constant*>(C1);           // undef ashr X --> undef
622       else if (isa<UndefValue>(C1)) 
623         return const_cast<Constant*>(C1);           // undef ashr undef -> undef
624       else
625         return const_cast<Constant*>(C1);           // X ashr undef --> X
626     case Instruction::Shl:
627       // undef << X -> 0   or   X << undef -> 0
628       return Constant::getNullValue(C1->getType());
629     }
630   }
631
632   // Handle simplifications of the RHS when a constant int.
633   if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
634     switch (Opcode) {
635     case Instruction::Add:
636       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X + 0 == X
637       break;
638     case Instruction::Sub:
639       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X - 0 == X
640       break;
641     case Instruction::Mul:
642       if (CI2->equalsInt(0)) return const_cast<Constant*>(C2);  // X * 0 == 0
643       if (CI2->equalsInt(1))
644         return const_cast<Constant*>(C1);                       // X * 1 == X
645       break;
646     case Instruction::UDiv:
647     case Instruction::SDiv:
648       if (CI2->equalsInt(1))
649         return const_cast<Constant*>(C1);                     // X / 1 == X
650       break;
651     case Instruction::URem:
652     case Instruction::SRem:
653       if (CI2->equalsInt(1))
654         return Constant::getNullValue(CI2->getType());        // X % 1 == 0
655       break;
656     case Instruction::And:
657       if (CI2->isZero()) return const_cast<Constant*>(C2);    // X & 0 == 0
658       if (CI2->isAllOnesValue())
659         return const_cast<Constant*>(C1);                     // X & -1 == X
660       
661       if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
662         // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
663         if (CE1->getOpcode() == Instruction::ZExt) {
664           unsigned DstWidth = CI2->getType()->getBitWidth();
665           unsigned SrcWidth =
666             CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
667           APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
668           if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
669             return const_cast<Constant*>(C1);
670         }
671         
672         // If and'ing the address of a global with a constant, fold it.
673         if (CE1->getOpcode() == Instruction::PtrToInt && 
674             isa<GlobalValue>(CE1->getOperand(0))) {
675           GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
676         
677           // Functions are at least 4-byte aligned.
678           unsigned GVAlign = GV->getAlignment();
679           if (isa<Function>(GV))
680             GVAlign = std::max(GVAlign, 4U);
681           
682           if (GVAlign > 1) {
683             unsigned DstWidth = CI2->getType()->getBitWidth();
684             unsigned SrcWidth = std::min(DstWidth, Log2_32(GVAlign));
685             APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
686
687             // If checking bits we know are clear, return zero.
688             if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
689               return Constant::getNullValue(CI2->getType());
690           }
691         }
692       }
693       break;
694     case Instruction::Or:
695       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X | 0 == X
696       if (CI2->isAllOnesValue())
697         return const_cast<Constant*>(C2);  // X | -1 == -1
698       break;
699     case Instruction::Xor:
700       if (CI2->equalsInt(0)) return const_cast<Constant*>(C1);  // X ^ 0 == X
701       break;
702     case Instruction::AShr:
703       // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
704       if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
705         if (CE1->getOpcode() == Instruction::ZExt)  // Top bits known zero.
706           return ConstantExpr::getLShr(const_cast<Constant*>(C1),
707                                        const_cast<Constant*>(C2));
708       break;
709     }
710   }
711   
712   // At this point we know neither constant is an UndefValue.
713   if (const ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
714     if (const ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
715       using namespace APIntOps;
716       const APInt &C1V = CI1->getValue();
717       const APInt &C2V = CI2->getValue();
718       switch (Opcode) {
719       default:
720         break;
721       case Instruction::Add:     
722         return ConstantInt::get(C1V + C2V);
723       case Instruction::Sub:     
724         return ConstantInt::get(C1V - C2V);
725       case Instruction::Mul:     
726         return ConstantInt::get(C1V * C2V);
727       case Instruction::UDiv:
728         if (CI2->isNullValue())                  
729           return 0;        // X / 0 -> can't fold
730         return ConstantInt::get(C1V.udiv(C2V));
731       case Instruction::SDiv:
732         if (CI2->isNullValue()) 
733           return 0;        // X / 0 -> can't fold
734         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
735           return 0;        // MIN_INT / -1 -> overflow
736         return ConstantInt::get(C1V.sdiv(C2V));
737       case Instruction::URem:
738         if (C2->isNullValue()) 
739           return 0;        // X / 0 -> can't fold
740         return ConstantInt::get(C1V.urem(C2V));
741       case Instruction::SRem:    
742         if (CI2->isNullValue()) 
743           return 0;        // X % 0 -> can't fold
744         if (C2V.isAllOnesValue() && C1V.isMinSignedValue())
745           return 0;        // MIN_INT % -1 -> overflow
746         return ConstantInt::get(C1V.srem(C2V));
747       case Instruction::And:
748         return ConstantInt::get(C1V & C2V);
749       case Instruction::Or:
750         return ConstantInt::get(C1V | C2V);
751       case Instruction::Xor:
752         return ConstantInt::get(C1V ^ C2V);
753       case Instruction::Shl: {
754         uint32_t shiftAmt = C2V.getZExtValue();
755         if (shiftAmt < C1V.getBitWidth())
756           return ConstantInt::get(C1V.shl(shiftAmt));
757         else
758           return UndefValue::get(C1->getType()); // too big shift is undef
759       }
760       case Instruction::LShr: {
761         uint32_t shiftAmt = C2V.getZExtValue();
762         if (shiftAmt < C1V.getBitWidth())
763           return ConstantInt::get(C1V.lshr(shiftAmt));
764         else
765           return UndefValue::get(C1->getType()); // too big shift is undef
766       }
767       case Instruction::AShr: {
768         uint32_t shiftAmt = C2V.getZExtValue();
769         if (shiftAmt < C1V.getBitWidth())
770           return ConstantInt::get(C1V.ashr(shiftAmt));
771         else
772           return UndefValue::get(C1->getType()); // too big shift is undef
773       }
774       }
775     }
776   } else if (const ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
777     if (const ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
778       APFloat C1V = CFP1->getValueAPF();
779       APFloat C2V = CFP2->getValueAPF();
780       APFloat C3V = C1V;  // copy for modification
781       switch (Opcode) {
782       default:                   
783         break;
784       case Instruction::Add:
785         (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
786         return ConstantFP::get(C3V);
787       case Instruction::Sub:     
788         (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
789         return ConstantFP::get(C3V);
790       case Instruction::Mul:
791         (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
792         return ConstantFP::get(C3V);
793       case Instruction::FDiv:
794         (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
795         return ConstantFP::get(C3V);
796       case Instruction::FRem:
797         if (C2V.isZero()) {
798           // IEEE 754, Section 7.1, #5
799           if (CFP1->getType() == Type::DoubleTy)
800             return ConstantFP::get(APFloat(std::numeric_limits<double>::
801                                            quiet_NaN()));
802           if (CFP1->getType() == Type::FloatTy)
803             return ConstantFP::get(APFloat(std::numeric_limits<float>::
804                                            quiet_NaN()));
805           break;
806         }
807         (void)C3V.mod(C2V, APFloat::rmNearestTiesToEven);
808         return ConstantFP::get(C3V);
809       }
810     }
811   } else if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType())) {
812     const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1);
813     const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2);
814     if ((CP1 != NULL || isa<ConstantAggregateZero>(C1)) &&
815         (CP2 != NULL || isa<ConstantAggregateZero>(C2))) {
816       switch (Opcode) {
817       default:
818         break;
819       case Instruction::Add: 
820         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAdd);
821       case Instruction::Sub: 
822         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSub);
823       case Instruction::Mul: 
824         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getMul);
825       case Instruction::UDiv:
826         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getUDiv);
827       case Instruction::SDiv:
828         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSDiv);
829       case Instruction::FDiv:
830         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFDiv);
831       case Instruction::URem:
832         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getURem);
833       case Instruction::SRem:
834         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getSRem);
835       case Instruction::FRem:
836         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getFRem);
837       case Instruction::And: 
838         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getAnd);
839       case Instruction::Or:  
840         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getOr);
841       case Instruction::Xor: 
842         return EvalVectorOp(CP1, CP2, VTy, ConstantExpr::getXor);
843       }
844     }
845   }
846
847   if (isa<ConstantExpr>(C1)) {
848     // There are many possible foldings we could do here.  We should probably
849     // at least fold add of a pointer with an integer into the appropriate
850     // getelementptr.  This will improve alias analysis a bit.
851   } else if (isa<ConstantExpr>(C2)) {
852     // If C2 is a constant expr and C1 isn't, flop them around and fold the
853     // other way if possible.
854     switch (Opcode) {
855     case Instruction::Add:
856     case Instruction::Mul:
857     case Instruction::And:
858     case Instruction::Or:
859     case Instruction::Xor:
860       // No change of opcode required.
861       return ConstantFoldBinaryInstruction(Opcode, C2, C1);
862       
863     case Instruction::Shl:
864     case Instruction::LShr:
865     case Instruction::AShr:
866     case Instruction::Sub:
867     case Instruction::SDiv:
868     case Instruction::UDiv:
869     case Instruction::FDiv:
870     case Instruction::URem:
871     case Instruction::SRem:
872     case Instruction::FRem:
873     default:  // These instructions cannot be flopped around.
874       break;
875     }
876   }
877   
878   // We don't know how to fold this.
879   return 0;
880 }
881
882 /// isZeroSizedType - This type is zero sized if its an array or structure of
883 /// zero sized types.  The only leaf zero sized type is an empty structure.
884 static bool isMaybeZeroSizedType(const Type *Ty) {
885   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
886   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
887
888     // If all of elements have zero size, this does too.
889     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
890       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
891     return true;
892
893   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
894     return isMaybeZeroSizedType(ATy->getElementType());
895   }
896   return false;
897 }
898
899 /// IdxCompare - Compare the two constants as though they were getelementptr
900 /// indices.  This allows coersion of the types to be the same thing.
901 ///
902 /// If the two constants are the "same" (after coersion), return 0.  If the
903 /// first is less than the second, return -1, if the second is less than the
904 /// first, return 1.  If the constants are not integral, return -2.
905 ///
906 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
907   if (C1 == C2) return 0;
908
909   // Ok, we found a different index.  If they are not ConstantInt, we can't do
910   // anything with them.
911   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
912     return -2; // don't know!
913
914   // Ok, we have two differing integer indices.  Sign extend them to be the same
915   // type.  Long is always big enough, so we use it.
916   if (C1->getType() != Type::Int64Ty)
917     C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
918
919   if (C2->getType() != Type::Int64Ty)
920     C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
921
922   if (C1 == C2) return 0;  // They are equal
923
924   // If the type being indexed over is really just a zero sized type, there is
925   // no pointer difference being made here.
926   if (isMaybeZeroSizedType(ElTy))
927     return -2; // dunno.
928
929   // If they are really different, now that they are the same type, then we
930   // found a difference!
931   if (cast<ConstantInt>(C1)->getSExtValue() < 
932       cast<ConstantInt>(C2)->getSExtValue())
933     return -1;
934   else
935     return 1;
936 }
937
938 /// evaluateFCmpRelation - This function determines if there is anything we can
939 /// decide about the two constants provided.  This doesn't need to handle simple
940 /// things like ConstantFP comparisons, but should instead handle ConstantExprs.
941 /// If we can determine that the two constants have a particular relation to 
942 /// each other, we should return the corresponding FCmpInst predicate, 
943 /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
944 /// ConstantFoldCompareInstruction.
945 ///
946 /// To simplify this code we canonicalize the relation so that the first
947 /// operand is always the most "complex" of the two.  We consider ConstantFP
948 /// to be the simplest, and ConstantExprs to be the most complex.
949 static FCmpInst::Predicate evaluateFCmpRelation(const Constant *V1, 
950                                                 const Constant *V2) {
951   assert(V1->getType() == V2->getType() &&
952          "Cannot compare values of different types!");
953
954   // No compile-time operations on this type yet.
955   if (V1->getType() == Type::PPC_FP128Ty)
956     return FCmpInst::BAD_FCMP_PREDICATE;
957
958   // Handle degenerate case quickly
959   if (V1 == V2) return FCmpInst::FCMP_OEQ;
960
961   if (!isa<ConstantExpr>(V1)) {
962     if (!isa<ConstantExpr>(V2)) {
963       // We distilled thisUse the standard constant folder for a few cases
964       ConstantInt *R = 0;
965       Constant *C1 = const_cast<Constant*>(V1);
966       Constant *C2 = const_cast<Constant*>(V2);
967       R = dyn_cast<ConstantInt>(
968                              ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, C1, C2));
969       if (R && !R->isZero()) 
970         return FCmpInst::FCMP_OEQ;
971       R = dyn_cast<ConstantInt>(
972                              ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, C1, C2));
973       if (R && !R->isZero()) 
974         return FCmpInst::FCMP_OLT;
975       R = dyn_cast<ConstantInt>(
976                              ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, C1, C2));
977       if (R && !R->isZero()) 
978         return FCmpInst::FCMP_OGT;
979
980       // Nothing more we can do
981       return FCmpInst::BAD_FCMP_PREDICATE;
982     }
983     
984     // If the first operand is simple and second is ConstantExpr, swap operands.
985     FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
986     if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
987       return FCmpInst::getSwappedPredicate(SwappedRelation);
988   } else {
989     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
990     // constantexpr or a simple constant.
991     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
992     switch (CE1->getOpcode()) {
993     case Instruction::FPTrunc:
994     case Instruction::FPExt:
995     case Instruction::UIToFP:
996     case Instruction::SIToFP:
997       // We might be able to do something with these but we don't right now.
998       break;
999     default:
1000       break;
1001     }
1002   }
1003   // There are MANY other foldings that we could perform here.  They will
1004   // probably be added on demand, as they seem needed.
1005   return FCmpInst::BAD_FCMP_PREDICATE;
1006 }
1007
1008 /// evaluateICmpRelation - This function determines if there is anything we can
1009 /// decide about the two constants provided.  This doesn't need to handle simple
1010 /// things like integer comparisons, but should instead handle ConstantExprs
1011 /// and GlobalValues.  If we can determine that the two constants have a
1012 /// particular relation to each other, we should return the corresponding ICmp
1013 /// predicate, otherwise return ICmpInst::BAD_ICMP_PREDICATE.
1014 ///
1015 /// To simplify this code we canonicalize the relation so that the first
1016 /// operand is always the most "complex" of the two.  We consider simple
1017 /// constants (like ConstantInt) to be the simplest, followed by
1018 /// GlobalValues, followed by ConstantExpr's (the most complex).
1019 ///
1020 static ICmpInst::Predicate evaluateICmpRelation(const Constant *V1, 
1021                                                 const Constant *V2,
1022                                                 bool isSigned) {
1023   assert(V1->getType() == V2->getType() &&
1024          "Cannot compare different types of values!");
1025   if (V1 == V2) return ICmpInst::ICMP_EQ;
1026
1027   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1028     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1029       // We distilled this down to a simple case, use the standard constant
1030       // folder.
1031       ConstantInt *R = 0;
1032       Constant *C1 = const_cast<Constant*>(V1);
1033       Constant *C2 = const_cast<Constant*>(V2);
1034       ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
1035       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1036       if (R && !R->isZero()) 
1037         return pred;
1038       pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1039       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1040       if (R && !R->isZero())
1041         return pred;
1042       pred = isSigned ?  ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1043       R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, C1, C2));
1044       if (R && !R->isZero())
1045         return pred;
1046       
1047       // If we couldn't figure it out, bail.
1048       return ICmpInst::BAD_ICMP_PREDICATE;
1049     }
1050     
1051     // If the first operand is simple, swap operands.
1052     ICmpInst::Predicate SwappedRelation = 
1053       evaluateICmpRelation(V2, V1, isSigned);
1054     if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1055       return ICmpInst::getSwappedPredicate(SwappedRelation);
1056
1057   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1058     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1059       ICmpInst::Predicate SwappedRelation = 
1060         evaluateICmpRelation(V2, V1, isSigned);
1061       if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
1062         return ICmpInst::getSwappedPredicate(SwappedRelation);
1063       else
1064         return ICmpInst::BAD_ICMP_PREDICATE;
1065     }
1066
1067     // Now we know that the RHS is a GlobalValue or simple constant,
1068     // which (since the types must match) means that it's a ConstantPointerNull.
1069     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1070       // Don't try to decide equality of aliases.
1071       if (!isa<GlobalAlias>(CPR1) && !isa<GlobalAlias>(CPR2))
1072         if (!CPR1->hasExternalWeakLinkage() || !CPR2->hasExternalWeakLinkage())
1073           return ICmpInst::ICMP_NE;
1074     } else {
1075       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1076       // GlobalVals can never be null.  Don't try to evaluate aliases.
1077       if (!CPR1->hasExternalWeakLinkage() && !isa<GlobalAlias>(CPR1))
1078         return ICmpInst::ICMP_NE;
1079     }
1080   } else {
1081     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1082     // constantexpr, a CPR, or a simple constant.
1083     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1084     const Constant *CE1Op0 = CE1->getOperand(0);
1085
1086     switch (CE1->getOpcode()) {
1087     case Instruction::Trunc:
1088     case Instruction::FPTrunc:
1089     case Instruction::FPExt:
1090     case Instruction::FPToUI:
1091     case Instruction::FPToSI:
1092       break; // We can't evaluate floating point casts or truncations.
1093
1094     case Instruction::UIToFP:
1095     case Instruction::SIToFP:
1096     case Instruction::BitCast:
1097     case Instruction::ZExt:
1098     case Instruction::SExt:
1099       // If the cast is not actually changing bits, and the second operand is a
1100       // null pointer, do the comparison with the pre-casted value.
1101       if (V2->isNullValue() &&
1102           (isa<PointerType>(CE1->getType()) || CE1->getType()->isInteger())) {
1103         bool sgnd = isSigned;
1104         if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1105         if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1106         return evaluateICmpRelation(CE1Op0,
1107                                     Constant::getNullValue(CE1Op0->getType()), 
1108                                     sgnd);
1109       }
1110
1111       // If the dest type is a pointer type, and the RHS is a constantexpr cast
1112       // from the same type as the src of the LHS, evaluate the inputs.  This is
1113       // important for things like "icmp eq (cast 4 to int*), (cast 5 to int*)",
1114       // which happens a lot in compilers with tagged integers.
1115       if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
1116         if (CE2->isCast() && isa<PointerType>(CE1->getType()) &&
1117             CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
1118             CE1->getOperand(0)->getType()->isInteger()) {
1119           bool sgnd = isSigned;
1120           if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
1121           if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
1122           return evaluateICmpRelation(CE1->getOperand(0), CE2->getOperand(0),
1123                                       sgnd);
1124         }
1125       break;
1126
1127     case Instruction::GetElementPtr:
1128       // Ok, since this is a getelementptr, we know that the constant has a
1129       // pointer type.  Check the various cases.
1130       if (isa<ConstantPointerNull>(V2)) {
1131         // If we are comparing a GEP to a null pointer, check to see if the base
1132         // of the GEP equals the null pointer.
1133         if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
1134           if (GV->hasExternalWeakLinkage())
1135             // Weak linkage GVals could be zero or not. We're comparing that
1136             // to null pointer so its greater-or-equal
1137             return isSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1138           else 
1139             // If its not weak linkage, the GVal must have a non-zero address
1140             // so the result is greater-than
1141             return isSigned ? ICmpInst::ICMP_SGT :  ICmpInst::ICMP_UGT;
1142         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1143           // If we are indexing from a null pointer, check to see if we have any
1144           // non-zero indices.
1145           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1146             if (!CE1->getOperand(i)->isNullValue())
1147               // Offsetting from null, must not be equal.
1148               return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1149           // Only zero indexes from null, must still be zero.
1150           return ICmpInst::ICMP_EQ;
1151         }
1152         // Otherwise, we can't really say if the first operand is null or not.
1153       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1154         if (isa<ConstantPointerNull>(CE1Op0)) {
1155           if (CPR2->hasExternalWeakLinkage())
1156             // Weak linkage GVals could be zero or not. We're comparing it to
1157             // a null pointer, so its less-or-equal
1158             return isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1159           else
1160             // If its not weak linkage, the GVal must have a non-zero address
1161             // so the result is less-than
1162             return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1163         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1164           if (CPR1 == CPR2) {
1165             // If this is a getelementptr of the same global, then it must be
1166             // different.  Because the types must match, the getelementptr could
1167             // only have at most one index, and because we fold getelementptr's
1168             // with a single zero index, it must be nonzero.
1169             assert(CE1->getNumOperands() == 2 &&
1170                    !CE1->getOperand(1)->isNullValue() &&
1171                    "Suprising getelementptr!");
1172             return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1173           } else {
1174             // If they are different globals, we don't know what the value is,
1175             // but they can't be equal.
1176             return ICmpInst::ICMP_NE;
1177           }
1178         }
1179       } else {
1180         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1181         const Constant *CE2Op0 = CE2->getOperand(0);
1182
1183         // There are MANY other foldings that we could perform here.  They will
1184         // probably be added on demand, as they seem needed.
1185         switch (CE2->getOpcode()) {
1186         default: break;
1187         case Instruction::GetElementPtr:
1188           // By far the most common case to handle is when the base pointers are
1189           // obviously to the same or different globals.
1190           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1191             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1192               return ICmpInst::ICMP_NE;
1193             // Ok, we know that both getelementptr instructions are based on the
1194             // same global.  From this, we can precisely determine the relative
1195             // ordering of the resultant pointers.
1196             unsigned i = 1;
1197
1198             // Compare all of the operands the GEP's have in common.
1199             gep_type_iterator GTI = gep_type_begin(CE1);
1200             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1201                  ++i, ++GTI)
1202               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1203                                  GTI.getIndexedType())) {
1204               case -1: return isSigned ? ICmpInst::ICMP_SLT:ICmpInst::ICMP_ULT;
1205               case 1:  return isSigned ? ICmpInst::ICMP_SGT:ICmpInst::ICMP_UGT;
1206               case -2: return ICmpInst::BAD_ICMP_PREDICATE;
1207               }
1208
1209             // Ok, we ran out of things they have in common.  If any leftovers
1210             // are non-zero then we have a difference, otherwise we are equal.
1211             for (; i < CE1->getNumOperands(); ++i)
1212               if (!CE1->getOperand(i)->isNullValue()) {
1213                 if (isa<ConstantInt>(CE1->getOperand(i)))
1214                   return isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1215                 else
1216                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1217               }
1218
1219             for (; i < CE2->getNumOperands(); ++i)
1220               if (!CE2->getOperand(i)->isNullValue()) {
1221                 if (isa<ConstantInt>(CE2->getOperand(i)))
1222                   return isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1223                 else
1224                   return ICmpInst::BAD_ICMP_PREDICATE; // Might be equal.
1225               }
1226             return ICmpInst::ICMP_EQ;
1227           }
1228         }
1229       }
1230     default:
1231       break;
1232     }
1233   }
1234
1235   return ICmpInst::BAD_ICMP_PREDICATE;
1236 }
1237
1238 Constant *llvm::ConstantFoldCompareInstruction(unsigned short pred, 
1239                                                const Constant *C1, 
1240                                                const Constant *C2) {
1241   // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
1242   if (pred == FCmpInst::FCMP_FALSE) {
1243     if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1244       return Constant::getNullValue(VectorType::getInteger(VT));
1245     else
1246       return ConstantInt::getFalse();
1247   }
1248   
1249   if (pred == FCmpInst::FCMP_TRUE) {
1250     if (const VectorType *VT = dyn_cast<VectorType>(C1->getType()))
1251       return Constant::getAllOnesValue(VectorType::getInteger(VT));
1252     else
1253       return ConstantInt::getTrue();
1254   }
1255       
1256   // Handle some degenerate cases first
1257   if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
1258     // vicmp/vfcmp -> [vector] undef
1259     if (const VectorType *VTy = dyn_cast<VectorType>(C1->getType()))
1260       return UndefValue::get(VectorType::getInteger(VTy));
1261     
1262     // icmp/fcmp -> i1 undef
1263     return UndefValue::get(Type::Int1Ty);
1264   }
1265
1266   // No compile-time operations on this type yet.
1267   if (C1->getType() == Type::PPC_FP128Ty)
1268     return 0;
1269
1270   // icmp eq/ne(null,GV) -> false/true
1271   if (C1->isNullValue()) {
1272     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
1273       // Don't try to evaluate aliases.  External weak GV can be null.
1274       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1275         if (pred == ICmpInst::ICMP_EQ)
1276           return ConstantInt::getFalse();
1277         else if (pred == ICmpInst::ICMP_NE)
1278           return ConstantInt::getTrue();
1279       }
1280   // icmp eq/ne(GV,null) -> false/true
1281   } else if (C2->isNullValue()) {
1282     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1))
1283       // Don't try to evaluate aliases.  External weak GV can be null.
1284       if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage()) {
1285         if (pred == ICmpInst::ICMP_EQ)
1286           return ConstantInt::getFalse();
1287         else if (pred == ICmpInst::ICMP_NE)
1288           return ConstantInt::getTrue();
1289       }
1290   }
1291
1292   if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
1293     APInt V1 = cast<ConstantInt>(C1)->getValue();
1294     APInt V2 = cast<ConstantInt>(C2)->getValue();
1295     switch (pred) {
1296     default: assert(0 && "Invalid ICmp Predicate"); return 0;
1297     case ICmpInst::ICMP_EQ: return ConstantInt::get(Type::Int1Ty, V1 == V2);
1298     case ICmpInst::ICMP_NE: return ConstantInt::get(Type::Int1Ty, V1 != V2);
1299     case ICmpInst::ICMP_SLT:return ConstantInt::get(Type::Int1Ty, V1.slt(V2));
1300     case ICmpInst::ICMP_SGT:return ConstantInt::get(Type::Int1Ty, V1.sgt(V2));
1301     case ICmpInst::ICMP_SLE:return ConstantInt::get(Type::Int1Ty, V1.sle(V2));
1302     case ICmpInst::ICMP_SGE:return ConstantInt::get(Type::Int1Ty, V1.sge(V2));
1303     case ICmpInst::ICMP_ULT:return ConstantInt::get(Type::Int1Ty, V1.ult(V2));
1304     case ICmpInst::ICMP_UGT:return ConstantInt::get(Type::Int1Ty, V1.ugt(V2));
1305     case ICmpInst::ICMP_ULE:return ConstantInt::get(Type::Int1Ty, V1.ule(V2));
1306     case ICmpInst::ICMP_UGE:return ConstantInt::get(Type::Int1Ty, V1.uge(V2));
1307     }
1308   } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
1309     APFloat C1V = cast<ConstantFP>(C1)->getValueAPF();
1310     APFloat C2V = cast<ConstantFP>(C2)->getValueAPF();
1311     APFloat::cmpResult R = C1V.compare(C2V);
1312     switch (pred) {
1313     default: assert(0 && "Invalid FCmp Predicate"); return 0;
1314     case FCmpInst::FCMP_FALSE: return ConstantInt::getFalse();
1315     case FCmpInst::FCMP_TRUE:  return ConstantInt::getTrue();
1316     case FCmpInst::FCMP_UNO:
1317       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered);
1318     case FCmpInst::FCMP_ORD:
1319       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpUnordered);
1320     case FCmpInst::FCMP_UEQ:
1321       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1322                                             R==APFloat::cmpEqual);
1323     case FCmpInst::FCMP_OEQ:   
1324       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpEqual);
1325     case FCmpInst::FCMP_UNE:
1326       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpEqual);
1327     case FCmpInst::FCMP_ONE:   
1328       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1329                                             R==APFloat::cmpGreaterThan);
1330     case FCmpInst::FCMP_ULT: 
1331       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1332                                             R==APFloat::cmpLessThan);
1333     case FCmpInst::FCMP_OLT:   
1334       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan);
1335     case FCmpInst::FCMP_UGT:
1336       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpUnordered ||
1337                                             R==APFloat::cmpGreaterThan);
1338     case FCmpInst::FCMP_OGT:
1339       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan);
1340     case FCmpInst::FCMP_ULE:
1341       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpGreaterThan);
1342     case FCmpInst::FCMP_OLE: 
1343       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpLessThan ||
1344                                             R==APFloat::cmpEqual);
1345     case FCmpInst::FCMP_UGE:
1346       return ConstantInt::get(Type::Int1Ty, R!=APFloat::cmpLessThan);
1347     case FCmpInst::FCMP_OGE: 
1348       return ConstantInt::get(Type::Int1Ty, R==APFloat::cmpGreaterThan ||
1349                                             R==APFloat::cmpEqual);
1350     }
1351   } else if (const ConstantVector *CP1 = dyn_cast<ConstantVector>(C1)) {
1352     if (const ConstantVector *CP2 = dyn_cast<ConstantVector>(C2)) {
1353       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) {
1354         for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1355           Constant *C = ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ,
1356                                               CP1->getOperand(i),
1357                                               CP2->getOperand(i));
1358           if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1359             return CB;
1360         }
1361         // Otherwise, could not decide from any element pairs.
1362         return 0;
1363       } else if (pred == ICmpInst::ICMP_EQ) {
1364         for (unsigned i = 0, e = CP1->getNumOperands(); i != e; ++i) {
1365           Constant *C = ConstantExpr::getICmp(ICmpInst::ICMP_EQ,
1366                                               CP1->getOperand(i),
1367                                               CP2->getOperand(i));
1368           if (ConstantInt *CB = dyn_cast<ConstantInt>(C))
1369             return CB;
1370         }
1371         // Otherwise, could not decide from any element pairs.
1372         return 0;
1373       }
1374     }
1375   }
1376
1377   if (C1->getType()->isFloatingPoint()) {
1378     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1379     switch (evaluateFCmpRelation(C1, C2)) {
1380     default: assert(0 && "Unknown relation!");
1381     case FCmpInst::FCMP_UNO:
1382     case FCmpInst::FCMP_ORD:
1383     case FCmpInst::FCMP_UEQ:
1384     case FCmpInst::FCMP_UNE:
1385     case FCmpInst::FCMP_ULT:
1386     case FCmpInst::FCMP_UGT:
1387     case FCmpInst::FCMP_ULE:
1388     case FCmpInst::FCMP_UGE:
1389     case FCmpInst::FCMP_TRUE:
1390     case FCmpInst::FCMP_FALSE:
1391     case FCmpInst::BAD_FCMP_PREDICATE:
1392       break; // Couldn't determine anything about these constants.
1393     case FCmpInst::FCMP_OEQ: // We know that C1 == C2
1394       Result = (pred == FCmpInst::FCMP_UEQ || pred == FCmpInst::FCMP_OEQ ||
1395                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE ||
1396                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1397       break;
1398     case FCmpInst::FCMP_OLT: // We know that C1 < C2
1399       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1400                 pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT ||
1401                 pred == FCmpInst::FCMP_ULE || pred == FCmpInst::FCMP_OLE);
1402       break;
1403     case FCmpInst::FCMP_OGT: // We know that C1 > C2
1404       Result = (pred == FCmpInst::FCMP_UNE || pred == FCmpInst::FCMP_ONE ||
1405                 pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT ||
1406                 pred == FCmpInst::FCMP_UGE || pred == FCmpInst::FCMP_OGE);
1407       break;
1408     case FCmpInst::FCMP_OLE: // We know that C1 <= C2
1409       // We can only partially decide this relation.
1410       if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1411         Result = 0;
1412       else if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1413         Result = 1;
1414       break;
1415     case FCmpInst::FCMP_OGE: // We known that C1 >= C2
1416       // We can only partially decide this relation.
1417       if (pred == FCmpInst::FCMP_ULT || pred == FCmpInst::FCMP_OLT) 
1418         Result = 0;
1419       else if (pred == FCmpInst::FCMP_UGT || pred == FCmpInst::FCMP_OGT) 
1420         Result = 1;
1421       break;
1422     case ICmpInst::ICMP_NE: // We know that C1 != C2
1423       // We can only partially decide this relation.
1424       if (pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ) 
1425         Result = 0;
1426       else if (pred == FCmpInst::FCMP_ONE || pred == FCmpInst::FCMP_UNE) 
1427         Result = 1;
1428       break;
1429     }
1430     
1431     // If we evaluated the result, return it now.
1432     if (Result != -1) {
1433       if (const VectorType *VT = dyn_cast<VectorType>(C1->getType())) {
1434         if (Result == 0)
1435           return Constant::getNullValue(VectorType::getInteger(VT));
1436         else
1437           return Constant::getAllOnesValue(VectorType::getInteger(VT));
1438       }
1439       return ConstantInt::get(Type::Int1Ty, Result);
1440     }
1441     
1442   } else {
1443     // Evaluate the relation between the two constants, per the predicate.
1444     int Result = -1;  // -1 = unknown, 0 = known false, 1 = known true.
1445     switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(pred))) {
1446     default: assert(0 && "Unknown relational!");
1447     case ICmpInst::BAD_ICMP_PREDICATE:
1448       break;  // Couldn't determine anything about these constants.
1449     case ICmpInst::ICMP_EQ:   // We know the constants are equal!
1450       // If we know the constants are equal, we can decide the result of this
1451       // computation precisely.
1452       Result = (pred == ICmpInst::ICMP_EQ  ||
1453                 pred == ICmpInst::ICMP_ULE ||
1454                 pred == ICmpInst::ICMP_SLE ||
1455                 pred == ICmpInst::ICMP_UGE ||
1456                 pred == ICmpInst::ICMP_SGE);
1457       break;
1458     case ICmpInst::ICMP_ULT:
1459       // If we know that C1 < C2, we can decide the result of this computation
1460       // precisely.
1461       Result = (pred == ICmpInst::ICMP_ULT ||
1462                 pred == ICmpInst::ICMP_NE  ||
1463                 pred == ICmpInst::ICMP_ULE);
1464       break;
1465     case ICmpInst::ICMP_SLT:
1466       // If we know that C1 < C2, we can decide the result of this computation
1467       // precisely.
1468       Result = (pred == ICmpInst::ICMP_SLT ||
1469                 pred == ICmpInst::ICMP_NE  ||
1470                 pred == ICmpInst::ICMP_SLE);
1471       break;
1472     case ICmpInst::ICMP_UGT:
1473       // If we know that C1 > C2, we can decide the result of this computation
1474       // precisely.
1475       Result = (pred == ICmpInst::ICMP_UGT ||
1476                 pred == ICmpInst::ICMP_NE  ||
1477                 pred == ICmpInst::ICMP_UGE);
1478       break;
1479     case ICmpInst::ICMP_SGT:
1480       // If we know that C1 > C2, we can decide the result of this computation
1481       // precisely.
1482       Result = (pred == ICmpInst::ICMP_SGT ||
1483                 pred == ICmpInst::ICMP_NE  ||
1484                 pred == ICmpInst::ICMP_SGE);
1485       break;
1486     case ICmpInst::ICMP_ULE:
1487       // If we know that C1 <= C2, we can only partially decide this relation.
1488       if (pred == ICmpInst::ICMP_UGT) Result = 0;
1489       if (pred == ICmpInst::ICMP_ULT) Result = 1;
1490       break;
1491     case ICmpInst::ICMP_SLE:
1492       // If we know that C1 <= C2, we can only partially decide this relation.
1493       if (pred == ICmpInst::ICMP_SGT) Result = 0;
1494       if (pred == ICmpInst::ICMP_SLT) Result = 1;
1495       break;
1496
1497     case ICmpInst::ICMP_UGE:
1498       // If we know that C1 >= C2, we can only partially decide this relation.
1499       if (pred == ICmpInst::ICMP_ULT) Result = 0;
1500       if (pred == ICmpInst::ICMP_UGT) Result = 1;
1501       break;
1502     case ICmpInst::ICMP_SGE:
1503       // If we know that C1 >= C2, we can only partially decide this relation.
1504       if (pred == ICmpInst::ICMP_SLT) Result = 0;
1505       if (pred == ICmpInst::ICMP_SGT) Result = 1;
1506       break;
1507
1508     case ICmpInst::ICMP_NE:
1509       // If we know that C1 != C2, we can only partially decide this relation.
1510       if (pred == ICmpInst::ICMP_EQ) Result = 0;
1511       if (pred == ICmpInst::ICMP_NE) Result = 1;
1512       break;
1513     }
1514     
1515     // If we evaluated the result, return it now.
1516     if (Result != -1) {
1517       if (const VectorType *VT = dyn_cast<VectorType>(C1->getType())) {
1518         if (Result == 0)
1519           return Constant::getNullValue(VT);
1520         else
1521           return Constant::getAllOnesValue(VT);
1522       }
1523       return ConstantInt::get(Type::Int1Ty, Result);
1524     }
1525     
1526     if (!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) {
1527       // If C2 is a constant expr and C1 isn't, flop them around and fold the
1528       // other way if possible.
1529       switch (pred) {
1530       case ICmpInst::ICMP_EQ:
1531       case ICmpInst::ICMP_NE:
1532         // No change of predicate required.
1533         return ConstantFoldCompareInstruction(pred, C2, C1);
1534
1535       case ICmpInst::ICMP_ULT:
1536       case ICmpInst::ICMP_SLT:
1537       case ICmpInst::ICMP_UGT:
1538       case ICmpInst::ICMP_SGT:
1539       case ICmpInst::ICMP_ULE:
1540       case ICmpInst::ICMP_SLE:
1541       case ICmpInst::ICMP_UGE:
1542       case ICmpInst::ICMP_SGE:
1543         // Change the predicate as necessary to swap the operands.
1544         pred = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)pred);
1545         return ConstantFoldCompareInstruction(pred, C2, C1);
1546
1547       default:  // These predicates cannot be flopped around.
1548         break;
1549       }
1550     }
1551   }
1552   return 0;
1553 }
1554
1555 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1556                                           Constant* const *Idxs,
1557                                           unsigned NumIdx) {
1558   if (NumIdx == 0 ||
1559       (NumIdx == 1 && Idxs[0]->isNullValue()))
1560     return const_cast<Constant*>(C);
1561
1562   if (isa<UndefValue>(C)) {
1563     const PointerType *Ptr = cast<PointerType>(C->getType());
1564     const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1565                                                        (Value **)Idxs,
1566                                                        (Value **)Idxs+NumIdx);
1567     assert(Ty != 0 && "Invalid indices for GEP!");
1568     return UndefValue::get(PointerType::get(Ty, Ptr->getAddressSpace()));
1569   }
1570
1571   Constant *Idx0 = Idxs[0];
1572   if (C->isNullValue()) {
1573     bool isNull = true;
1574     for (unsigned i = 0, e = NumIdx; i != e; ++i)
1575       if (!Idxs[i]->isNullValue()) {
1576         isNull = false;
1577         break;
1578       }
1579     if (isNull) {
1580       const PointerType *Ptr = cast<PointerType>(C->getType());
1581       const Type *Ty = GetElementPtrInst::getIndexedType(Ptr,
1582                                                          (Value**)Idxs,
1583                                                          (Value**)Idxs+NumIdx);
1584       assert(Ty != 0 && "Invalid indices for GEP!");
1585       return 
1586         ConstantPointerNull::get(PointerType::get(Ty,Ptr->getAddressSpace()));
1587     }
1588   }
1589
1590   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1591     // Combine Indices - If the source pointer to this getelementptr instruction
1592     // is a getelementptr instruction, combine the indices of the two
1593     // getelementptr instructions into a single instruction.
1594     //
1595     if (CE->getOpcode() == Instruction::GetElementPtr) {
1596       const Type *LastTy = 0;
1597       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1598            I != E; ++I)
1599         LastTy = *I;
1600
1601       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1602         SmallVector<Value*, 16> NewIndices;
1603         NewIndices.reserve(NumIdx + CE->getNumOperands());
1604         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1605           NewIndices.push_back(CE->getOperand(i));
1606
1607         // Add the last index of the source with the first index of the new GEP.
1608         // Make sure to handle the case when they are actually different types.
1609         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1610         // Otherwise it must be an array.
1611         if (!Idx0->isNullValue()) {
1612           const Type *IdxTy = Combined->getType();
1613           if (IdxTy != Idx0->getType()) {
1614             Constant *C1 = ConstantExpr::getSExtOrBitCast(Idx0, Type::Int64Ty);
1615             Constant *C2 = ConstantExpr::getSExtOrBitCast(Combined, 
1616                                                           Type::Int64Ty);
1617             Combined = ConstantExpr::get(Instruction::Add, C1, C2);
1618           } else {
1619             Combined =
1620               ConstantExpr::get(Instruction::Add, Idx0, Combined);
1621           }
1622         }
1623
1624         NewIndices.push_back(Combined);
1625         NewIndices.insert(NewIndices.end(), Idxs+1, Idxs+NumIdx);
1626         return ConstantExpr::getGetElementPtr(CE->getOperand(0), &NewIndices[0],
1627                                               NewIndices.size());
1628       }
1629     }
1630
1631     // Implement folding of:
1632     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1633     //                        long 0, long 0)
1634     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1635     //
1636     if (CE->isCast() && NumIdx > 1 && Idx0->isNullValue()) {
1637       if (const PointerType *SPT =
1638           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1639         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1640           if (const ArrayType *CAT =
1641         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1642             if (CAT->getElementType() == SAT->getElementType())
1643               return ConstantExpr::getGetElementPtr(
1644                       (Constant*)CE->getOperand(0), Idxs, NumIdx);
1645     }
1646     
1647     // Fold: getelementptr (i8* inttoptr (i64 1 to i8*), i32 -1)
1648     // Into: inttoptr (i64 0 to i8*)
1649     // This happens with pointers to member functions in C++.
1650     if (CE->getOpcode() == Instruction::IntToPtr && NumIdx == 1 &&
1651         isa<ConstantInt>(CE->getOperand(0)) && isa<ConstantInt>(Idxs[0]) &&
1652         cast<PointerType>(CE->getType())->getElementType() == Type::Int8Ty) {
1653       Constant *Base = CE->getOperand(0);
1654       Constant *Offset = Idxs[0];
1655       
1656       // Convert the smaller integer to the larger type.
1657       if (Offset->getType()->getPrimitiveSizeInBits() < 
1658           Base->getType()->getPrimitiveSizeInBits())
1659         Offset = ConstantExpr::getSExt(Offset, Base->getType());
1660       else if (Base->getType()->getPrimitiveSizeInBits() <
1661                Offset->getType()->getPrimitiveSizeInBits())
1662         Base = ConstantExpr::getZExt(Base, Base->getType());
1663       
1664       Base = ConstantExpr::getAdd(Base, Offset);
1665       return ConstantExpr::getIntToPtr(Base, CE->getType());
1666     }
1667   }
1668   return 0;
1669 }
1670