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