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