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