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