28993d5224732731819712dd0c466b9dc74c2992
[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 #include <cmath>
32 using namespace llvm;
33
34 namespace {
35   struct VISIBILITY_HIDDEN ConstRules {
36     ConstRules() {}
37     virtual ~ConstRules() {}
38
39     // Binary Operators...
40     virtual Constant *add(const Constant *V1, const Constant *V2) const = 0;
41     virtual Constant *sub(const Constant *V1, const Constant *V2) const = 0;
42     virtual Constant *mul(const Constant *V1, const Constant *V2) const = 0;
43     virtual Constant *urem(const Constant *V1, const Constant *V2) const = 0;
44     virtual Constant *srem(const Constant *V1, const Constant *V2) const = 0;
45     virtual Constant *frem(const Constant *V1, const Constant *V2) const = 0;
46     virtual Constant *udiv(const Constant *V1, const Constant *V2) const = 0;
47     virtual Constant *sdiv(const Constant *V1, const Constant *V2) const = 0;
48     virtual Constant *fdiv(const Constant *V1, const Constant *V2) const = 0;
49     virtual Constant *op_and(const Constant *V1, const Constant *V2) const = 0;
50     virtual Constant *op_or (const Constant *V1, const Constant *V2) const = 0;
51     virtual Constant *op_xor(const Constant *V1, const Constant *V2) const = 0;
52     virtual Constant *shl(const Constant *V1, const Constant *V2) const = 0;
53     virtual Constant *lshr(const Constant *V1, const Constant *V2) const = 0;
54     virtual Constant *ashr(const Constant *V1, const Constant *V2) const = 0;
55     virtual Constant *lessthan(const Constant *V1, const Constant *V2) const =0;
56     virtual Constant *equalto(const Constant *V1, const Constant *V2) const = 0;
57
58     // Casting operators.
59     virtual Constant *castToBool  (const Constant *V) const = 0;
60     virtual Constant *castToSByte (const Constant *V) const = 0;
61     virtual Constant *castToUByte (const Constant *V) const = 0;
62     virtual Constant *castToShort (const Constant *V) const = 0;
63     virtual Constant *castToUShort(const Constant *V) const = 0;
64     virtual Constant *castToInt   (const Constant *V) const = 0;
65     virtual Constant *castToUInt  (const Constant *V) const = 0;
66     virtual Constant *castToLong  (const Constant *V) const = 0;
67     virtual Constant *castToULong (const Constant *V) const = 0;
68     virtual Constant *castToFloat (const Constant *V) const = 0;
69     virtual Constant *castToDouble(const Constant *V) const = 0;
70     virtual Constant *castToPointer(const Constant *V,
71                                     const PointerType *Ty) const = 0;
72
73     // ConstRules::get - Return an instance of ConstRules for the specified
74     // constant operands.
75     //
76     static ConstRules &get(const Constant *V1, const Constant *V2);
77   private:
78     ConstRules(const ConstRules &);             // Do not implement
79     ConstRules &operator=(const ConstRules &);  // Do not implement
80   };
81 }
82
83
84 //===----------------------------------------------------------------------===//
85 //                             TemplateRules Class
86 //===----------------------------------------------------------------------===//
87 //
88 // TemplateRules - Implement a subclass of ConstRules that provides all
89 // operations as noops.  All other rules classes inherit from this class so
90 // that if functionality is needed in the future, it can simply be added here
91 // and to ConstRules without changing anything else...
92 //
93 // This class also provides subclasses with typesafe implementations of methods
94 // so that don't have to do type casting.
95 //
96 namespace {
97 template<class ArgType, class SubClassName>
98 class VISIBILITY_HIDDEN TemplateRules : public ConstRules {
99
100
101   //===--------------------------------------------------------------------===//
102   // Redirecting functions that cast to the appropriate types
103   //===--------------------------------------------------------------------===//
104
105   virtual Constant *add(const Constant *V1, const Constant *V2) const {
106     return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
107   }
108   virtual Constant *sub(const Constant *V1, const Constant *V2) const {
109     return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
110   }
111   virtual Constant *mul(const Constant *V1, const Constant *V2) const {
112     return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
113   }
114   virtual Constant *udiv(const Constant *V1, const Constant *V2) const {
115     return SubClassName::UDiv((const ArgType *)V1, (const ArgType *)V2);
116   }
117   virtual Constant *sdiv(const Constant *V1, const Constant *V2) const {
118     return SubClassName::SDiv((const ArgType *)V1, (const ArgType *)V2);
119   }
120   virtual Constant *fdiv(const Constant *V1, const Constant *V2) const {
121     return SubClassName::FDiv((const ArgType *)V1, (const ArgType *)V2);
122   }
123   virtual Constant *urem(const Constant *V1, const Constant *V2) const {
124     return SubClassName::URem((const ArgType *)V1, (const ArgType *)V2);
125   }
126   virtual Constant *srem(const Constant *V1, const Constant *V2) const {
127     return SubClassName::SRem((const ArgType *)V1, (const ArgType *)V2);
128   }
129   virtual Constant *frem(const Constant *V1, const Constant *V2) const {
130     return SubClassName::FRem((const ArgType *)V1, (const ArgType *)V2);
131   }
132   virtual Constant *op_and(const Constant *V1, const Constant *V2) const {
133     return SubClassName::And((const ArgType *)V1, (const ArgType *)V2);
134   }
135   virtual Constant *op_or(const Constant *V1, const Constant *V2) const {
136     return SubClassName::Or((const ArgType *)V1, (const ArgType *)V2);
137   }
138   virtual Constant *op_xor(const Constant *V1, const Constant *V2) const {
139     return SubClassName::Xor((const ArgType *)V1, (const ArgType *)V2);
140   }
141   virtual Constant *shl(const Constant *V1, const Constant *V2) const {
142     return SubClassName::Shl((const ArgType *)V1, (const ArgType *)V2);
143   }
144   virtual Constant *lshr(const Constant *V1, const Constant *V2) const {
145     return SubClassName::LShr((const ArgType *)V1, (const ArgType *)V2);
146   }
147   virtual Constant *ashr(const Constant *V1, const Constant *V2) const {
148     return SubClassName::AShr((const ArgType *)V1, (const ArgType *)V2);
149   }
150
151   virtual Constant *lessthan(const Constant *V1, const Constant *V2) const {
152     return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
153   }
154   virtual Constant *equalto(const Constant *V1, const Constant *V2) const {
155     return SubClassName::EqualTo((const ArgType *)V1, (const ArgType *)V2);
156   }
157
158   // Casting operators.  ick
159   virtual Constant *castToBool(const Constant *V) const {
160     return SubClassName::CastToBool((const ArgType*)V);
161   }
162   virtual Constant *castToSByte(const Constant *V) const {
163     return SubClassName::CastToSByte((const ArgType*)V);
164   }
165   virtual Constant *castToUByte(const Constant *V) const {
166     return SubClassName::CastToUByte((const ArgType*)V);
167   }
168   virtual Constant *castToShort(const Constant *V) const {
169     return SubClassName::CastToShort((const ArgType*)V);
170   }
171   virtual Constant *castToUShort(const Constant *V) const {
172     return SubClassName::CastToUShort((const ArgType*)V);
173   }
174   virtual Constant *castToInt(const Constant *V) const {
175     return SubClassName::CastToInt((const ArgType*)V);
176   }
177   virtual Constant *castToUInt(const Constant *V) const {
178     return SubClassName::CastToUInt((const ArgType*)V);
179   }
180   virtual Constant *castToLong(const Constant *V) const {
181     return SubClassName::CastToLong((const ArgType*)V);
182   }
183   virtual Constant *castToULong(const Constant *V) const {
184     return SubClassName::CastToULong((const ArgType*)V);
185   }
186   virtual Constant *castToFloat(const Constant *V) const {
187     return SubClassName::CastToFloat((const ArgType*)V);
188   }
189   virtual Constant *castToDouble(const Constant *V) const {
190     return SubClassName::CastToDouble((const ArgType*)V);
191   }
192   virtual Constant *castToPointer(const Constant *V,
193                                   const PointerType *Ty) const {
194     return SubClassName::CastToPointer((const ArgType*)V, Ty);
195   }
196
197   //===--------------------------------------------------------------------===//
198   // Default "noop" implementations
199   //===--------------------------------------------------------------------===//
200
201   static Constant *Add (const ArgType *V1, const ArgType *V2) { return 0; }
202   static Constant *Sub (const ArgType *V1, const ArgType *V2) { return 0; }
203   static Constant *Mul (const ArgType *V1, const ArgType *V2) { return 0; }
204   static Constant *SDiv(const ArgType *V1, const ArgType *V2) { return 0; }
205   static Constant *UDiv(const ArgType *V1, const ArgType *V2) { return 0; }
206   static Constant *FDiv(const ArgType *V1, const ArgType *V2) { return 0; }
207   static Constant *URem(const ArgType *V1, const ArgType *V2) { return 0; }
208   static Constant *SRem(const ArgType *V1, const ArgType *V2) { return 0; }
209   static Constant *FRem(const ArgType *V1, const ArgType *V2) { return 0; }
210   static Constant *And (const ArgType *V1, const ArgType *V2) { return 0; }
211   static Constant *Or  (const ArgType *V1, const ArgType *V2) { return 0; }
212   static Constant *Xor (const ArgType *V1, const ArgType *V2) { return 0; }
213   static Constant *Shl (const ArgType *V1, const ArgType *V2) { return 0; }
214   static Constant *LShr(const ArgType *V1, const ArgType *V2) { return 0; }
215   static Constant *AShr(const ArgType *V1, const ArgType *V2) { return 0; }
216   static Constant *LessThan(const ArgType *V1, const ArgType *V2) {
217     return 0;
218   }
219   static Constant *EqualTo(const ArgType *V1, const ArgType *V2) {
220     return 0;
221   }
222
223   // Casting operators.  ick
224   static Constant *CastToBool  (const Constant *V) { return 0; }
225   static Constant *CastToSByte (const Constant *V) { return 0; }
226   static Constant *CastToUByte (const Constant *V) { return 0; }
227   static Constant *CastToShort (const Constant *V) { return 0; }
228   static Constant *CastToUShort(const Constant *V) { return 0; }
229   static Constant *CastToInt   (const Constant *V) { return 0; }
230   static Constant *CastToUInt  (const Constant *V) { return 0; }
231   static Constant *CastToLong  (const Constant *V) { return 0; }
232   static Constant *CastToULong (const Constant *V) { return 0; }
233   static Constant *CastToFloat (const Constant *V) { return 0; }
234   static Constant *CastToDouble(const Constant *V) { return 0; }
235   static Constant *CastToPointer(const Constant *,
236                                  const PointerType *) {return 0;}
237
238 public:
239   virtual ~TemplateRules() {}
240 };
241 }  // end anonymous namespace
242
243
244 //===----------------------------------------------------------------------===//
245 //                             EmptyRules Class
246 //===----------------------------------------------------------------------===//
247 //
248 // EmptyRules provides a concrete base class of ConstRules that does nothing
249 //
250 namespace {
251 struct VISIBILITY_HIDDEN EmptyRules
252   : public TemplateRules<Constant, EmptyRules> {
253   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
254     if (V1 == V2) return ConstantBool::getTrue();
255     return 0;
256   }
257 };
258 }  // end anonymous namespace
259
260
261
262 //===----------------------------------------------------------------------===//
263 //                              BoolRules Class
264 //===----------------------------------------------------------------------===//
265 //
266 // BoolRules provides a concrete base class of ConstRules for the 'bool' type.
267 //
268 namespace {
269 struct VISIBILITY_HIDDEN BoolRules
270   : public TemplateRules<ConstantBool, BoolRules> {
271
272   static Constant *LessThan(const ConstantBool *V1, const ConstantBool *V2) {
273     return ConstantBool::get(V1->getValue() < V2->getValue());
274   }
275
276   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
277     return ConstantBool::get(V1 == V2);
278   }
279
280   static Constant *And(const ConstantBool *V1, const ConstantBool *V2) {
281     return ConstantBool::get(V1->getValue() & V2->getValue());
282   }
283
284   static Constant *Or(const ConstantBool *V1, const ConstantBool *V2) {
285     return ConstantBool::get(V1->getValue() | V2->getValue());
286   }
287
288   static Constant *Xor(const ConstantBool *V1, const ConstantBool *V2) {
289     return ConstantBool::get(V1->getValue() ^ V2->getValue());
290   }
291
292   // Casting operators.  ick
293 #define DEF_CAST(TYPE, CLASS, CTYPE) \
294   static Constant *CastTo##TYPE  (const ConstantBool *V) {    \
295     return CLASS::get(Type::TYPE##Ty, (CTYPE)(bool)V->getValue()); \
296   }
297
298   DEF_CAST(Bool  , ConstantBool, bool)
299   DEF_CAST(SByte , ConstantInt, signed char)
300   DEF_CAST(UByte , ConstantInt, unsigned char)
301   DEF_CAST(Short , ConstantInt, signed short)
302   DEF_CAST(UShort, ConstantInt, unsigned short)
303   DEF_CAST(Int   , ConstantInt, signed int)
304   DEF_CAST(UInt  , ConstantInt, unsigned int)
305   DEF_CAST(Long  , ConstantInt, int64_t)
306   DEF_CAST(ULong , ConstantInt, uint64_t)
307   DEF_CAST(Float , ConstantFP  , float)
308   DEF_CAST(Double, ConstantFP  , double)
309 #undef DEF_CAST
310 };
311 }  // end anonymous namespace
312
313
314 //===----------------------------------------------------------------------===//
315 //                            NullPointerRules Class
316 //===----------------------------------------------------------------------===//
317 //
318 // NullPointerRules provides a concrete base class of ConstRules for null
319 // pointers.
320 //
321 namespace {
322 struct VISIBILITY_HIDDEN NullPointerRules
323   : public TemplateRules<ConstantPointerNull, NullPointerRules> {
324   static Constant *EqualTo(const Constant *V1, const Constant *V2) {
325     return ConstantBool::getTrue();  // Null pointers are always equal
326   }
327   static Constant *CastToBool(const Constant *V) {
328     return ConstantBool::getFalse();
329   }
330   static Constant *CastToSByte (const Constant *V) {
331     return ConstantInt::get(Type::SByteTy, 0);
332   }
333   static Constant *CastToUByte (const Constant *V) {
334     return ConstantInt::get(Type::UByteTy, 0);
335   }
336   static Constant *CastToShort (const Constant *V) {
337     return ConstantInt::get(Type::ShortTy, 0);
338   }
339   static Constant *CastToUShort(const Constant *V) {
340     return ConstantInt::get(Type::UShortTy, 0);
341   }
342   static Constant *CastToInt   (const Constant *V) {
343     return ConstantInt::get(Type::IntTy, 0);
344   }
345   static Constant *CastToUInt  (const Constant *V) {
346     return ConstantInt::get(Type::UIntTy, 0);
347   }
348   static Constant *CastToLong  (const Constant *V) {
349     return ConstantInt::get(Type::LongTy, 0);
350   }
351   static Constant *CastToULong (const Constant *V) {
352     return ConstantInt::get(Type::ULongTy, 0);
353   }
354   static Constant *CastToFloat (const Constant *V) {
355     return ConstantFP::get(Type::FloatTy, 0);
356   }
357   static Constant *CastToDouble(const Constant *V) {
358     return ConstantFP::get(Type::DoubleTy, 0);
359   }
360
361   static Constant *CastToPointer(const ConstantPointerNull *V,
362                                  const PointerType *PTy) {
363     return ConstantPointerNull::get(PTy);
364   }
365 };
366 }  // end anonymous namespace
367
368 //===----------------------------------------------------------------------===//
369 //                          ConstantPackedRules Class
370 //===----------------------------------------------------------------------===//
371
372 /// DoVectorOp - Given two packed constants and a function pointer, apply the
373 /// function pointer to each element pair, producing a new ConstantPacked
374 /// constant.
375 static Constant *EvalVectorOp(const ConstantPacked *V1, 
376                               const ConstantPacked *V2,
377                               Constant *(*FP)(Constant*, Constant*)) {
378   std::vector<Constant*> Res;
379   for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i)
380     Res.push_back(FP(const_cast<Constant*>(V1->getOperand(i)),
381                      const_cast<Constant*>(V2->getOperand(i))));
382   return ConstantPacked::get(Res);
383 }
384
385 /// PackedTypeRules provides a concrete base class of ConstRules for
386 /// ConstantPacked operands.
387 ///
388 namespace {
389 struct VISIBILITY_HIDDEN ConstantPackedRules
390   : public TemplateRules<ConstantPacked, ConstantPackedRules> {
391   
392   static Constant *Add(const ConstantPacked *V1, const ConstantPacked *V2) {
393     return EvalVectorOp(V1, V2, ConstantExpr::getAdd);
394   }
395   static Constant *Sub(const ConstantPacked *V1, const ConstantPacked *V2) {
396     return EvalVectorOp(V1, V2, ConstantExpr::getSub);
397   }
398   static Constant *Mul(const ConstantPacked *V1, const ConstantPacked *V2) {
399     return EvalVectorOp(V1, V2, ConstantExpr::getMul);
400   }
401   static Constant *UDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
402     return EvalVectorOp(V1, V2, ConstantExpr::getUDiv);
403   }
404   static Constant *SDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
405     return EvalVectorOp(V1, V2, ConstantExpr::getSDiv);
406   }
407   static Constant *FDiv(const ConstantPacked *V1, const ConstantPacked *V2) {
408     return EvalVectorOp(V1, V2, ConstantExpr::getFDiv);
409   }
410   static Constant *URem(const ConstantPacked *V1, const ConstantPacked *V2) {
411     return EvalVectorOp(V1, V2, ConstantExpr::getURem);
412   }
413   static Constant *SRem(const ConstantPacked *V1, const ConstantPacked *V2) {
414     return EvalVectorOp(V1, V2, ConstantExpr::getSRem);
415   }
416   static Constant *FRem(const ConstantPacked *V1, const ConstantPacked *V2) {
417     return EvalVectorOp(V1, V2, ConstantExpr::getFRem);
418   }
419   static Constant *And(const ConstantPacked *V1, const ConstantPacked *V2) {
420     return EvalVectorOp(V1, V2, ConstantExpr::getAnd);
421   }
422   static Constant *Or (const ConstantPacked *V1, const ConstantPacked *V2) {
423     return EvalVectorOp(V1, V2, ConstantExpr::getOr);
424   }
425   static Constant *Xor(const ConstantPacked *V1, const ConstantPacked *V2) {
426     return EvalVectorOp(V1, V2, ConstantExpr::getXor);
427   }
428   static Constant *LessThan(const ConstantPacked *V1, const ConstantPacked *V2){
429     return 0;
430   }
431   static Constant *EqualTo(const ConstantPacked *V1, const ConstantPacked *V2) {
432     for (unsigned i = 0, e = V1->getNumOperands(); i != e; ++i) {
433       Constant *C = 
434         ConstantExpr::getSetEQ(const_cast<Constant*>(V1->getOperand(i)),
435                                const_cast<Constant*>(V2->getOperand(i)));
436       if (ConstantBool *CB = dyn_cast<ConstantBool>(C))
437         return CB;
438     }
439     // Otherwise, could not decide from any element pairs.
440     return 0;
441   }
442 };
443 }  // end anonymous namespace
444
445
446 //===----------------------------------------------------------------------===//
447 //                          GeneralPackedRules Class
448 //===----------------------------------------------------------------------===//
449
450 /// GeneralPackedRules provides a concrete base class of ConstRules for
451 /// PackedType operands, where both operands are not ConstantPacked.  The usual
452 /// cause for this is that one operand is a ConstantAggregateZero.
453 ///
454 namespace {
455 struct VISIBILITY_HIDDEN GeneralPackedRules
456   : public TemplateRules<Constant, GeneralPackedRules> {
457 };
458 }  // end anonymous namespace
459
460
461 //===----------------------------------------------------------------------===//
462 //                           DirectIntRules Class
463 //===----------------------------------------------------------------------===//
464 //
465 // DirectIntRules provides implementations of functions that are valid on
466 // integer types, but not all types in general.
467 //
468 namespace {
469 template <class BuiltinType, Type **Ty>
470 struct VISIBILITY_HIDDEN DirectIntRules
471   : public TemplateRules<ConstantInt, DirectIntRules<BuiltinType, Ty> > {
472
473   static Constant *Add(const ConstantInt *V1, const ConstantInt *V2) {
474     BuiltinType R = (BuiltinType)V1->getZExtValue() + 
475                     (BuiltinType)V2->getZExtValue();
476     return ConstantInt::get(*Ty, R);
477   }
478
479   static Constant *Sub(const ConstantInt *V1, const ConstantInt *V2) {
480     BuiltinType R = (BuiltinType)V1->getZExtValue() - 
481                     (BuiltinType)V2->getZExtValue();
482     return ConstantInt::get(*Ty, R);
483   }
484
485   static Constant *Mul(const ConstantInt *V1, const ConstantInt *V2) {
486     BuiltinType R = (BuiltinType)V1->getZExtValue() * 
487                     (BuiltinType)V2->getZExtValue();
488     return ConstantInt::get(*Ty, R);
489   }
490
491   static Constant *LessThan(const ConstantInt *V1, const ConstantInt *V2) {
492     bool R = (BuiltinType)V1->getZExtValue() < (BuiltinType)V2->getZExtValue();
493     return ConstantBool::get(R);
494   }
495
496   static Constant *EqualTo(const ConstantInt *V1, const ConstantInt *V2) {
497     bool R = (BuiltinType)V1->getZExtValue() == (BuiltinType)V2->getZExtValue();
498     return ConstantBool::get(R);
499   }
500
501   static Constant *CastToPointer(const ConstantInt *V,
502                                  const PointerType *PTy) {
503     if (V->isNullValue())    // Is it a FP or Integral null value?
504       return ConstantPointerNull::get(PTy);
505     return 0;  // Can't const prop other types of pointers
506   }
507
508   // Casting operators.  ick
509 #define DEF_CAST(TYPE, CLASS, CTYPE) \
510   static Constant *CastTo##TYPE  (const ConstantInt *V) {    \
511     return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getZExtValue()); \
512   }
513
514   DEF_CAST(Bool  , ConstantBool, bool)
515   DEF_CAST(SByte , ConstantInt, signed char)
516   DEF_CAST(UByte , ConstantInt, unsigned char)
517   DEF_CAST(Short , ConstantInt, signed short)
518   DEF_CAST(UShort, ConstantInt, unsigned short)
519   DEF_CAST(Int   , ConstantInt, signed int)
520   DEF_CAST(UInt  , ConstantInt, unsigned int)
521   DEF_CAST(Long  , ConstantInt, int64_t)
522   DEF_CAST(ULong , ConstantInt, uint64_t)
523   DEF_CAST(Float , ConstantFP , float)
524   DEF_CAST(Double, ConstantFP , double)
525 #undef DEF_CAST
526
527   static Constant *UDiv(const ConstantInt *V1, const ConstantInt *V2) {
528     if (V2->isNullValue())                   // X / 0
529       return 0;
530     BuiltinType R = (BuiltinType)(V1->getZExtValue() / V2->getZExtValue());
531     return ConstantInt::get(*Ty, R);
532   }
533
534   static Constant *SDiv(const ConstantInt *V1, const ConstantInt *V2) {
535     if (V2->isNullValue())                   // X / 0
536       return 0;
537     if (V2->isAllOnesValue() &&              // MIN_INT / -1
538         (BuiltinType)V1->getSExtValue() == -(BuiltinType)V1->getSExtValue())
539       return 0;
540     BuiltinType R = (BuiltinType)(V1->getSExtValue() / V2->getSExtValue());
541     return ConstantInt::get(*Ty, R);
542   }
543
544   static Constant *URem(const ConstantInt *V1,
545                         const ConstantInt *V2) {
546     if (V2->isNullValue()) return 0;         // X / 0
547     BuiltinType R = (BuiltinType)(V1->getZExtValue() % V2->getZExtValue());
548     return ConstantInt::get(*Ty, R);
549   }
550
551   static Constant *SRem(const ConstantInt *V1,
552                         const ConstantInt *V2) {
553     if (V2->isNullValue()) return 0;         // X % 0
554     if (V2->isAllOnesValue() &&              // MIN_INT % -1
555         (BuiltinType)V1->getSExtValue() == -(BuiltinType)V1->getSExtValue())
556       return 0;
557     BuiltinType R = (BuiltinType)(V1->getSExtValue() % V2->getSExtValue());
558     return ConstantInt::get(*Ty, R);
559   }
560
561   static Constant *And(const ConstantInt *V1, const ConstantInt *V2) {
562     BuiltinType R = 
563       (BuiltinType)V1->getZExtValue() & (BuiltinType)V2->getZExtValue();
564     return ConstantInt::get(*Ty, R);
565   }
566   static Constant *Or(const ConstantInt *V1, const ConstantInt *V2) {
567     BuiltinType R = 
568       (BuiltinType)V1->getZExtValue() | (BuiltinType)V2->getZExtValue();
569     return ConstantInt::get(*Ty, R);
570   }
571   static Constant *Xor(const ConstantInt *V1, const ConstantInt *V2) {
572     BuiltinType R = 
573       (BuiltinType)V1->getZExtValue() ^ (BuiltinType)V2->getZExtValue();
574     return ConstantInt::get(*Ty, R);
575   }
576
577   static Constant *Shl(const ConstantInt *V1, const ConstantInt *V2) {
578     BuiltinType R = 
579       (BuiltinType)V1->getZExtValue() << (BuiltinType)V2->getZExtValue();
580     return ConstantInt::get(*Ty, R);
581   }
582
583   static Constant *LShr(const ConstantInt *V1, const ConstantInt *V2) {
584     BuiltinType R = BuiltinType(V1->getZExtValue() >> V2->getZExtValue());
585     return ConstantInt::get(*Ty, R);
586   }
587
588   static Constant *AShr(const ConstantInt *V1, const ConstantInt *V2) {
589     BuiltinType R = BuiltinType(V1->getSExtValue() >> V2->getZExtValue());
590     return ConstantInt::get(*Ty, R);
591   }
592 };
593 }  // end anonymous namespace
594
595
596 //===----------------------------------------------------------------------===//
597 //                           DirectFPRules Class
598 //===----------------------------------------------------------------------===//
599 //
600 /// DirectFPRules provides implementations of functions that are valid on
601 /// floating point types, but not all types in general.
602 ///
603 namespace {
604 template <class BuiltinType, Type **Ty>
605 struct VISIBILITY_HIDDEN DirectFPRules
606   : public TemplateRules<ConstantFP, DirectFPRules<BuiltinType, Ty> > {
607
608   static Constant *Add(const ConstantFP *V1, const ConstantFP *V2) {
609     BuiltinType R = (BuiltinType)V1->getValue() + 
610                     (BuiltinType)V2->getValue();
611     return ConstantFP::get(*Ty, R);
612   }
613
614   static Constant *Sub(const ConstantFP *V1, const ConstantFP *V2) {
615     BuiltinType R = (BuiltinType)V1->getValue() - (BuiltinType)V2->getValue();
616     return ConstantFP::get(*Ty, R);
617   }
618
619   static Constant *Mul(const ConstantFP *V1, const ConstantFP *V2) {
620     BuiltinType R = (BuiltinType)V1->getValue() * (BuiltinType)V2->getValue();
621     return ConstantFP::get(*Ty, R);
622   }
623
624   static Constant *LessThan(const ConstantFP *V1, const ConstantFP *V2) {
625     bool R = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
626     return ConstantBool::get(R);
627   }
628
629   static Constant *EqualTo(const ConstantFP *V1, const ConstantFP *V2) {
630     bool R = (BuiltinType)V1->getValue() == (BuiltinType)V2->getValue();
631     return ConstantBool::get(R);
632   }
633
634   static Constant *CastToPointer(const ConstantFP *V,
635                                  const PointerType *PTy) {
636     if (V->isNullValue())    // Is it a FP or Integral null value?
637       return ConstantPointerNull::get(PTy);
638     return 0;  // Can't const prop other types of pointers
639   }
640
641   // Casting operators.  ick
642 #define DEF_CAST(TYPE, CLASS, CTYPE) \
643   static Constant *CastTo##TYPE  (const ConstantFP *V) {    \
644     return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
645   }
646
647   DEF_CAST(Bool  , ConstantBool, bool)
648   DEF_CAST(SByte , ConstantInt, signed char)
649   DEF_CAST(UByte , ConstantInt, unsigned char)
650   DEF_CAST(Short , ConstantInt, signed short)
651   DEF_CAST(UShort, ConstantInt, unsigned short)
652   DEF_CAST(Int   , ConstantInt, signed int)
653   DEF_CAST(UInt  , ConstantInt, unsigned int)
654   DEF_CAST(Long  , ConstantInt, int64_t)
655   DEF_CAST(ULong , ConstantInt, uint64_t)
656   DEF_CAST(Float , ConstantFP , float)
657   DEF_CAST(Double, ConstantFP , double)
658 #undef DEF_CAST
659
660   static Constant *FRem(const ConstantFP *V1, const ConstantFP *V2) {
661     if (V2->isNullValue()) return 0;
662     BuiltinType Result = std::fmod((BuiltinType)V1->getValue(),
663                                    (BuiltinType)V2->getValue());
664     return ConstantFP::get(*Ty, Result);
665   }
666   static Constant *FDiv(const ConstantFP *V1, const ConstantFP *V2) {
667     BuiltinType inf = std::numeric_limits<BuiltinType>::infinity();
668     if (V2->isExactlyValue(0.0)) return ConstantFP::get(*Ty, inf);
669     if (V2->isExactlyValue(-0.0)) return ConstantFP::get(*Ty, -inf);
670     BuiltinType R = (BuiltinType)V1->getValue() / (BuiltinType)V2->getValue();
671     return ConstantFP::get(*Ty, R);
672   }
673 };
674 }  // end anonymous namespace
675
676 static ManagedStatic<EmptyRules>       EmptyR;
677 static ManagedStatic<BoolRules>        BoolR;
678 static ManagedStatic<NullPointerRules> NullPointerR;
679 static ManagedStatic<ConstantPackedRules> ConstantPackedR;
680 static ManagedStatic<GeneralPackedRules> GeneralPackedR;
681 static ManagedStatic<DirectIntRules<signed char   , &Type::SByteTy> > SByteR;
682 static ManagedStatic<DirectIntRules<unsigned char , &Type::UByteTy> > UByteR;
683 static ManagedStatic<DirectIntRules<signed short  , &Type::ShortTy> > ShortR;
684 static ManagedStatic<DirectIntRules<unsigned short, &Type::UShortTy> > UShortR;
685 static ManagedStatic<DirectIntRules<signed int    , &Type::IntTy> >   IntR;
686 static ManagedStatic<DirectIntRules<unsigned int  , &Type::UIntTy> >  UIntR;
687 static ManagedStatic<DirectIntRules<int64_t       , &Type::LongTy> >  LongR;
688 static ManagedStatic<DirectIntRules<uint64_t      , &Type::ULongTy> > ULongR;
689 static ManagedStatic<DirectFPRules <float         , &Type::FloatTy> > FloatR;
690 static ManagedStatic<DirectFPRules <double        , &Type::DoubleTy> > DoubleR;
691
692 /// ConstRules::get - This method returns the constant rules implementation that
693 /// implements the semantics of the two specified constants.
694 ConstRules &ConstRules::get(const Constant *V1, const Constant *V2) {
695   if (isa<ConstantExpr>(V1) || isa<ConstantExpr>(V2) ||
696       isa<GlobalValue>(V1) || isa<GlobalValue>(V2) ||
697       isa<UndefValue>(V1) || isa<UndefValue>(V2))
698     return *EmptyR;
699
700   switch (V1->getType()->getTypeID()) {
701   default: assert(0 && "Unknown value type for constant folding!");
702   case Type::BoolTyID:    return *BoolR;
703   case Type::PointerTyID: return *NullPointerR;
704   case Type::SByteTyID:   return *SByteR;
705   case Type::UByteTyID:   return *UByteR;
706   case Type::ShortTyID:   return *ShortR;
707   case Type::UShortTyID:  return *UShortR;
708   case Type::IntTyID:     return *IntR;
709   case Type::UIntTyID:    return *UIntR;
710   case Type::LongTyID:    return *LongR;
711   case Type::ULongTyID:   return *ULongR;
712   case Type::FloatTyID:   return *FloatR;
713   case Type::DoubleTyID:  return *DoubleR;
714   case Type::PackedTyID:
715     if (isa<ConstantPacked>(V1) && isa<ConstantPacked>(V2))
716       return *ConstantPackedR;
717     return *GeneralPackedR; // Constant folding rules for ConstantAggregateZero.
718   }
719 }
720
721
722 //===----------------------------------------------------------------------===//
723 //                ConstantFold*Instruction Implementations
724 //===----------------------------------------------------------------------===//
725 //
726 // These methods contain the special case hackery required to symbolically
727 // evaluate some constant expression cases, and use the ConstantRules class to
728 // evaluate normal constants.
729 //
730 static unsigned getSize(const Type *Ty) {
731   unsigned S = Ty->getPrimitiveSize();
732   return S ? S : 8;  // Treat pointers at 8 bytes
733 }
734
735 /// CastConstantPacked - Convert the specified ConstantPacked node to the
736 /// specified packed type.  At this point, we know that the elements of the
737 /// input packed constant are all simple integer or FP values.
738 static Constant *CastConstantPacked(ConstantPacked *CP,
739                                     const PackedType *DstTy) {
740   unsigned SrcNumElts = CP->getType()->getNumElements();
741   unsigned DstNumElts = DstTy->getNumElements();
742   const Type *SrcEltTy = CP->getType()->getElementType();
743   const Type *DstEltTy = DstTy->getElementType();
744   
745   // If both vectors have the same number of elements (thus, the elements
746   // are the same size), perform the conversion now.
747   if (SrcNumElts == DstNumElts) {
748     std::vector<Constant*> Result;
749     
750     // If the src and dest elements are both integers, just cast each one
751     // which will do the appropriate bit-convert.
752     if (SrcEltTy->isIntegral() && DstEltTy->isIntegral()) {
753       for (unsigned i = 0; i != SrcNumElts; ++i)
754         Result.push_back(ConstantExpr::getCast(CP->getOperand(i),
755                                                DstEltTy));
756       return ConstantPacked::get(Result);
757     }
758     
759     if (SrcEltTy->isIntegral()) {
760       // Otherwise, this is an int-to-fp cast.
761       assert(DstEltTy->isFloatingPoint());
762       if (DstEltTy->getTypeID() == Type::DoubleTyID) {
763         for (unsigned i = 0; i != SrcNumElts; ++i) {
764           double V =
765             BitsToDouble(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
766           Result.push_back(ConstantFP::get(Type::DoubleTy, V));
767         }
768         return ConstantPacked::get(Result);
769       }
770       assert(DstEltTy == Type::FloatTy && "Unknown fp type!");
771       for (unsigned i = 0; i != SrcNumElts; ++i) {
772         float V =
773         BitsToFloat(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
774         Result.push_back(ConstantFP::get(Type::FloatTy, V));
775       }
776       return ConstantPacked::get(Result);
777     }
778     
779     // Otherwise, this is an fp-to-int cast.
780     assert(SrcEltTy->isFloatingPoint() && DstEltTy->isIntegral());
781     
782     if (SrcEltTy->getTypeID() == Type::DoubleTyID) {
783       for (unsigned i = 0; i != SrcNumElts; ++i) {
784         uint64_t V =
785           DoubleToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
786         Constant *C = ConstantInt::get(Type::ULongTy, V);
787         Result.push_back(ConstantExpr::getCast(C, DstEltTy));
788       }
789       return ConstantPacked::get(Result);
790     }
791
792     assert(SrcEltTy->getTypeID() == Type::FloatTyID);
793     for (unsigned i = 0; i != SrcNumElts; ++i) {
794       uint32_t V = FloatToBits(cast<ConstantFP>(CP->getOperand(i))->getValue());
795       Constant *C = ConstantInt::get(Type::UIntTy, V);
796       Result.push_back(ConstantExpr::getCast(C, DstEltTy));
797     }
798     return ConstantPacked::get(Result);
799   }
800   
801   // Otherwise, this is a cast that changes element count and size.  Handle
802   // casts which shrink the elements here.
803   
804   // FIXME: We need to know endianness to do this!
805   
806   return 0;
807 }
808
809
810 Constant *llvm::ConstantFoldCastInstruction(const Constant *V,
811                                             const Type *DestTy) {
812   if (V->getType() == DestTy) return (Constant*)V;
813
814   // Cast of a global address to boolean is always true.
815   if (isa<GlobalValue>(V)) {
816     if (DestTy == Type::BoolTy)
817       // FIXME: When we support 'external weak' references, we have to prevent
818       // this transformation from happening.  This code will need to be updated
819       // to ignore external weak symbols when we support it.
820       return ConstantBool::getTrue();
821   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
822     if (CE->getOpcode() == Instruction::Cast) {
823       Constant *Op = const_cast<Constant*>(CE->getOperand(0));
824       // Try to not produce a cast of a cast, which is almost always redundant.
825       if (!Op->getType()->isFloatingPoint() &&
826           !CE->getType()->isFloatingPoint() &&
827           !DestTy->isFloatingPoint()) {
828         unsigned S1 = getSize(Op->getType()), S2 = getSize(CE->getType());
829         unsigned S3 = getSize(DestTy);
830         if (Op->getType() == DestTy && S3 >= S2)
831           return Op;
832         if (S1 >= S2 && S2 >= S3)
833           return ConstantExpr::getCast(Op, DestTy);
834         if (S1 <= S2 && S2 >= S3 && S1 <= S3)
835           return ConstantExpr::getCast(Op, DestTy);
836       }
837     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
838       // If all of the indexes in the GEP are null values, there is no pointer
839       // adjustment going on.  We might as well cast the source pointer.
840       bool isAllNull = true;
841       for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
842         if (!CE->getOperand(i)->isNullValue()) {
843           isAllNull = false;
844           break;
845         }
846       if (isAllNull)
847         return ConstantExpr::getCast(CE->getOperand(0), DestTy);
848     }
849   } else if (isa<UndefValue>(V)) {
850     return UndefValue::get(DestTy);
851   }
852
853   // Check to see if we are casting an pointer to an aggregate to a pointer to
854   // the first element.  If so, return the appropriate GEP instruction.
855   if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
856     if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy)) {
857       std::vector<Value*> IdxList;
858       IdxList.push_back(Constant::getNullValue(Type::IntTy));
859       const Type *ElTy = PTy->getElementType();
860       while (ElTy != DPTy->getElementType()) {
861         if (const StructType *STy = dyn_cast<StructType>(ElTy)) {
862           if (STy->getNumElements() == 0) break;
863           ElTy = STy->getElementType(0);
864           IdxList.push_back(Constant::getNullValue(Type::UIntTy));
865         } else if (const SequentialType *STy = dyn_cast<SequentialType>(ElTy)) {
866           if (isa<PointerType>(ElTy)) break;  // Can't index into pointers!
867           ElTy = STy->getElementType();
868           IdxList.push_back(IdxList[0]);
869         } else {
870           break;
871         }
872       }
873
874       if (ElTy == DPTy->getElementType())
875         return ConstantExpr::getGetElementPtr(const_cast<Constant*>(V),IdxList);
876     }
877       
878   // Handle casts from one packed constant to another.  We know that the src and
879   // dest type have the same size.
880   if (const PackedType *DestPTy = dyn_cast<PackedType>(DestTy)) {
881     if (const PackedType *SrcTy = dyn_cast<PackedType>(V->getType())) {
882       assert(DestPTy->getElementType()->getPrimitiveSizeInBits() * 
883                  DestPTy->getNumElements()  ==
884              SrcTy->getElementType()->getPrimitiveSizeInBits() * 
885              SrcTy->getNumElements() && "Not cast between same sized vectors!");
886       if (isa<ConstantAggregateZero>(V))
887         return Constant::getNullValue(DestTy);
888       if (isa<UndefValue>(V))
889         return UndefValue::get(DestTy);
890       if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
891         // This is a cast from a ConstantPacked of one type to a ConstantPacked
892         // of another type.  Check to see if all elements of the input are
893         // simple.
894         bool AllSimpleConstants = true;
895         for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
896           if (!isa<ConstantInt>(CP->getOperand(i)) &&
897               !isa<ConstantFP>(CP->getOperand(i))) {
898             AllSimpleConstants = false;
899             break;
900           }
901         }
902             
903         // If all of the elements are simple constants, we can fold this.
904         if (AllSimpleConstants)
905           return CastConstantPacked(const_cast<ConstantPacked*>(CP), DestPTy);
906       }
907     }
908   }
909
910   ConstRules &Rules = ConstRules::get(V, V);
911
912   switch (DestTy->getTypeID()) {
913   case Type::BoolTyID:    return Rules.castToBool(V);
914   case Type::UByteTyID:   return Rules.castToUByte(V);
915   case Type::SByteTyID:   return Rules.castToSByte(V);
916   case Type::UShortTyID:  return Rules.castToUShort(V);
917   case Type::ShortTyID:   return Rules.castToShort(V);
918   case Type::UIntTyID:    return Rules.castToUInt(V);
919   case Type::IntTyID:     return Rules.castToInt(V);
920   case Type::ULongTyID:   return Rules.castToULong(V);
921   case Type::LongTyID:    return Rules.castToLong(V);
922   case Type::FloatTyID:   return Rules.castToFloat(V);
923   case Type::DoubleTyID:  return Rules.castToDouble(V);
924   case Type::PointerTyID:
925     return Rules.castToPointer(V, cast<PointerType>(DestTy));
926   default: return 0;
927   }
928 }
929
930 Constant *llvm::ConstantFoldSelectInstruction(const Constant *Cond,
931                                               const Constant *V1,
932                                               const Constant *V2) {
933   if (const ConstantBool *CB = dyn_cast<ConstantBool>(Cond))
934     return const_cast<Constant*>(CB->getValue() ? V1 : V2);
935
936   if (isa<UndefValue>(V1)) return const_cast<Constant*>(V2);
937   if (isa<UndefValue>(V2)) return const_cast<Constant*>(V1);
938   if (isa<UndefValue>(Cond)) return const_cast<Constant*>(V1);
939   if (V1 == V2) return const_cast<Constant*>(V1);
940   return 0;
941 }
942
943 Constant *llvm::ConstantFoldExtractElementInstruction(const Constant *Val,
944                                                       const Constant *Idx) {
945   if (isa<UndefValue>(Val))  // ee(undef, x) -> undef
946     return UndefValue::get(cast<PackedType>(Val->getType())->getElementType());
947   if (Val->isNullValue())  // ee(zero, x) -> zero
948     return Constant::getNullValue(
949                           cast<PackedType>(Val->getType())->getElementType());
950   
951   if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
952     if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx)) {
953       return const_cast<Constant*>(CVal->getOperand(CIdx->getZExtValue()));
954     } else if (isa<UndefValue>(Idx)) {
955       // ee({w,x,y,z}, undef) -> w (an arbitrary value).
956       return const_cast<Constant*>(CVal->getOperand(0));
957     }
958   }
959   return 0;
960 }
961
962 Constant *llvm::ConstantFoldInsertElementInstruction(const Constant *Val,
963                                                      const Constant *Elt,
964                                                      const Constant *Idx) {
965   const ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
966   if (!CIdx) return 0;
967   uint64_t idxVal = CIdx->getZExtValue();
968   if (isa<UndefValue>(Val)) { 
969     // Insertion of scalar constant into packed undef
970     // Optimize away insertion of undef
971     if (isa<UndefValue>(Elt))
972       return const_cast<Constant*>(Val);
973     // Otherwise break the aggregate undef into multiple undefs and do
974     // the insertion
975     unsigned numOps = 
976       cast<PackedType>(Val->getType())->getNumElements();
977     std::vector<Constant*> Ops; 
978     Ops.reserve(numOps);
979     for (unsigned i = 0; i < numOps; ++i) {
980       const Constant *Op =
981         (i == idxVal) ? Elt : UndefValue::get(Elt->getType());
982       Ops.push_back(const_cast<Constant*>(Op));
983     }
984     return ConstantPacked::get(Ops);
985   }
986   if (isa<ConstantAggregateZero>(Val)) {
987     // Insertion of scalar constant into packed aggregate zero
988     // Optimize away insertion of zero
989     if (Elt->isNullValue())
990       return const_cast<Constant*>(Val);
991     // Otherwise break the aggregate zero into multiple zeros and do
992     // the insertion
993     unsigned numOps = 
994       cast<PackedType>(Val->getType())->getNumElements();
995     std::vector<Constant*> Ops; 
996     Ops.reserve(numOps);
997     for (unsigned i = 0; i < numOps; ++i) {
998       const Constant *Op =
999         (i == idxVal) ? Elt : Constant::getNullValue(Elt->getType());
1000       Ops.push_back(const_cast<Constant*>(Op));
1001     }
1002     return ConstantPacked::get(Ops);
1003   }
1004   if (const ConstantPacked *CVal = dyn_cast<ConstantPacked>(Val)) {
1005     // Insertion of scalar constant into packed constant
1006     std::vector<Constant*> Ops; 
1007     Ops.reserve(CVal->getNumOperands());
1008     for (unsigned i = 0; i < CVal->getNumOperands(); ++i) {
1009       const Constant *Op =
1010         (i == idxVal) ? Elt : cast<Constant>(CVal->getOperand(i));
1011       Ops.push_back(const_cast<Constant*>(Op));
1012     }
1013     return ConstantPacked::get(Ops);
1014   }
1015   return 0;
1016 }
1017
1018 Constant *llvm::ConstantFoldShuffleVectorInstruction(const Constant *V1,
1019                                                      const Constant *V2,
1020                                                      const Constant *Mask) {
1021   // TODO:
1022   return 0;
1023 }
1024
1025
1026 /// isZeroSizedType - This type is zero sized if its an array or structure of
1027 /// zero sized types.  The only leaf zero sized type is an empty structure.
1028 static bool isMaybeZeroSizedType(const Type *Ty) {
1029   if (isa<OpaqueType>(Ty)) return true;  // Can't say.
1030   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1031
1032     // If all of elements have zero size, this does too.
1033     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1034       if (!isMaybeZeroSizedType(STy->getElementType(i))) return false;
1035     return true;
1036
1037   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1038     return isMaybeZeroSizedType(ATy->getElementType());
1039   }
1040   return false;
1041 }
1042
1043 /// IdxCompare - Compare the two constants as though they were getelementptr
1044 /// indices.  This allows coersion of the types to be the same thing.
1045 ///
1046 /// If the two constants are the "same" (after coersion), return 0.  If the
1047 /// first is less than the second, return -1, if the second is less than the
1048 /// first, return 1.  If the constants are not integral, return -2.
1049 ///
1050 static int IdxCompare(Constant *C1, Constant *C2, const Type *ElTy) {
1051   if (C1 == C2) return 0;
1052
1053   // Ok, we found a different index.  Are either of the operands
1054   // ConstantExprs?  If so, we can't do anything with them.
1055   if (!isa<ConstantInt>(C1) || !isa<ConstantInt>(C2))
1056     return -2; // don't know!
1057
1058   // Ok, we have two differing integer indices.  Sign extend them to be the same
1059   // type.  Long is always big enough, so we use it.
1060   C1 = ConstantExpr::getSignExtend(C1, Type::LongTy);
1061   C2 = ConstantExpr::getSignExtend(C2, Type::LongTy);
1062   if (C1 == C2) return 0;  // Are they just differing types?
1063
1064   // If the type being indexed over is really just a zero sized type, there is
1065   // no pointer difference being made here.
1066   if (isMaybeZeroSizedType(ElTy))
1067     return -2; // dunno.
1068
1069   // If they are really different, now that they are the same type, then we
1070   // found a difference!
1071   if (cast<ConstantInt>(C1)->getSExtValue() < 
1072       cast<ConstantInt>(C2)->getSExtValue())
1073     return -1;
1074   else
1075     return 1;
1076 }
1077
1078 /// evaluateRelation - This function determines if there is anything we can
1079 /// decide about the two constants provided.  This doesn't need to handle simple
1080 /// things like integer comparisons, but should instead handle ConstantExprs
1081 /// and GlobalValuess.  If we can determine that the two constants have a
1082 /// particular relation to each other, we should return the corresponding SetCC
1083 /// code, otherwise return Instruction::BinaryOpsEnd.
1084 ///
1085 /// To simplify this code we canonicalize the relation so that the first
1086 /// operand is always the most "complex" of the two.  We consider simple
1087 /// constants (like ConstantInt) to be the simplest, followed by
1088 /// GlobalValues, followed by ConstantExpr's (the most complex).
1089 ///
1090 static Instruction::BinaryOps evaluateRelation(Constant *V1, Constant *V2) {
1091   assert(V1->getType() == V2->getType() &&
1092          "Cannot compare different types of values!");
1093   if (V1 == V2) return Instruction::SetEQ;
1094
1095   if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1)) {
1096     if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2)) {
1097       // We distilled this down to a simple case, use the standard constant
1098       // folder.
1099       ConstantBool *R = dyn_cast<ConstantBool>(ConstantExpr::getSetEQ(V1, V2));
1100       if (R && R->getValue()) return Instruction::SetEQ;
1101       R = dyn_cast<ConstantBool>(ConstantExpr::getSetLT(V1, V2));
1102       if (R && R->getValue()) return Instruction::SetLT;
1103       R = dyn_cast<ConstantBool>(ConstantExpr::getSetGT(V1, V2));
1104       if (R && R->getValue()) return Instruction::SetGT;
1105       
1106       // If we couldn't figure it out, bail.
1107       return Instruction::BinaryOpsEnd;
1108     }
1109     
1110     // If the first operand is simple, swap operands.
1111     Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
1112     if (SwappedRelation != Instruction::BinaryOpsEnd)
1113       return SetCondInst::getSwappedCondition(SwappedRelation);
1114
1115   } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(V1)) {
1116     if (isa<ConstantExpr>(V2)) {  // Swap as necessary.
1117       Instruction::BinaryOps SwappedRelation = evaluateRelation(V2, V1);
1118       if (SwappedRelation != Instruction::BinaryOpsEnd)
1119         return SetCondInst::getSwappedCondition(SwappedRelation);
1120       else
1121         return Instruction::BinaryOpsEnd;
1122     }
1123
1124     // Now we know that the RHS is a GlobalValue or simple constant,
1125     // which (since the types must match) means that it's a ConstantPointerNull.
1126     if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1127       assert(CPR1 != CPR2 &&
1128              "GVs for the same value exist at different addresses??");
1129       // FIXME: If both globals are external weak, they might both be null!
1130       return Instruction::SetNE;
1131     } else {
1132       assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
1133       // Global can never be null.  FIXME: if we implement external weak
1134       // linkage, this is not necessarily true!
1135       return Instruction::SetNE;
1136     }
1137
1138   } else {
1139     // Ok, the LHS is known to be a constantexpr.  The RHS can be any of a
1140     // constantexpr, a CPR, or a simple constant.
1141     ConstantExpr *CE1 = cast<ConstantExpr>(V1);
1142     Constant *CE1Op0 = CE1->getOperand(0);
1143
1144     switch (CE1->getOpcode()) {
1145     case Instruction::Cast:
1146       // If the cast is not actually changing bits, and the second operand is a
1147       // null pointer, do the comparison with the pre-casted value.
1148       if (V2->isNullValue() &&
1149           (isa<PointerType>(CE1->getType()) || CE1->getType()->isIntegral()))
1150         return evaluateRelation(CE1Op0,
1151                                 Constant::getNullValue(CE1Op0->getType()));
1152
1153       // If the dest type is a pointer type, and the RHS is a constantexpr cast
1154       // from the same type as the src of the LHS, evaluate the inputs.  This is
1155       // important for things like "seteq (cast 4 to int*), (cast 5 to int*)",
1156       // which happens a lot in compilers with tagged integers.
1157       if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(V2))
1158         if (isa<PointerType>(CE1->getType()) && 
1159             CE2->getOpcode() == Instruction::Cast &&
1160             CE1->getOperand(0)->getType() == CE2->getOperand(0)->getType() &&
1161             CE1->getOperand(0)->getType()->isIntegral()) {
1162           return evaluateRelation(CE1->getOperand(0), CE2->getOperand(0));
1163         }
1164       break;
1165
1166     case Instruction::GetElementPtr:
1167       // Ok, since this is a getelementptr, we know that the constant has a
1168       // pointer type.  Check the various cases.
1169       if (isa<ConstantPointerNull>(V2)) {
1170         // If we are comparing a GEP to a null pointer, check to see if the base
1171         // of the GEP equals the null pointer.
1172         if (isa<GlobalValue>(CE1Op0)) {
1173           // FIXME: this is not true when we have external weak references!
1174           // No offset can go from a global to a null pointer.
1175           return Instruction::SetGT;
1176         } else if (isa<ConstantPointerNull>(CE1Op0)) {
1177           // If we are indexing from a null pointer, check to see if we have any
1178           // non-zero indices.
1179           for (unsigned i = 1, e = CE1->getNumOperands(); i != e; ++i)
1180             if (!CE1->getOperand(i)->isNullValue())
1181               // Offsetting from null, must not be equal.
1182               return Instruction::SetGT;
1183           // Only zero indexes from null, must still be zero.
1184           return Instruction::SetEQ;
1185         }
1186         // Otherwise, we can't really say if the first operand is null or not.
1187       } else if (const GlobalValue *CPR2 = dyn_cast<GlobalValue>(V2)) {
1188         if (isa<ConstantPointerNull>(CE1Op0)) {
1189           // FIXME: This is not true with external weak references.
1190           return Instruction::SetLT;
1191         } else if (const GlobalValue *CPR1 = dyn_cast<GlobalValue>(CE1Op0)) {
1192           if (CPR1 == CPR2) {
1193             // If this is a getelementptr of the same global, then it must be
1194             // different.  Because the types must match, the getelementptr could
1195             // only have at most one index, and because we fold getelementptr's
1196             // with a single zero index, it must be nonzero.
1197             assert(CE1->getNumOperands() == 2 &&
1198                    !CE1->getOperand(1)->isNullValue() &&
1199                    "Suprising getelementptr!");
1200             return Instruction::SetGT;
1201           } else {
1202             // If they are different globals, we don't know what the value is,
1203             // but they can't be equal.
1204             return Instruction::SetNE;
1205           }
1206         }
1207       } else {
1208         const ConstantExpr *CE2 = cast<ConstantExpr>(V2);
1209         const Constant *CE2Op0 = CE2->getOperand(0);
1210
1211         // There are MANY other foldings that we could perform here.  They will
1212         // probably be added on demand, as they seem needed.
1213         switch (CE2->getOpcode()) {
1214         default: break;
1215         case Instruction::GetElementPtr:
1216           // By far the most common case to handle is when the base pointers are
1217           // obviously to the same or different globals.
1218           if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
1219             if (CE1Op0 != CE2Op0) // Don't know relative ordering, but not equal
1220               return Instruction::SetNE;
1221             // Ok, we know that both getelementptr instructions are based on the
1222             // same global.  From this, we can precisely determine the relative
1223             // ordering of the resultant pointers.
1224             unsigned i = 1;
1225
1226             // Compare all of the operands the GEP's have in common.
1227             gep_type_iterator GTI = gep_type_begin(CE1);
1228             for (;i != CE1->getNumOperands() && i != CE2->getNumOperands();
1229                  ++i, ++GTI)
1230               switch (IdxCompare(CE1->getOperand(i), CE2->getOperand(i),
1231                                  GTI.getIndexedType())) {
1232               case -1: return Instruction::SetLT;
1233               case 1:  return Instruction::SetGT;
1234               case -2: return Instruction::BinaryOpsEnd;
1235               }
1236
1237             // Ok, we ran out of things they have in common.  If any leftovers
1238             // are non-zero then we have a difference, otherwise we are equal.
1239             for (; i < CE1->getNumOperands(); ++i)
1240               if (!CE1->getOperand(i)->isNullValue())
1241                 if (isa<ConstantIntegral>(CE1->getOperand(i)))
1242                   return Instruction::SetGT;
1243                 else
1244                   return Instruction::BinaryOpsEnd; // Might be equal.
1245
1246             for (; i < CE2->getNumOperands(); ++i)
1247               if (!CE2->getOperand(i)->isNullValue())
1248                 if (isa<ConstantIntegral>(CE2->getOperand(i)))
1249                   return Instruction::SetLT;
1250                 else
1251                   return Instruction::BinaryOpsEnd; // Might be equal.
1252             return Instruction::SetEQ;
1253           }
1254         }
1255       }
1256
1257     default:
1258       break;
1259     }
1260   }
1261
1262   return Instruction::BinaryOpsEnd;
1263 }
1264
1265 Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode,
1266                                               const Constant *V1,
1267                                               const Constant *V2) {
1268   Constant *C = 0;
1269   switch (Opcode) {
1270   default:                   break;
1271   case Instruction::Add:     C = ConstRules::get(V1, V2).add(V1, V2); break;
1272   case Instruction::Sub:     C = ConstRules::get(V1, V2).sub(V1, V2); break;
1273   case Instruction::Mul:     C = ConstRules::get(V1, V2).mul(V1, V2); break;
1274   case Instruction::UDiv:    C = ConstRules::get(V1, V2).udiv(V1, V2); break;
1275   case Instruction::SDiv:    C = ConstRules::get(V1, V2).sdiv(V1, V2); break;
1276   case Instruction::FDiv:    C = ConstRules::get(V1, V2).fdiv(V1, V2); break;
1277   case Instruction::URem:    C = ConstRules::get(V1, V2).urem(V1, V2); break;
1278   case Instruction::SRem:    C = ConstRules::get(V1, V2).srem(V1, V2); break;
1279   case Instruction::FRem:    C = ConstRules::get(V1, V2).frem(V1, V2); break;
1280   case Instruction::And:     C = ConstRules::get(V1, V2).op_and(V1, V2); break;
1281   case Instruction::Or:      C = ConstRules::get(V1, V2).op_or (V1, V2); break;
1282   case Instruction::Xor:     C = ConstRules::get(V1, V2).op_xor(V1, V2); break;
1283   case Instruction::Shl:     C = ConstRules::get(V1, V2).shl(V1, V2); break;
1284   case Instruction::LShr:    C = ConstRules::get(V1, V2).lshr(V1, V2); break;
1285   case Instruction::AShr:    C = ConstRules::get(V1, V2).ashr(V1, V2); break;
1286   case Instruction::SetEQ:   C = ConstRules::get(V1, V2).equalto(V1, V2); break;
1287   case Instruction::SetLT:   C = ConstRules::get(V1, V2).lessthan(V1, V2);break;
1288   case Instruction::SetGT:   C = ConstRules::get(V1, V2).lessthan(V2, V1);break;
1289   case Instruction::SetNE:   // V1 != V2  ===  !(V1 == V2)
1290     C = ConstRules::get(V1, V2).equalto(V1, V2);
1291     if (C) return ConstantExpr::getNot(C);
1292     break;
1293   case Instruction::SetLE:   // V1 <= V2  ===  !(V2 < V1)
1294     C = ConstRules::get(V1, V2).lessthan(V2, V1);
1295     if (C) return ConstantExpr::getNot(C);
1296     break;
1297   case Instruction::SetGE:   // V1 >= V2  ===  !(V1 < V2)
1298     C = ConstRules::get(V1, V2).lessthan(V1, V2);
1299     if (C) return ConstantExpr::getNot(C);
1300     break;
1301   }
1302
1303   // If we successfully folded the expression, return it now.
1304   if (C) return C;
1305
1306   if (SetCondInst::isComparison(Opcode)) {
1307     if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1308       return UndefValue::get(Type::BoolTy);
1309     switch (evaluateRelation(const_cast<Constant*>(V1),
1310                              const_cast<Constant*>(V2))) {
1311     default: assert(0 && "Unknown relational!");
1312     case Instruction::BinaryOpsEnd:
1313       break;  // Couldn't determine anything about these constants.
1314     case Instruction::SetEQ:   // We know the constants are equal!
1315       // If we know the constants are equal, we can decide the result of this
1316       // computation precisely.
1317       return ConstantBool::get(Opcode == Instruction::SetEQ ||
1318                                Opcode == Instruction::SetLE ||
1319                                Opcode == Instruction::SetGE);
1320     case Instruction::SetLT:
1321       // If we know that V1 < V2, we can decide the result of this computation
1322       // precisely.
1323       return ConstantBool::get(Opcode == Instruction::SetLT ||
1324                                Opcode == Instruction::SetNE ||
1325                                Opcode == Instruction::SetLE);
1326     case Instruction::SetGT:
1327       // If we know that V1 > V2, we can decide the result of this computation
1328       // precisely.
1329       return ConstantBool::get(Opcode == Instruction::SetGT ||
1330                                Opcode == Instruction::SetNE ||
1331                                Opcode == Instruction::SetGE);
1332     case Instruction::SetLE:
1333       // If we know that V1 <= V2, we can only partially decide this relation.
1334       if (Opcode == Instruction::SetGT) return ConstantBool::getFalse();
1335       if (Opcode == Instruction::SetLT) return ConstantBool::getTrue();
1336       break;
1337
1338     case Instruction::SetGE:
1339       // If we know that V1 >= V2, we can only partially decide this relation.
1340       if (Opcode == Instruction::SetLT) return ConstantBool::getFalse();
1341       if (Opcode == Instruction::SetGT) return ConstantBool::getTrue();
1342       break;
1343
1344     case Instruction::SetNE:
1345       // If we know that V1 != V2, we can only partially decide this relation.
1346       if (Opcode == Instruction::SetEQ) return ConstantBool::getFalse();
1347       if (Opcode == Instruction::SetNE) return ConstantBool::getTrue();
1348       break;
1349     }
1350   }
1351
1352   if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) {
1353     switch (Opcode) {
1354     case Instruction::Add:
1355     case Instruction::Sub:
1356     case Instruction::Xor:
1357       return UndefValue::get(V1->getType());
1358
1359     case Instruction::Mul:
1360     case Instruction::And:
1361       return Constant::getNullValue(V1->getType());
1362     case Instruction::UDiv:
1363     case Instruction::SDiv:
1364     case Instruction::FDiv:
1365     case Instruction::URem:
1366     case Instruction::SRem:
1367     case Instruction::FRem:
1368       if (!isa<UndefValue>(V2))                    // undef / X -> 0
1369         return Constant::getNullValue(V1->getType());
1370       return const_cast<Constant*>(V2);            // X / undef -> undef
1371     case Instruction::Or:                          // X | undef -> -1
1372       return ConstantInt::getAllOnesValue(V1->getType());
1373     case Instruction::LShr:
1374       if (isa<UndefValue>(V2) && isa<UndefValue>(V1))
1375         return const_cast<Constant*>(V1);           // undef lshr undef -> undef
1376       return Constant::getNullValue(V1->getType()); // X lshr undef -> 0
1377                                                     // undef lshr X -> 0
1378     case Instruction::AShr:
1379       if (!isa<UndefValue>(V2))
1380         return const_cast<Constant*>(V1);           // undef ashr X --> undef
1381       else if (isa<UndefValue>(V1)) 
1382         return const_cast<Constant*>(V1);           // undef ashr undef -> undef
1383       else
1384         return const_cast<Constant*>(V1);           // X ashr undef --> X
1385     case Instruction::Shl:
1386       // undef << X -> 0   or   X << undef -> 0
1387       return Constant::getNullValue(V1->getType());
1388     }
1389   }
1390
1391   if (const ConstantExpr *CE1 = dyn_cast<ConstantExpr>(V1)) {
1392     if (isa<ConstantExpr>(V2)) {
1393       // There are many possible foldings we could do here.  We should probably
1394       // at least fold add of a pointer with an integer into the appropriate
1395       // getelementptr.  This will improve alias analysis a bit.
1396     } else {
1397       // Just implement a couple of simple identities.
1398       switch (Opcode) {
1399       case Instruction::Add:
1400         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X + 0 == X
1401         break;
1402       case Instruction::Sub:
1403         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X - 0 == X
1404         break;
1405       case Instruction::Mul:
1406         if (V2->isNullValue()) return const_cast<Constant*>(V2);  // X * 0 == 0
1407         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1408           if (CI->getZExtValue() == 1)
1409             return const_cast<Constant*>(V1);                     // X * 1 == X
1410         break;
1411       case Instruction::UDiv:
1412       case Instruction::SDiv:
1413         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1414           if (CI->getZExtValue() == 1)
1415             return const_cast<Constant*>(V1);                     // X / 1 == X
1416         break;
1417       case Instruction::URem:
1418       case Instruction::SRem:
1419         if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1420           if (CI->getZExtValue() == 1)
1421             return Constant::getNullValue(CI->getType());         // X % 1 == 0
1422         break;
1423       case Instruction::And:
1424         if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1425           return const_cast<Constant*>(V1);                       // X & -1 == X
1426         if (V2->isNullValue()) return const_cast<Constant*>(V2);  // X & 0 == 0
1427         if (CE1->getOpcode() == Instruction::Cast &&
1428             isa<GlobalValue>(CE1->getOperand(0))) {
1429           GlobalValue *CPR = cast<GlobalValue>(CE1->getOperand(0));
1430
1431           // Functions are at least 4-byte aligned.  If and'ing the address of a
1432           // function with a constant < 4, fold it to zero.
1433           if (const ConstantInt *CI = dyn_cast<ConstantInt>(V2))
1434             if (CI->getZExtValue() < 4 && isa<Function>(CPR))
1435               return Constant::getNullValue(CI->getType());
1436         }
1437         break;
1438       case Instruction::Or:
1439         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X | 0 == X
1440         if (cast<ConstantIntegral>(V2)->isAllOnesValue())
1441           return const_cast<Constant*>(V2);  // X | -1 == -1
1442         break;
1443       case Instruction::Xor:
1444         if (V2->isNullValue()) return const_cast<Constant*>(V1);  // X ^ 0 == X
1445         break;
1446       }
1447     }
1448
1449   } else if (isa<ConstantExpr>(V2)) {
1450     // If V2 is a constant expr and V1 isn't, flop them around and fold the
1451     // other way if possible.
1452     switch (Opcode) {
1453     case Instruction::Add:
1454     case Instruction::Mul:
1455     case Instruction::And:
1456     case Instruction::Or:
1457     case Instruction::Xor:
1458     case Instruction::SetEQ:
1459     case Instruction::SetNE:
1460       // No change of opcode required.
1461       return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1462
1463     case Instruction::SetLT:
1464     case Instruction::SetGT:
1465     case Instruction::SetLE:
1466     case Instruction::SetGE:
1467       // Change the opcode as necessary to swap the operands.
1468       Opcode = SetCondInst::getSwappedCondition((Instruction::BinaryOps)Opcode);
1469       return ConstantFoldBinaryInstruction(Opcode, V2, V1);
1470
1471     case Instruction::Shl:
1472     case Instruction::LShr:
1473     case Instruction::AShr:
1474     case Instruction::Sub:
1475     case Instruction::SDiv:
1476     case Instruction::UDiv:
1477     case Instruction::FDiv:
1478     case Instruction::URem:
1479     case Instruction::SRem:
1480     case Instruction::FRem:
1481     default:  // These instructions cannot be flopped around.
1482       break;
1483     }
1484   }
1485   return 0;
1486 }
1487
1488 Constant *llvm::ConstantFoldGetElementPtr(const Constant *C,
1489                                           const std::vector<Value*> &IdxList) {
1490   if (IdxList.size() == 0 ||
1491       (IdxList.size() == 1 && cast<Constant>(IdxList[0])->isNullValue()))
1492     return const_cast<Constant*>(C);
1493
1494   if (isa<UndefValue>(C)) {
1495     const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1496                                                        true);
1497     assert(Ty != 0 && "Invalid indices for GEP!");
1498     return UndefValue::get(PointerType::get(Ty));
1499   }
1500
1501   Constant *Idx0 = cast<Constant>(IdxList[0]);
1502   if (C->isNullValue()) {
1503     bool isNull = true;
1504     for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1505       if (!cast<Constant>(IdxList[i])->isNullValue()) {
1506         isNull = false;
1507         break;
1508       }
1509     if (isNull) {
1510       const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1511                                                          true);
1512       assert(Ty != 0 && "Invalid indices for GEP!");
1513       return ConstantPointerNull::get(PointerType::get(Ty));
1514     }
1515
1516     if (IdxList.size() == 1) {
1517       const Type *ElTy = cast<PointerType>(C->getType())->getElementType();
1518       if (uint32_t ElSize = ElTy->getPrimitiveSize()) {
1519         // gep null, C is equal to C*sizeof(nullty).  If nullty is a known llvm
1520         // type, we can statically fold this.
1521         Constant *R = ConstantInt::get(Type::UIntTy, ElSize);
1522         R = ConstantExpr::getCast(R, Idx0->getType());
1523         R = ConstantExpr::getMul(R, Idx0);
1524         return ConstantExpr::getCast(R, C->getType());
1525       }
1526     }
1527   }
1528
1529   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(const_cast<Constant*>(C))) {
1530     // Combine Indices - If the source pointer to this getelementptr instruction
1531     // is a getelementptr instruction, combine the indices of the two
1532     // getelementptr instructions into a single instruction.
1533     //
1534     if (CE->getOpcode() == Instruction::GetElementPtr) {
1535       const Type *LastTy = 0;
1536       for (gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
1537            I != E; ++I)
1538         LastTy = *I;
1539
1540       if ((LastTy && isa<ArrayType>(LastTy)) || Idx0->isNullValue()) {
1541         std::vector<Value*> NewIndices;
1542         NewIndices.reserve(IdxList.size() + CE->getNumOperands());
1543         for (unsigned i = 1, e = CE->getNumOperands()-1; i != e; ++i)
1544           NewIndices.push_back(CE->getOperand(i));
1545
1546         // Add the last index of the source with the first index of the new GEP.
1547         // Make sure to handle the case when they are actually different types.
1548         Constant *Combined = CE->getOperand(CE->getNumOperands()-1);
1549         // Otherwise it must be an array.
1550         if (!Idx0->isNullValue()) {
1551           const Type *IdxTy = Combined->getType();
1552           if (IdxTy != Idx0->getType()) IdxTy = Type::LongTy;
1553           Combined =
1554             ConstantExpr::get(Instruction::Add,
1555                               ConstantExpr::getCast(Idx0, IdxTy),
1556                               ConstantExpr::getCast(Combined, IdxTy));
1557         }
1558
1559         NewIndices.push_back(Combined);
1560         NewIndices.insert(NewIndices.end(), IdxList.begin()+1, IdxList.end());
1561         return ConstantExpr::getGetElementPtr(CE->getOperand(0), NewIndices);
1562       }
1563     }
1564
1565     // Implement folding of:
1566     //    int* getelementptr ([2 x int]* cast ([3 x int]* %X to [2 x int]*),
1567     //                        long 0, long 0)
1568     // To: int* getelementptr ([3 x int]* %X, long 0, long 0)
1569     //
1570     if (CE->getOpcode() == Instruction::Cast && IdxList.size() > 1 &&
1571         Idx0->isNullValue())
1572       if (const PointerType *SPT =
1573           dyn_cast<PointerType>(CE->getOperand(0)->getType()))
1574         if (const ArrayType *SAT = dyn_cast<ArrayType>(SPT->getElementType()))
1575           if (const ArrayType *CAT =
1576         dyn_cast<ArrayType>(cast<PointerType>(C->getType())->getElementType()))
1577             if (CAT->getElementType() == SAT->getElementType())
1578               return ConstantExpr::getGetElementPtr(
1579                       (Constant*)CE->getOperand(0), IdxList);
1580   }
1581   return 0;
1582 }
1583