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