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