772b79a29a4a276ed5c2e3f42399cae37acc50be
[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/GetElementPtrTypeIterator.h"
27 #include <cmath>
28 using namespace llvm;
29
30 namespace {
31   struct ConstRules {
32     ConstRules() {}
33     
34     // Binary Operators...
35     virtual Constant *add(const Constant *V1, const Constant *V2) const = 0;
36     virtual Constant *sub(const Constant *V1, const Constant *V2) const = 0;
37     virtual Constant *mul(const Constant *V1, const Constant *V2) const = 0;
38     virtual Constant *div(const Constant *V1, const Constant *V2) const = 0;
39     virtual Constant *rem(const Constant *V1, const Constant *V2) const = 0;
40     virtual Constant *op_and(const Constant *V1, const Constant *V2) const = 0;
41     virtual Constant *op_or (const Constant *V1, const Constant *V2) const = 0;
42     virtual Constant *op_xor(const Constant *V1, const Constant *V2) const = 0;
43     virtual Constant *shl(const Constant *V1, const Constant *V2) const = 0;
44     virtual Constant *shr(const Constant *V1, const Constant *V2) const = 0;
45     virtual Constant *lessthan(const Constant *V1, const Constant *V2) const =0;
46     virtual Constant *equalto(const Constant *V1, const Constant *V2) const = 0;
47
48     // Casting operators.
49     virtual Constant *castToBool  (const Constant *V) const = 0;
50     virtual Constant *castToSByte (const Constant *V) const = 0;
51     virtual Constant *castToUByte (const Constant *V) const = 0;
52     virtual Constant *castToShort (const Constant *V) const = 0;
53     virtual Constant *castToUShort(const Constant *V) const = 0;
54     virtual Constant *castToInt   (const Constant *V) const = 0;
55     virtual Constant *castToUInt  (const Constant *V) const = 0;
56     virtual Constant *castToLong  (const Constant *V) const = 0;
57     virtual Constant *castToULong (const Constant *V) const = 0;
58     virtual Constant *castToFloat (const Constant *V) const = 0;
59     virtual Constant *castToDouble(const Constant *V) const = 0;
60     virtual Constant *castToPointer(const Constant *V,
61                                     const PointerType *Ty) const = 0;
62     
63     // ConstRules::get - Return an instance of ConstRules for the specified
64     // constant operands.
65     //
66     static ConstRules &get(const Constant *V1, const Constant *V2);
67   private:
68     ConstRules(const ConstRules &);             // Do not implement
69     ConstRules &operator=(const ConstRules &);  // Do not implement
70   };
71 }
72
73
74 //===----------------------------------------------------------------------===//
75 //                             TemplateRules Class
76 //===----------------------------------------------------------------------===//
77 //
78 // TemplateRules - Implement a subclass of ConstRules that provides all 
79 // operations as noops.  All other rules classes inherit from this class so 
80 // that if functionality is needed in the future, it can simply be added here 
81 // and to ConstRules without changing anything else...
82 // 
83 // This class also provides subclasses with typesafe implementations of methods
84 // so that don't have to do type casting.
85 //
86 template<class ArgType, class SubClassName>
87 class TemplateRules : public ConstRules {
88
89   //===--------------------------------------------------------------------===//
90   // Redirecting functions that cast to the appropriate types
91   //===--------------------------------------------------------------------===//
92
93   virtual Constant *add(const Constant *V1, const Constant *V2) const { 
94     return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);  
95   }
96   virtual Constant *sub(const Constant *V1, const Constant *V2) const { 
97     return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);  
98   }
99   virtual Constant *mul(const Constant *V1, const Constant *V2) const { 
100     return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);  
101   }
102   virtual Constant *div(const Constant *V1, const Constant *V2) const { 
103     return SubClassName::Div((const ArgType *)V1, (const ArgType *)V2);  
104   }
105   virtual Constant *rem(const Constant *V1, const Constant *V2) const { 
106     return SubClassName::Rem((const ArgType *)V1, (const ArgType *)V2);  
107   }
108   virtual Constant *op_and(const Constant *V1, const Constant *V2) const { 
109     return SubClassName::And((const ArgType *)V1, (const ArgType *)V2);  
110   }
111   virtual Constant *op_or(const Constant *V1, const Constant *V2) const { 
112     return SubClassName::Or((const ArgType *)V1, (const ArgType *)V2);  
113   }
114   virtual Constant *op_xor(const Constant *V1, const Constant *V2) const { 
115     return SubClassName::Xor((const ArgType *)V1, (const ArgType *)V2);  
116   }
117   virtual Constant *shl(const Constant *V1, const Constant *V2) const { 
118     return SubClassName::Shl((const ArgType *)V1, (const ArgType *)V2);  
119   }
120   virtual Constant *shr(const Constant *V1, const Constant *V2) const { 
121     return SubClassName::Shr((const ArgType *)V1, (const ArgType *)V2);  
122   }
123
124   virtual Constant *lessthan(const Constant *V1, const Constant *V2) const { 
125     return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
126   }
127   virtual Constant *equalto(const Constant *V1, const Constant *V2) const { 
128     return SubClassName::EqualTo((const ArgType *)V1, (const ArgType *)V2);
129   }
130
131   // Casting operators.  ick
132   virtual Constant *castToBool(const Constant *V) const {
133     return SubClassName::CastToBool((const ArgType*)V);
134   }
135   virtual Constant *castToSByte(const Constant *V) const {
136     return SubClassName::CastToSByte((const ArgType*)V);
137   }
138   virtual Constant *castToUByte(const Constant *V) const {
139     return SubClassName::CastToUByte((const ArgType*)V);
140   }
141   virtual Constant *castToShort(const Constant *V) const {
142     return SubClassName::CastToShort((const ArgType*)V);
143   }
144   virtual Constant *castToUShort(const Constant *V) const {
145     return SubClassName::CastToUShort((const ArgType*)V);
146   }
147   virtual Constant *castToInt(const Constant *V) const {
148     return SubClassName::CastToInt((const ArgType*)V);
149   }
150   virtual Constant *castToUInt(const Constant *V) const {
151     return SubClassName::CastToUInt((const ArgType*)V);
152   }
153   virtual Constant *castToLong(const Constant *V) const {
154     return SubClassName::CastToLong((const ArgType*)V);
155   }
156   virtual Constant *castToULong(const Constant *V) const {
157     return SubClassName::CastToULong((const ArgType*)V);
158   }
159   virtual Constant *castToFloat(const Constant *V) const {
160     return SubClassName::CastToFloat((const ArgType*)V);
161   }
162   virtual Constant *castToDouble(const Constant *V) const {
163     return SubClassName::CastToDouble((const ArgType*)V);
164   }
165   virtual Constant *castToPointer(const Constant *V, 
166                                   const PointerType *Ty) const {
167     return SubClassName::CastToPointer((const ArgType*)V, Ty);
168   }
169
170   //===--------------------------------------------------------------------===//
171   // Default "noop" implementations
172   //===--------------------------------------------------------------------===//
173
174   static Constant *Add(const ArgType *V1, const ArgType *V2) { return 0; }
175   static Constant *Sub(const ArgType *V1, const ArgType *V2) { return 0; }
176   static Constant *Mul(const ArgType *V1, const ArgType *V2) { return 0; }
177   static Constant *Div(const ArgType *V1, const ArgType *V2) { return 0; }
178   static Constant *Rem(const ArgType *V1, const ArgType *V2) { return 0; }
179   static Constant *And(const ArgType *V1, const ArgType *V2) { return 0; }
180   static Constant *Or (const ArgType *V1, const ArgType *V2) { return 0; }
181   static Constant *Xor(const ArgType *V1, const ArgType *V2) { return 0; }
182   static Constant *Shl(const ArgType *V1, const ArgType *V2) { return 0; }
183   static Constant *Shr(const ArgType *V1, const ArgType *V2) { return 0; }
184   static Constant *LessThan(const ArgType *V1, const ArgType *V2) {
185     return 0;
186   }
187   static Constant *EqualTo(const ArgType *V1, const ArgType *V2) {
188     return 0;
189   }
190
191   // Casting operators.  ick
192   static Constant *CastToBool  (const Constant *V) { return 0; }
193   static Constant *CastToSByte (const Constant *V) { return 0; }
194   static Constant *CastToUByte (const Constant *V) { return 0; }
195   static Constant *CastToShort (const Constant *V) { return 0; }
196   static Constant *CastToUShort(const Constant *V) { return 0; }
197   static Constant *CastToInt   (const Constant *V) { return 0; }
198   static Constant *CastToUInt  (const Constant *V) { return 0; }
199   static Constant *CastToLong  (const Constant *V) { return 0; }
200   static Constant *CastToULong (const Constant *V) { return 0; }
201   static Constant *CastToFloat (const Constant *V) { return 0; }
202   static Constant *CastToDouble(const Constant *V) { return 0; }
203   static Constant *CastToPointer(const Constant *,
204                                  const PointerType *) {return 0;}
205 };
206
207
208
209 //===----------------------------------------------------------------------===//
210 //                             EmptyRules Class
211 //===----------------------------------------------------------------------===//
212 //
213 // EmptyRules provides a concrete base class of ConstRules that does nothing
214 //
215 struct EmptyRules : public TemplateRules<Constant, EmptyRules> {
216   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
217     if (V1 == V2) return ConstantBool::True;
218     return 0;
219   }
220 };
221
222
223
224 //===----------------------------------------------------------------------===//
225 //                              BoolRules Class
226 //===----------------------------------------------------------------------===//
227 //
228 // BoolRules provides a concrete base class of ConstRules for the 'bool' type.
229 //
230 struct BoolRules : public TemplateRules<ConstantBool, BoolRules> {
231
232   static Constant *LessThan(const ConstantBool *V1, const ConstantBool *V2){
233     return ConstantBool::get(V1->getValue() < V2->getValue());
234   }
235
236   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
237     return ConstantBool::get(V1 == V2);
238   }
239
240   static Constant *And(const ConstantBool *V1, const ConstantBool *V2) {
241     return ConstantBool::get(V1->getValue() & V2->getValue());
242   }
243
244   static Constant *Or(const ConstantBool *V1, const ConstantBool *V2) {
245     return ConstantBool::get(V1->getValue() | V2->getValue());
246   }
247
248   static Constant *Xor(const ConstantBool *V1, const ConstantBool *V2) {
249     return ConstantBool::get(V1->getValue() ^ V2->getValue());
250   }
251
252   // Casting operators.  ick
253 #define DEF_CAST(TYPE, CLASS, CTYPE) \
254   static Constant *CastTo##TYPE  (const ConstantBool *V) {    \
255     return CLASS::get(Type::TYPE##Ty, (CTYPE)(bool)V->getValue()); \
256   }
257
258   DEF_CAST(Bool  , ConstantBool, bool)
259   DEF_CAST(SByte , ConstantSInt, signed char)
260   DEF_CAST(UByte , ConstantUInt, unsigned char)
261   DEF_CAST(Short , ConstantSInt, signed short)
262   DEF_CAST(UShort, ConstantUInt, unsigned short)
263   DEF_CAST(Int   , ConstantSInt, signed int)
264   DEF_CAST(UInt  , ConstantUInt, unsigned int)
265   DEF_CAST(Long  , ConstantSInt, int64_t)
266   DEF_CAST(ULong , ConstantUInt, uint64_t)
267   DEF_CAST(Float , ConstantFP  , float)
268   DEF_CAST(Double, ConstantFP  , double)
269 #undef DEF_CAST
270 };
271
272
273 //===----------------------------------------------------------------------===//
274 //                            NullPointerRules Class
275 //===----------------------------------------------------------------------===//
276 //
277 // NullPointerRules provides a concrete base class of ConstRules for null
278 // pointers.
279 //
280 struct NullPointerRules : public TemplateRules<ConstantPointerNull,
281                                                NullPointerRules> {
282   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
283     return ConstantBool::True;  // Null pointers are always equal
284   }
285   static Constant *CastToBool(const Constant *V) {
286     return ConstantBool::False;
287   }
288   static Constant *CastToSByte (const Constant *V) {
289     return ConstantSInt::get(Type::SByteTy, 0);
290   }
291   static Constant *CastToUByte (const Constant *V) {
292     return ConstantUInt::get(Type::UByteTy, 0);
293   }
294   static Constant *CastToShort (const Constant *V) {
295     return ConstantSInt::get(Type::ShortTy, 0);
296   }
297   static Constant *CastToUShort(const Constant *V) {
298     return ConstantUInt::get(Type::UShortTy, 0);
299   }
300   static Constant *CastToInt   (const Constant *V) {
301     return ConstantSInt::get(Type::IntTy, 0);
302   }
303   static Constant *CastToUInt  (const Constant *V) {
304     return ConstantUInt::get(Type::UIntTy, 0);
305   }
306   static Constant *CastToLong  (const Constant *V) {
307     return ConstantSInt::get(Type::LongTy, 0);
308   }
309   static Constant *CastToULong (const Constant *V) {
310     return ConstantUInt::get(Type::ULongTy, 0);
311   }
312   static Constant *CastToFloat (const Constant *V) {
313     return ConstantFP::get(Type::FloatTy, 0);
314   }
315   static Constant *CastToDouble(const Constant *V) {
316     return ConstantFP::get(Type::DoubleTy, 0);
317   }
318
319   static Constant *CastToPointer(const ConstantPointerNull *V,
320                                  const PointerType *PTy) {
321     return ConstantPointerNull::get(PTy);
322   }
323 };
324
325
326 //===----------------------------------------------------------------------===//
327 //                             DirectRules Class
328 //===----------------------------------------------------------------------===//
329 //
330 // DirectRules provides a concrete base classes of ConstRules for a variety of
331 // different types.  This allows the C++ compiler to automatically generate our
332 // constant handling operations in a typesafe and accurate manner.
333 //
334 template<class ConstantClass, class BuiltinType, Type **Ty, class SuperClass>
335 struct DirectRules : public TemplateRules<ConstantClass, SuperClass> {
336   static Constant *Add(const ConstantClass *V1, const ConstantClass *V2) {
337     BuiltinType R = (BuiltinType)V1->getValue() + (BuiltinType)V2->getValue();
338     return ConstantClass::get(*Ty, R);
339   }
340
341   static Constant *Sub(const ConstantClass *V1, const ConstantClass *V2) {
342     BuiltinType R = (BuiltinType)V1->getValue() - (BuiltinType)V2->getValue();
343     return ConstantClass::get(*Ty, R);
344   }
345
346   static Constant *Mul(const ConstantClass *V1, const ConstantClass *V2) {
347     BuiltinType R = (BuiltinType)V1->getValue() * (BuiltinType)V2->getValue();
348     return ConstantClass::get(*Ty, R);
349   }
350
351   static Constant *Div(const ConstantClass *V1, const ConstantClass *V2) {
352     if (V2->isNullValue()) return 0;
353     BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
354     return ConstantClass::get(*Ty, R);
355   }
356
357   static Constant *LessThan(const ConstantClass *V1, const ConstantClass *V2) {
358     bool R = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
359     return ConstantBool::get(R);
360   } 
361
362   static Constant *EqualTo(const ConstantClass *V1, const ConstantClass *V2) {
363     bool R = (BuiltinType)V1->getValue() == (BuiltinType)V2->getValue();
364     return ConstantBool::get(R);
365   }
366
367   static Constant *CastToPointer(const ConstantClass *V,
368                                  const PointerType *PTy) {
369     if (V->isNullValue())    // Is it a FP or Integral null value?
370       return ConstantPointerNull::get(PTy);
371     return 0;  // Can't const prop other types of pointers
372   }
373
374   // Casting operators.  ick
375 #define DEF_CAST(TYPE, CLASS, CTYPE) \
376   static Constant *CastTo##TYPE  (const ConstantClass *V) {    \
377     return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
378   }
379
380   DEF_CAST(Bool  , ConstantBool, bool)
381   DEF_CAST(SByte , ConstantSInt, signed char)
382   DEF_CAST(UByte , ConstantUInt, unsigned char)
383   DEF_CAST(Short , ConstantSInt, signed short)
384   DEF_CAST(UShort, ConstantUInt, unsigned short)
385   DEF_CAST(Int   , ConstantSInt, signed int)
386   DEF_CAST(UInt  , ConstantUInt, unsigned int)
387   DEF_CAST(Long  , ConstantSInt, int64_t)
388   DEF_CAST(ULong , ConstantUInt, uint64_t)
389   DEF_CAST(Float , ConstantFP  , float)
390   DEF_CAST(Double, ConstantFP  , double)
391 #undef DEF_CAST
392 };
393
394
395 //===----------------------------------------------------------------------===//
396 //                           DirectIntRules Class
397 //===----------------------------------------------------------------------===//
398 //
399 // DirectIntRules provides implementations of functions that are valid on
400 // integer types, but not all types in general.
401 //
402 template <class ConstantClass, class BuiltinType, Type **Ty>
403 struct DirectIntRules
404   : public DirectRules<ConstantClass, BuiltinType, Ty,
405                        DirectIntRules<ConstantClass, BuiltinType, Ty> > {
406
407   static Constant *Div(const ConstantClass *V1, const ConstantClass *V2) {
408     if (V2->isNullValue()) return 0;
409     if (V2->isAllOnesValue() &&              // MIN_INT / -1
410         (BuiltinType)V1->getValue() == -(BuiltinType)V1->getValue())
411       return 0;
412     BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
413     return ConstantClass::get(*Ty, R);
414   }
415
416   static Constant *Rem(const ConstantClass *V1,
417                        const ConstantClass *V2) {
418     if (V2->isNullValue()) return 0;         // X / 0
419     if (V2->isAllOnesValue() &&              // MIN_INT / -1
420         (BuiltinType)V1->getValue() == -(BuiltinType)V1->getValue())
421       return 0;
422     BuiltinType R = (BuiltinType)V1->getValue() % (BuiltinType)V2->getValue();
423     return ConstantClass::get(*Ty, R);
424   }
425
426   static Constant *And(const ConstantClass *V1, const ConstantClass *V2) {
427     BuiltinType R = (BuiltinType)V1->getValue() & (BuiltinType)V2->getValue();
428     return ConstantClass::get(*Ty, R);
429   }
430   static Constant *Or(const ConstantClass *V1, const ConstantClass *V2) {
431     BuiltinType R = (BuiltinType)V1->getValue() | (BuiltinType)V2->getValue();
432     return ConstantClass::get(*Ty, R);
433   }
434   static Constant *Xor(const ConstantClass *V1, const ConstantClass *V2) {
435     BuiltinType R = (BuiltinType)V1->getValue() ^ (BuiltinType)V2->getValue();
436     return ConstantClass::get(*Ty, R);
437   }
438
439   static Constant *Shl(const ConstantClass *V1, const ConstantClass *V2) {
440     BuiltinType R = (BuiltinType)V1->getValue() << (BuiltinType)V2->getValue();
441     return ConstantClass::get(*Ty, R);
442   }
443
444   static Constant *Shr(const ConstantClass *V1, const ConstantClass *V2) {
445     BuiltinType R = (BuiltinType)V1->getValue() >> (BuiltinType)V2->getValue();
446     return ConstantClass::get(*Ty, R);
447   }
448 };
449
450
451 //===----------------------------------------------------------------------===//
452 //                           DirectFPRules Class
453 //===----------------------------------------------------------------------===//
454 //
455 /// DirectFPRules provides implementations of functions that are valid on
456 /// floating point types, but not all types in general.
457 ///
458 template <class ConstantClass, class BuiltinType, Type **Ty>
459 struct DirectFPRules
460   : public DirectRules<ConstantClass, BuiltinType, Ty,
461                        DirectFPRules<ConstantClass, BuiltinType, Ty> > {
462   static Constant *Rem(const ConstantClass *V1, const ConstantClass *V2) {
463     if (V2->isNullValue()) return 0;
464     BuiltinType Result = std::fmod((BuiltinType)V1->getValue(),
465                                    (BuiltinType)V2->getValue());
466     return ConstantClass::get(*Ty, Result);
467   }
468 };
469
470
471 /// ConstRules::get - This method returns the constant rules implementation that
472 /// implements the semantics of the two specified constants.
473 ConstRules &ConstRules::get(const Constant *V1, const Constant *V2) {
474   static EmptyRules       EmptyR;
475   static BoolRules        BoolR;
476   static NullPointerRules NullPointerR;
477   static DirectIntRules<ConstantSInt,   signed char , &Type::SByteTy>  SByteR;
478   static DirectIntRules<ConstantUInt, unsigned char , &Type::UByteTy>  UByteR;
479   static DirectIntRules<ConstantSInt,   signed short, &Type::ShortTy>  ShortR;
480   static DirectIntRules<ConstantUInt, unsigned short, &Type::UShortTy> UShortR;
481   static DirectIntRules<ConstantSInt,   signed int  , &Type::IntTy>    IntR;
482   static DirectIntRules<ConstantUInt, unsigned int  , &Type::UIntTy>   UIntR;
483   static DirectIntRules<ConstantSInt,  int64_t      , &Type::LongTy>   LongR;
484   static DirectIntRules<ConstantUInt, uint64_t      , &Type::ULongTy>  ULongR;
485   static DirectFPRules <ConstantFP  , float         , &Type::FloatTy>  FloatR;
486   static DirectFPRules <ConstantFP  , double        , &Type::DoubleTy> DoubleR;
487
488   if (isa<ConstantExpr>(V1) || isa<ConstantExpr>(V2) ||
489       isa<GlobalValue>(V1) || isa<GlobalValue>(V2) ||
490       isa<UndefValue>(V1) || isa<UndefValue>(V2))
491     return EmptyR;
492
493   switch (V1->getType()->getTypeID()) {
494   default: assert(0 && "Unknown value type for constant folding!");
495   case Type::BoolTyID:    return BoolR;
496   case Type::PointerTyID: return NullPointerR;
497   case Type::SByteTyID:   return SByteR;
498   case Type::UByteTyID:   return UByteR;
499   case Type::ShortTyID:   return ShortR;
500   case Type::UShortTyID:  return UShortR;
501   case Type::IntTyID:     return IntR;
502   case Type::UIntTyID:    return UIntR;
503   case Type::LongTyID:    return LongR;
504   case Type::ULongTyID:   return ULongR;
505   case Type::FloatTyID:   return FloatR;
506   case Type::DoubleTyID:  return DoubleR;
507   }
508 }
509
510
511 //===----------------------------------------------------------------------===//
512 //                ConstantFold*Instruction Implementations
513 //===----------------------------------------------------------------------===//
514 //
515 // These methods contain the special case hackery required to symbolically
516 // evaluate some constant expression cases, and use the ConstantRules class to
517 // evaluate normal constants.
518 //
519 static unsigned getSize(const Type *Ty) {
520   unsigned S = Ty->getPrimitiveSize();
521   return S ? S : 8;  // Treat pointers at 8 bytes
522 }
523
524 Constant *llvm::ConstantFoldCastInstruction(const Constant *V,
525                                             const Type *DestTy) {
526   if (V->getType() == DestTy) return (Constant*)V;
527
528   // Cast of a global address to boolean is always true.
529   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
530     if (DestTy == Type::BoolTy)
531       // FIXME: When we support 'external weak' references, we have to prevent
532       // this transformation from happening.  This code will need to be updated
533       // to ignore external weak symbols when we support it.
534       return ConstantBool::True;
535   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
536     if (CE->getOpcode() == Instruction::Cast) {
537       Constant *Op = const_cast<Constant*>(CE->getOperand(0));
538       // Try to not produce a cast of a cast, which is almost always redundant.
539       if (!Op->getType()->isFloatingPoint() &&
540           !CE->getType()->isFloatingPoint() &&
541           !DestTy->isFloatingPoint()) {
542         unsigned S1 = getSize(Op->getType()), S2 = getSize(CE->getType());
543         unsigned S3 = getSize(DestTy);
544         if (Op->getType() == DestTy && S3 >= S2)
545           return Op;
546         if (S1 >= S2 && S2 >= S3)
547           return ConstantExpr::getCast(Op, DestTy);
548         if (S1 <= S2 && S2 >= S3 && S1 <= S3)
549           return ConstantExpr::getCast(Op, DestTy);
550       }
551     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
552       // If all of the indexes in the GEP are null values, there is no pointer
553       // adjustment going on.  We might as well cast the source pointer.
554       bool isAllNull = true;
555       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
556         if (!CE->getOperand(i)->isNullValue()) {
557           isAllNull = false;
558           break;
559         }
560       if (isAllNull)
561         return ConstantExpr::getCast(CE->getOperand(0), DestTy);
562     }
563   } else if (isa<UndefValue>(V)) {
564     return UndefValue::get(DestTy);
565   }
566
567   // Check to see if we are casting an pointer to an aggregate to a pointer to
568   // the first element.  If so, return the appropriate GEP instruction.
569   if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
570     if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
571       std::vector<Value*> IdxList;
572       IdxList.push_back(Constant::getNullValue(Type::IntTy));
573       const Type *ElTy = PTy->getElementType();
574       while (ElTy != DPTy->getElementType()) {
575         if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
576           if (STy->getNumElements() == 0) break;
577           ElTy = STy->getElementType(0);
578           IdxList.push_back(Constant::getNullValue(Type::UIntTy));
579         } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
580           if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
581           ElTy = STy->getElementType();
582           IdxList.push_back(IdxList[0]);
583         } else {
584           break;
585         }
586       }
587
588       if (ElTy == DPTy->getElementType())
589         return ConstantExpr::getGetElementPtr(const_cast<Constant*>(V),IdxList);
590     }
591
592   ConstRules &Rules = ConstRules::get(V, V);
593
594   switch (DestTy->getTypeID()) {
595   case Type::BoolTyID:    return Rules.castToBool(V);
596   case Type::UByteTyID:   return Rules.castToUByte(V);
597   case Type::SByteTyID:   return Rules.castToSByte(V);
598   case Type::UShortTyID:  return Rules.castToUShort(V);
599   case Type::ShortTyID:   return Rules.castToShort(V);
600   case Type::UIntTyID:    return Rules.castToUInt(V);
601   case Type::IntTyID:     return Rules.castToInt(V);
602   case Type::ULongTyID:   return Rules.castToULong(V);
603   case Type::LongTyID:    return Rules.castToLong(V);
604   case Type::FloatTyID:   return Rules.castToFloat(V);
605   case Type::DoubleTyID:  return Rules.castToDouble(V);
606   case Type::PointerTyID:
607     return Rules.castToPointer(V, cast<PointerType>(DestTy));
608   default: return 0;
609   }
610 }
611
612 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
613                                               const Constant *V1,
614                                               const Constant *V2) {
615   if (Cond == ConstantBool::True)
616     return const_cast<Constant*>(V1);
617   else if (Cond == ConstantBool::False)
618     return const_cast<Constant*>(V2);
619
620   if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
621   if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
622   if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
623   return 0;
624 }
625
626 /// isZeroSizedType - This type is zero sized if its an array or structure of
627 /// zero sized types.  The only leaf zero sized type is an empty structure.
628 static bool isMaybeZeroSizedType(const Type *Ty) {
629   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
630   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
631
632     // If all of elements have zero size, this does too.
633     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
634       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
635     return true;
636
637   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
638     return isMaybeZeroSizedType(ATy->getElementType());
639   }
640   return false;
641 }
642
643 /// IdxCompare - Compare the two constants as though they were getelementptr
644 /// indices.  This allows coersion of the types to be the same thing.
645 ///
646 /// If the two constants are the "same" (after coersion), return 0.  If the
647 /// first is less than the second, return -1, if the second is less than the
648 /// first, return 1.  If the constants are not integral, return -2.
649 ///
650 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
651   if (C1 == C2) return 0;
652
653   // Ok, we found a different index.  Are either of the operands
654   // ConstantExprs?  If so, we can't do anything with them.
655   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
656     return -2; // don't know!
657   
658   // Ok, we have two differing integer indices.  Sign extend them to be the same
659   // type.  Long is always big enough, so we use it.
660   C1 = ConstantExpr::getSignExtend(C1, Type::LongTy);
661   C2 = ConstantExpr::getSignExtend(C2, Type::LongTy);
662   if (C1 == C2) return 0;  // Are they just differing types?
663
664   // If the type being indexed over is really just a zero sized type, there is
665   // no pointer difference being made here.
666   if (isMaybeZeroSizedType(ElTy))
667     return -2; // dunno.
668
669   // If they are really different, now that they are the same type, then we
670   // found a difference!
671   if (cast<ConstantSInt>(C1)->getValue() < cast<ConstantSInt>(C2)->getValue())
672     return -1;
673   else
674     return 1;
675 }
676
677 /// evaluateRelation - This function determines if there is anything we can
678 /// decide about the two constants provided.  This doesn't need to handle simple
679 /// things like integer comparisons, but should instead handle ConstantExprs
680 /// and GlobalValuess.  If we can determine that the two constants have a
681 /// particular relation to each other, we should return the corresponding SetCC
682 /// code, otherwise return Instruction::BinaryOpsEnd.
683 ///
684 /// To simplify this code we canonicalize the relation so that the first
685 /// operand is always the most "complex" of the two.  We consider simple
686 /// constants (like ConstantInt) to be the simplest, followed by
687 /// GlobalValues, followed by ConstantExpr's (the most complex).
688 ///
689 static Instruction::BinaryOps evaluateRelation(const Constant *V1,
690                                                const Constant *V2) {
691   assert(V1->getType() == V2->getType() &&
692          "Cannot compare different types of values!");
693   if (V1 == V2) return Instruction::SetEQ;
694
695   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
696     // If the first operand is simple, swap operands.
697     assert((isa<GlobalValue>(V2) || isa<ConstantExpr>(V2)) &&
698            "Simple cases should have been handled by caller!");
699     Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
700     if (SwappedRelation != Instruction::BinaryOpsEnd)
701       return SetCondInst::getSwappedCondition(SwappedRelation);
702
703   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)){
704     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
705     Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
706     if (SwappedRelation != Instruction::BinaryOpsEnd)
707       return SetCondInst::getSwappedCondition(SwappedRelation);
708     else
709       return Instruction::BinaryOpsEnd;
710     }
711
712     // Now we know that the RHS is a GlobalValue or simple constant,
713     // which (since the types must match) means that it's a ConstantPointerNull.
714     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
715       assert(CPR1 != CPR2 &&
716              "GVs for the same value exist at different addresses??");
717       // FIXME: If both globals are external weak, they might both be null!
718       return Instruction::SetNE;
719     } else {
720       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
721       // Global can never be null.  FIXME: if we implement external weak
722       // linkage, this is not necessarily true!
723       return Instruction::SetNE;
724     }
725
726   } else {
727     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
728     // constantexpr, a CPR, or a simple constant.
729     const ConstantExpr *CE1 = cast<ConstantExpr>(V1);
730     Constant *CE1Op0 = CE1->getOperand(0);
731
732     switch (CE1->getOpcode()) {
733     case Instruction::Cast:
734       // If the cast is not actually changing bits, and the second operand is a
735       // null pointer, do the comparison with the pre-casted value.
736       if (V2->isNullValue() &&
737           CE1->getType()->isLosslesslyConvertibleTo(CE1Op0->getType()))
738         return evaluateRelation(CE1Op0,
739                                 Constant::getNullValue(CE1Op0->getType()));
740       break;
741
742     case Instruction::GetElementPtr:
743       // Ok, since this is a getelementptr, we know that the constant has a
744       // pointer type.  Check the various cases.
745       if (isa<ConstantPointerNull>(V2)) {
746         // If we are comparing a GEP to a null pointer, check to see if the base
747         // of the GEP equals the null pointer.
748         if (isa<GlobalValue>(CE1Op0)) {
749           // FIXME: this is not true when we have external weak references!
750           // No offset can go from a global to a null pointer.
751           return Instruction::SetGT;
752         } else if (isa<ConstantPointerNull>(CE1Op0)) {
753           // If we are indexing from a null pointer, check to see if we have any
754           // non-zero indices.
755           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
756             if (!CE1->getOperand(i)->isNullValue())
757               // Offsetting from null, must not be equal.
758               return Instruction::SetGT;
759           // Only zero indexes from null, must still be zero.
760           return Instruction::SetEQ;
761         }
762         // Otherwise, we can't really say if the first operand is null or not.
763       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
764         if (isa<ConstantPointerNull>(CE1Op0)) {
765           // FIXME: This is not true with external weak references.
766           return Instruction::SetLT;
767         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
768           if (CPR1 == CPR2) {
769             // If this is a getelementptr of the same global, then it must be
770             // different.  Because the types must match, the getelementptr could
771             // only have at most one index, and because we fold getelementptr's
772             // with a single zero index, it must be nonzero.
773             assert(CE1->getNumOperands() == 2 &&
774                    !CE1->getOperand(1)->isNullValue() &&
775                    "Suprising getelementptr!");
776             return Instruction::SetGT;
777           } else {
778             // If they are different globals, we don't know what the value is,
779             // but they can't be equal.
780             return Instruction::SetNE;
781           }
782         }
783       } else {
784         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
785         const Constant *CE2Op0 = CE2->getOperand(0);
786
787         // There are MANY other foldings that we could perform here.  They will
788         // probably be added on demand, as they seem needed.
789         switch (CE2->getOpcode()) {
790         default: break;
791         case Instruction::GetElementPtr:
792           // By far the most common case to handle is when the base pointers are
793           // obviously to the same or different globals.
794           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
795             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
796               return Instruction::SetNE;
797             // Ok, we know that both getelementptr instructions are based on the
798             // same global.  From this, we can precisely determine the relative
799             // ordering of the resultant pointers.
800             unsigned i = 1;
801             
802             // Compare all of the operands the GEP's have in common.
803             gep_type_iterator GTI = gep_type_begin(CE1);
804             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
805                  ++i, ++GTI)
806               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
807                                  GTI.getIndexedType())) {
808               case -1: return Instruction::SetLT;
809               case 1:  return Instruction::SetGT;
810               case -2: return Instruction::BinaryOpsEnd;
811               }
812
813             // Ok, we ran out of things they have in common.  If any leftovers
814             // are non-zero then we have a difference, otherwise we are equal.
815             for (; i < CE1->getNumOperands(); ++i)
816               if (!CE1->getOperand(i)->isNullValue())
817                 if (isa<ConstantIntegral>(CE1->getOperand(i)))
818                   return Instruction::SetGT;
819                 else
820                   return Instruction::BinaryOpsEnd; // Might be equal.
821                     
822             for (; i < CE2->getNumOperands(); ++i)
823               if (!CE2->getOperand(i)->isNullValue())
824                 if (isa<ConstantIntegral>(CE2->getOperand(i)))
825                   return Instruction::SetLT;
826                 else
827                   return Instruction::BinaryOpsEnd; // Might be equal.
828             return Instruction::SetEQ;
829           }
830         }
831       }
832       
833     default:
834       break;
835     }
836   }
837
838   return Instruction::BinaryOpsEnd;
839 }
840
841 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
842                                               const Constant *V1,
843                                               const Constant *V2) {
844   Constant *C = 0;
845   switch (Opcode) {
846   default:                   break;
847   case Instruction::Add:     C = ConstRules::get(V1, V2).add(V1, V2); break;
848   case Instruction::Sub:     C = ConstRules::get(V1, V2).sub(V1, V2); break;
849   case Instruction::Mul:     C = ConstRules::get(V1, V2).mul(V1, V2); break;
850   case Instruction::Div:     C = ConstRules::get(V1, V2).div(V1, V2); break;
851   case Instruction::Rem:     C = ConstRules::get(V1, V2).rem(V1, V2); break;
852   case Instruction::And:     C = ConstRules::get(V1, V2).op_and(V1, V2); break;
853   case Instruction::Or:      C = ConstRules::get(V1, V2).op_or (V1, V2); break;
854   case Instruction::Xor:     C = ConstRules::get(V1, V2).op_xor(V1, V2); break;
855   case Instruction::Shl:     C = ConstRules::get(V1, V2).shl(V1, V2); break;
856   case Instruction::Shr:     C = ConstRules::get(V1, V2).shr(V1, V2); break;
857   case Instruction::SetEQ:   C = ConstRules::get(V1, V2).equalto(V1, V2); break;
858   case Instruction::SetLT:   C = ConstRules::get(V1, V2).lessthan(V1, V2);break;
859   case Instruction::SetGT:   C = ConstRules::get(V1, V2).lessthan(V2, V1);break;
860   case Instruction::SetNE:   // V1 != V2  ===  !(V1 == V2)
861     C = ConstRules::get(V1, V2).equalto(V1, V2);
862     if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
863     break;
864   case Instruction::SetLE:   // V1 <= V2  ===  !(V2 < V1)
865     C = ConstRules::get(V1, V2).lessthan(V2, V1);
866     if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
867     break;
868   case Instruction::SetGE:   // V1 >= V2  ===  !(V1 < V2)
869     C = ConstRules::get(V1, V2).lessthan(V1, V2);
870     if (C) return ConstantExpr::get(Instruction::Xor, C, ConstantBool::True);
871     break;
872   }
873
874   // If we successfully folded the expression, return it now.
875   if (C) return C;
876
877   if (SetCondInst::isRelational(Opcode)) {
878     if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
879       return UndefValue::get(Type::BoolTy);
880     switch (evaluateRelation(V1, V2)) {
881     default: assert(0 && "Unknown relational!");
882     case Instruction::BinaryOpsEnd:
883       break;  // Couldn't determine anything about these constants.
884     case Instruction::SetEQ:   // We know the constants are equal!
885       // If we know the constants are equal, we can decide the result of this
886       // computation precisely.
887       return ConstantBool::get(Opcode == Instruction::SetEQ ||
888                                Opcode == Instruction::SetLE ||
889                                Opcode == Instruction::SetGE);
890     case Instruction::SetLT:
891       // If we know that V1 < V2, we can decide the result of this computation
892       // precisely.
893       return ConstantBool::get(Opcode == Instruction::SetLT ||
894                                Opcode == Instruction::SetNE ||
895                                Opcode == Instruction::SetLE);
896     case Instruction::SetGT:
897       // If we know that V1 > V2, we can decide the result of this computation
898       // precisely.
899       return ConstantBool::get(Opcode == Instruction::SetGT ||
900                                Opcode == Instruction::SetNE ||
901                                Opcode == Instruction::SetGE);
902     case Instruction::SetLE:
903       // If we know that V1 <= V2, we can only partially decide this relation.
904       if (Opcode == Instruction::SetGT) return ConstantBool::False;
905       if (Opcode == Instruction::SetLT) return ConstantBool::True;
906       break;
907
908     case Instruction::SetGE:
909       // If we know that V1 >= V2, we can only partially decide this relation.
910       if (Opcode == Instruction::SetLT) return ConstantBool::False;
911       if (Opcode == Instruction::SetGT) return ConstantBool::True;
912       break;
913       
914     case Instruction::SetNE:
915       // If we know that V1 != V2, we can only partially decide this relation.
916       if (Opcode == Instruction::SetEQ) return ConstantBool::False;
917       if (Opcode == Instruction::SetNE) return ConstantBool::True;
918       break;
919     }
920   }
921
922   if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) {
923     switch (Opcode) {
924     case Instruction::Add:
925     case Instruction::Sub:
926     case Instruction::Xor:
927       return UndefValue::get(V1->getType());
928
929     case Instruction::Mul:
930     case Instruction::And:
931       return Constant::getNullValue(V1->getType());
932     case Instruction::Div:
933     case Instruction::Rem:
934       if (!isa<UndefValue>(V2))     // undef/X -> 0
935         return Constant::getNullValue(V1->getType());
936       return const_cast<Constant*>(V2);                // X/undef -> undef
937     case Instruction::Or:           // X|undef -> -1
938       return ConstantInt::getAllOnesValue(V1->getType());
939     case Instruction::Shr:
940       if (!isa<UndefValue>(V2)) {
941         if (V1->getType()->isSigned())
942           return const_cast<Constant*>(V1);  // undef >>s X -> undef
943         // undef >>u X -> 0
944       } else if (isa<UndefValue>(V1)) {
945         return const_cast<Constant*>(V1);   //  undef >> undef -> undef
946       } else {
947         if (V1->getType()->isSigned())
948           return const_cast<Constant*>(V1);  // X >>s undef -> X
949         // X >>u undef -> 0
950       }
951       return Constant::getNullValue(V1->getType());
952
953     case Instruction::Shl:
954       // undef << X -> 0   X << undef -> 0
955       return Constant::getNullValue(V1->getType());
956     }
957   }
958
959   if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(V1)) {
960     if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2)) {
961       // There are many possible foldings we could do here.  We should probably
962       // at least fold add of a pointer with an integer into the appropriate
963       // getelementptr.  This will improve alias analysis a bit.
964
965
966
967
968     } else {
969       // Just implement a couple of simple identities.
970       switch (Opcode) {
971       case Instruction::Add:
972         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X + 0 == X
973         break;
974       case Instruction::Sub:
975         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X - 0 == X
976         break;
977       case Instruction::Mul:
978         if (V2->isNullValue()) return const_cast<Constant*>(V2);  // X * 0 == 0
979         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
980           if (CI->getRawValue() == 1)
981             return const_cast<Constant*>(V1);                     // X * 1 == X
982         break;
983       case Instruction::Div:
984         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
985           if (CI->getRawValue() == 1)
986             return const_cast<Constant*>(V1);                     // X / 1 == X
987         break;
988       case Instruction::Rem:
989         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
990           if (CI->getRawValue() == 1)
991             return Constant::getNullValue(CI->getType()); // X % 1 == 0
992         break;
993       case Instruction::And:
994         if (cast<ConstantIntegral>(V2)->isAllOnesValue())
995           return const_cast<Constant*>(V1);                       // X & -1 == X
996         if (V2->isNullValue()) return const_cast<Constant*>(V2);  // X & 0 == 0
997         if (CE1->getOpcode() == Instruction::Cast &&
998             isa<GlobalValue>(CE1->getOperand(0))) {
999           GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
1000
1001           // Functions are at least 4-byte aligned.  If and'ing the address of a
1002           // function with a constant < 4, fold it to zero.
1003           if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1004             if (CI->getRawValue() < 4 && isa<Function>(CPR))
1005               return Constant::getNullValue(CI->getType());
1006         }
1007         break;
1008       case Instruction::Or:
1009         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X | 0 == X
1010         if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1011           return const_cast<Constant*>(V2);  // X | -1 == -1
1012         break;
1013       case Instruction::Xor:
1014         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X ^ 0 == X
1015         break;
1016       }
1017     }
1018
1019   } else if (const ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2)) {
1020     // If V2 is a constant expr and V1 isn't, flop them around and fold the
1021     // other way if possible.
1022     switch (Opcode) {
1023     case Instruction::Add:
1024     case Instruction::Mul:
1025     case Instruction::And:
1026     case Instruction::Or:
1027     case Instruction::Xor:
1028     case Instruction::SetEQ:
1029     case Instruction::SetNE:
1030       // No change of opcode required.
1031       return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1032
1033     case Instruction::SetLT:
1034     case Instruction::SetGT:
1035     case Instruction::SetLE:
1036     case Instruction::SetGE:
1037       // Change the opcode as necessary to swap the operands.
1038       Opcode = SetCondInst::getSwappedCondition((Instruction::BinaryOps)Opcode);
1039       return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1040
1041     case Instruction::Shl:
1042     case Instruction::Shr:
1043     case Instruction::Sub:
1044     case Instruction::Div:
1045     case Instruction::Rem:
1046     default:  // These instructions cannot be flopped around.
1047       break;
1048     }
1049   }
1050   return 0;
1051 }
1052
1053 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1054                                           const std::vector<Value*> &IdxList) {
1055   if (IdxList.size() == 0 ||
1056       (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
1057     return const_cast<Constant*>(C);
1058
1059   if (isa<UndefValue>(C)) {
1060     const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1061                                                        true);
1062     assert(Ty != 0 && "Invalid indices for GEP!");
1063     return UndefValue::get(PointerType::get(Ty));
1064   }
1065
1066   Constant *Idx0 = cast<Constant>(IdxList[0]);
1067   if (C->isNullValue()) {
1068     bool isNull = true;
1069     for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1070       if (!cast<Constant>(IdxList[i])->isNullValue()) {
1071         isNull = false;
1072         break;
1073       }
1074     if (isNull) {
1075       const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1076                                                          true);
1077       assert(Ty != 0 && "Invalid indices for GEP!");
1078       return ConstantPointerNull::get(PointerType::get(Ty));
1079     }
1080
1081     if (IdxList.size() == 1) {
1082       const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
1083       if (unsigned ElSize = ElTy->getPrimitiveSize()) {
1084         // gep null, C is equal to C*sizeof(nullty).  If nullty is a known llvm
1085         // type, we can statically fold this.
1086         Constant *R = ConstantUInt::get(Type::UIntTy, ElSize);
1087         R = ConstantExpr::getCast(R, Idx0->getType());
1088         R = ConstantExpr::getMul(R, Idx0);
1089         return ConstantExpr::getCast(R, C->getType());
1090       }
1091     }
1092   }
1093
1094   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1095     // Combine Indices - If the source pointer to this getelementptr instruction
1096     // is a getelementptr instruction, combine the indices of the two
1097     // getelementptr instructions into a single instruction.
1098     //
1099     if (CE->getOpcode() == Instruction::GetElementPtr) {
1100       const Type *LastTy = 0;
1101       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1102            I != E; ++I)
1103         LastTy = *I;
1104
1105       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1106         std::vector<Value*> NewIndices;
1107         NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1108         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1109           NewIndices.push_back(CE->getOperand(i));
1110
1111         // Add the last index of the source with the first index of the new GEP.
1112         // Make sure to handle the case when they are actually different types.
1113         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1114         // Otherwise it must be an array.
1115         if (!Idx0->isNullValue()) {
1116           const Type *IdxTy = Combined->getType();
1117           if (IdxTy != Idx0->getType()) IdxTy = Type::LongTy;
1118           Combined = 
1119             ConstantExpr::get(Instruction::Add,
1120                               ConstantExpr::getCast(Idx0, IdxTy),
1121                               ConstantExpr::getCast(Combined, IdxTy));
1122         }
1123         
1124         NewIndices.push_back(Combined);
1125         NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1126         return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1127       }
1128     }
1129
1130     // Implement folding of:
1131     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1132     //                        long 0, long 0)
1133     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1134     //
1135     if (CE->getOpcode() == Instruction::Cast && IdxList.size() > 1 &&
1136         Idx0->isNullValue())
1137       if (const PointerType *SPT = 
1138           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1139         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1140           if (const ArrayType *CAT =
1141               dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1142             if (CAT->getElementType() == SAT->getElementType())
1143               return ConstantExpr::getGetElementPtr(
1144                       (Constant*)CE->getOperand(0), IdxList);
1145   }
1146   return 0;
1147 }
1148