IR support for extractvalue and insertvalue instructions. Also, begin
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Constant* classes...
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include <algorithm>
28 #include <map>
29 using namespace llvm;
30
31 //===----------------------------------------------------------------------===//
32 //                              Constant Class
33 //===----------------------------------------------------------------------===//
34
35 void Constant::destroyConstantImpl() {
36   // When a Constant is destroyed, there may be lingering
37   // references to the constant by other constants in the constant pool.  These
38   // constants are implicitly dependent on the module that is being deleted,
39   // but they don't know that.  Because we only find out when the CPV is
40   // deleted, we must now notify all of our users (that should only be
41   // Constants) that they are, in fact, invalid now and should be deleted.
42   //
43   while (!use_empty()) {
44     Value *V = use_back();
45 #ifndef NDEBUG      // Only in -g mode...
46     if (!isa<Constant>(V))
47       DOUT << "While deleting: " << *this
48            << "\n\nUse still stuck around after Def is destroyed: "
49            << *V << "\n\n";
50 #endif
51     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
52     Constant *CV = cast<Constant>(V);
53     CV->destroyConstant();
54
55     // The constant should remove itself from our use list...
56     assert((use_empty() || use_back() != V) && "Constant not removed!");
57   }
58
59   // Value has no outstanding references it is safe to delete it now...
60   delete this;
61 }
62
63 /// canTrap - Return true if evaluation of this constant could trap.  This is
64 /// true for things like constant expressions that could divide by zero.
65 bool Constant::canTrap() const {
66   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67   // The only thing that could possibly trap are constant exprs.
68   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69   if (!CE) return false;
70   
71   // ConstantExpr traps if any operands can trap. 
72   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73     if (getOperand(i)->canTrap()) 
74       return true;
75
76   // Otherwise, only specific operations can trap.
77   switch (CE->getOpcode()) {
78   default:
79     return false;
80   case Instruction::UDiv:
81   case Instruction::SDiv:
82   case Instruction::FDiv:
83   case Instruction::URem:
84   case Instruction::SRem:
85   case Instruction::FRem:
86     // Div and rem can trap if the RHS is not known to be non-zero.
87     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88       return true;
89     return false;
90   }
91 }
92
93 /// ContaintsRelocations - Return true if the constant value contains
94 /// relocations which cannot be resolved at compile time.
95 bool Constant::ContainsRelocations() const {
96   if (isa<GlobalValue>(this))
97     return true;
98   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99     if (getOperand(i)->ContainsRelocations())
100       return true;
101   return false;
102 }
103
104 // Static constructor to create a '0' constant of arbitrary type...
105 Constant *Constant::getNullValue(const Type *Ty) {
106   static uint64_t zero[2] = {0, 0};
107   switch (Ty->getTypeID()) {
108   case Type::IntegerTyID:
109     return ConstantInt::get(Ty, 0);
110   case Type::FloatTyID:
111     return ConstantFP::get(APFloat(APInt(32, 0)));
112   case Type::DoubleTyID:
113     return ConstantFP::get(APFloat(APInt(64, 0)));
114   case Type::X86_FP80TyID:
115     return ConstantFP::get(APFloat(APInt(80, 2, zero)));
116   case Type::FP128TyID:
117     return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
118   case Type::PPC_FP128TyID:
119     return ConstantFP::get(APFloat(APInt(128, 2, zero)));
120   case Type::PointerTyID:
121     return ConstantPointerNull::get(cast<PointerType>(Ty));
122   case Type::StructTyID:
123   case Type::ArrayTyID:
124   case Type::VectorTyID:
125     return ConstantAggregateZero::get(Ty);
126   default:
127     // Function, Label, or Opaque type?
128     assert(!"Cannot create a null constant of that type!");
129     return 0;
130   }
131 }
132
133 Constant *Constant::getAllOnesValue(const Type *Ty) {
134   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135     return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136   return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
137 }
138
139 // Static constructor to create an integral constant with all bits set
140 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
141   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
142     return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
143   return 0;
144 }
145
146 /// @returns the value for a vector integer constant of the given type that
147 /// has all its bits set to true.
148 /// @brief Get the all ones value
149 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
150   std::vector<Constant*> Elts;
151   Elts.resize(Ty->getNumElements(),
152               ConstantInt::getAllOnesValue(Ty->getElementType()));
153   assert(Elts[0] && "Not a vector integer type!");
154   return cast<ConstantVector>(ConstantVector::get(Elts));
155 }
156
157
158 //===----------------------------------------------------------------------===//
159 //                                ConstantInt
160 //===----------------------------------------------------------------------===//
161
162 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
163   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
164   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
165 }
166
167 ConstantInt *ConstantInt::TheTrueVal = 0;
168 ConstantInt *ConstantInt::TheFalseVal = 0;
169
170 namespace llvm {
171   void CleanupTrueFalse(void *) {
172     ConstantInt::ResetTrueFalse();
173   }
174 }
175
176 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
177
178 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
179   assert(TheTrueVal == 0 && TheFalseVal == 0);
180   TheTrueVal  = get(Type::Int1Ty, 1);
181   TheFalseVal = get(Type::Int1Ty, 0);
182   
183   // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
184   TrueFalseCleanup.Register();
185   
186   return WhichOne ? TheTrueVal : TheFalseVal;
187 }
188
189
190 namespace {
191   struct DenseMapAPIntKeyInfo {
192     struct KeyTy {
193       APInt val;
194       const Type* type;
195       KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
196       KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
197       bool operator==(const KeyTy& that) const {
198         return type == that.type && this->val == that.val;
199       }
200       bool operator!=(const KeyTy& that) const {
201         return !this->operator==(that);
202       }
203     };
204     static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
205     static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
206     static unsigned getHashValue(const KeyTy &Key) {
207       return DenseMapInfo<void*>::getHashValue(Key.type) ^ 
208         Key.val.getHashValue();
209     }
210     static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
211       return LHS == RHS;
212     }
213     static bool isPod() { return false; }
214   };
215 }
216
217
218 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*, 
219                  DenseMapAPIntKeyInfo> IntMapTy;
220 static ManagedStatic<IntMapTy> IntConstants;
221
222 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
223   const IntegerType *ITy = cast<IntegerType>(Ty);
224   return get(APInt(ITy->getBitWidth(), V, isSigned));
225 }
226
227 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
228 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
229 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
230 // compare APInt's of different widths, which would violate an APInt class
231 // invariant which generates an assertion.
232 ConstantInt *ConstantInt::get(const APInt& V) {
233   // Get the corresponding integer type for the bit width of the value.
234   const IntegerType *ITy = IntegerType::get(V.getBitWidth());
235   // get an existing value or the insertion position
236   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
237   ConstantInt *&Slot = (*IntConstants)[Key]; 
238   // if it exists, return it.
239   if (Slot)
240     return Slot;
241   // otherwise create a new one, insert it, and return it.
242   return Slot = new ConstantInt(ITy, V);
243 }
244
245 //===----------------------------------------------------------------------===//
246 //                                ConstantFP
247 //===----------------------------------------------------------------------===//
248
249 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
250   if (Ty == Type::FloatTy)
251     return &APFloat::IEEEsingle;
252   if (Ty == Type::DoubleTy)
253     return &APFloat::IEEEdouble;
254   if (Ty == Type::X86_FP80Ty)
255     return &APFloat::x87DoubleExtended;
256   else if (Ty == Type::FP128Ty)
257     return &APFloat::IEEEquad;
258   
259   assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
260   return &APFloat::PPCDoubleDouble;
261 }
262
263 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
264   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
265   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
266          "FP type Mismatch");
267 }
268
269 bool ConstantFP::isNullValue() const {
270   return Val.isZero() && !Val.isNegative();
271 }
272
273 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
274   APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
275   apf.changeSign();
276   return ConstantFP::get(apf);
277 }
278
279 bool ConstantFP::isExactlyValue(const APFloat& V) const {
280   return Val.bitwiseIsEqual(V);
281 }
282
283 namespace {
284   struct DenseMapAPFloatKeyInfo {
285     struct KeyTy {
286       APFloat val;
287       KeyTy(const APFloat& V) : val(V){}
288       KeyTy(const KeyTy& that) : val(that.val) {}
289       bool operator==(const KeyTy& that) const {
290         return this->val.bitwiseIsEqual(that.val);
291       }
292       bool operator!=(const KeyTy& that) const {
293         return !this->operator==(that);
294       }
295     };
296     static inline KeyTy getEmptyKey() { 
297       return KeyTy(APFloat(APFloat::Bogus,1));
298     }
299     static inline KeyTy getTombstoneKey() { 
300       return KeyTy(APFloat(APFloat::Bogus,2)); 
301     }
302     static unsigned getHashValue(const KeyTy &Key) {
303       return Key.val.getHashValue();
304     }
305     static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
306       return LHS == RHS;
307     }
308     static bool isPod() { return false; }
309   };
310 }
311
312 //---- ConstantFP::get() implementation...
313 //
314 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*, 
315                  DenseMapAPFloatKeyInfo> FPMapTy;
316
317 static ManagedStatic<FPMapTy> FPConstants;
318
319 ConstantFP *ConstantFP::get(const APFloat &V) {
320   DenseMapAPFloatKeyInfo::KeyTy Key(V);
321   ConstantFP *&Slot = (*FPConstants)[Key];
322   if (Slot) return Slot;
323   
324   const Type *Ty;
325   if (&V.getSemantics() == &APFloat::IEEEsingle)
326     Ty = Type::FloatTy;
327   else if (&V.getSemantics() == &APFloat::IEEEdouble)
328     Ty = Type::DoubleTy;
329   else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
330     Ty = Type::X86_FP80Ty;
331   else if (&V.getSemantics() == &APFloat::IEEEquad)
332     Ty = Type::FP128Ty;
333   else {
334     assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
335     Ty = Type::PPC_FP128Ty;
336   }
337   
338   return Slot = new ConstantFP(Ty, V);
339 }
340
341 /// get() - This returns a constant fp for the specified value in the
342 /// specified type.  This should only be used for simple constant values like
343 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
344 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
345   APFloat FV(V);
346   FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven);
347   return get(FV);
348 }
349
350 //===----------------------------------------------------------------------===//
351 //                            ConstantXXX Classes
352 //===----------------------------------------------------------------------===//
353
354
355 ConstantArray::ConstantArray(const ArrayType *T,
356                              const std::vector<Constant*> &V)
357   : Constant(T, ConstantArrayVal,
358              OperandTraits<ConstantArray>::op_end(this) - V.size(),
359              V.size()) {
360   assert(V.size() == T->getNumElements() &&
361          "Invalid initializer vector for constant array");
362   Use *OL = OperandList;
363   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
364        I != E; ++I, ++OL) {
365     Constant *C = *I;
366     assert((C->getType() == T->getElementType() ||
367             (T->isAbstract() &&
368              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
369            "Initializer for array element doesn't match array element type!");
370     OL->init(C, this);
371   }
372 }
373
374
375 ConstantStruct::ConstantStruct(const StructType *T,
376                                const std::vector<Constant*> &V)
377   : Constant(T, ConstantStructVal,
378              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
379              V.size()) {
380   assert(V.size() == T->getNumElements() &&
381          "Invalid initializer vector for constant structure");
382   Use *OL = OperandList;
383   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
384        I != E; ++I, ++OL) {
385     Constant *C = *I;
386     assert((C->getType() == T->getElementType(I-V.begin()) ||
387             ((T->getElementType(I-V.begin())->isAbstract() ||
388               C->getType()->isAbstract()) &&
389              T->getElementType(I-V.begin())->getTypeID() == 
390                    C->getType()->getTypeID())) &&
391            "Initializer for struct element doesn't match struct element type!");
392     OL->init(C, this);
393   }
394 }
395
396
397 ConstantVector::ConstantVector(const VectorType *T,
398                                const std::vector<Constant*> &V)
399   : Constant(T, ConstantVectorVal,
400              OperandTraits<ConstantVector>::op_end(this) - V.size(),
401              V.size()) {
402   Use *OL = OperandList;
403     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
404          I != E; ++I, ++OL) {
405       Constant *C = *I;
406       assert((C->getType() == T->getElementType() ||
407             (T->isAbstract() &&
408              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
409            "Initializer for vector element doesn't match vector element type!");
410     OL->init(C, this);
411   }
412 }
413
414
415 namespace llvm {
416 // We declare several classes private to this file, so use an anonymous
417 // namespace
418 namespace {
419
420 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
421 /// behind the scenes to implement unary constant exprs.
422 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
423   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
424 public:
425   // allocate space for exactly one operand
426   void *operator new(size_t s) {
427     return User::operator new(s, 1);
428   }
429   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
430     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
431     Op<0>() = C;
432   }
433   /// Transparently provide more efficient getOperand methods.
434   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
435 };
436
437 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
438 /// behind the scenes to implement binary constant exprs.
439 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
440   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
441 public:
442   // allocate space for exactly two operands
443   void *operator new(size_t s) {
444     return User::operator new(s, 2);
445   }
446   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
447     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
448     Op<0>().init(C1, this);
449     Op<1>().init(C2, this);
450   }
451   /// Transparently provide more efficient getOperand methods.
452   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
453 };
454
455 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
456 /// behind the scenes to implement select constant exprs.
457 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
458   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
459 public:
460   // allocate space for exactly three operands
461   void *operator new(size_t s) {
462     return User::operator new(s, 3);
463   }
464   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
465     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
466     Op<0>().init(C1, this);
467     Op<1>().init(C2, this);
468     Op<2>().init(C3, this);
469   }
470   /// Transparently provide more efficient getOperand methods.
471   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
472 };
473
474 /// ExtractElementConstantExpr - This class is private to
475 /// Constants.cpp, and is used behind the scenes to implement
476 /// extractelement constant exprs.
477 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
478   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
479 public:
480   // allocate space for exactly two operands
481   void *operator new(size_t s) {
482     return User::operator new(s, 2);
483   }
484   ExtractElementConstantExpr(Constant *C1, Constant *C2)
485     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
486                    Instruction::ExtractElement, &Op<0>(), 2) {
487     Op<0>().init(C1, this);
488     Op<1>().init(C2, this);
489   }
490   /// Transparently provide more efficient getOperand methods.
491   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
492 };
493
494 /// InsertElementConstantExpr - This class is private to
495 /// Constants.cpp, and is used behind the scenes to implement
496 /// insertelement constant exprs.
497 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
498   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
499 public:
500   // allocate space for exactly three operands
501   void *operator new(size_t s) {
502     return User::operator new(s, 3);
503   }
504   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
505     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
506                    &Op<0>(), 3) {
507     Op<0>().init(C1, this);
508     Op<1>().init(C2, this);
509     Op<2>().init(C3, this);
510   }
511   /// Transparently provide more efficient getOperand methods.
512   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
513 };
514
515 /// ShuffleVectorConstantExpr - This class is private to
516 /// Constants.cpp, and is used behind the scenes to implement
517 /// shufflevector constant exprs.
518 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
519   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
520 public:
521   // allocate space for exactly three operands
522   void *operator new(size_t s) {
523     return User::operator new(s, 3);
524   }
525   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
526   : ConstantExpr(C1->getType(), Instruction::ShuffleVector, 
527                  &Op<0>(), 3) {
528     Op<0>().init(C1, this);
529     Op<1>().init(C2, this);
530     Op<2>().init(C3, this);
531   }
532   /// Transparently provide more efficient getOperand methods.
533   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
534 };
535
536 /// ExtractValueConstantExpr - This class is private to
537 /// Constants.cpp, and is used behind the scenes to implement
538 /// extractvalue constant exprs.
539 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
540   ExtractValueConstantExpr(Constant *Agg, const std::vector<Constant*> &IdxList,
541                            const Type *DestTy);
542 public:
543   static ExtractValueConstantExpr *Create(Constant *Agg,
544                                           const std::vector<Constant*> &IdxList,
545                                           const Type *DestTy) {
546     return
547       new(IdxList.size() + 1) ExtractValueConstantExpr(Agg, IdxList, DestTy);
548   }
549   /// Transparently provide more efficient getOperand methods.
550   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
551 };
552
553 /// InsertValueConstantExpr - This class is private to
554 /// Constants.cpp, and is used behind the scenes to implement
555 /// insertvalue constant exprs.
556 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
557   InsertValueConstantExpr(Constant *Agg, Constant *Val,
558                           const std::vector<Constant*> &IdxList,
559                           const Type *DestTy);
560 public:
561   static InsertValueConstantExpr *Create(Constant *Agg, Constant *Val,
562                                          const std::vector<Constant*> &IdxList,
563                                          const Type *DestTy) {
564     return
565       new(IdxList.size() + 2) InsertValueConstantExpr(Agg, Val,
566                                                       IdxList, DestTy);
567   }
568   /// Transparently provide more efficient getOperand methods.
569   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
570 };
571
572
573 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
574 /// used behind the scenes to implement getelementpr constant exprs.
575 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
576   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
577                             const Type *DestTy);
578 public:
579   static GetElementPtrConstantExpr *Create(Constant *C,
580                                            const std::vector<Constant*>&IdxList,
581                                            const Type *DestTy) {
582     return new(IdxList.size() + 1)
583       GetElementPtrConstantExpr(C, IdxList, DestTy);
584   }
585   /// Transparently provide more efficient getOperand methods.
586   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
587 };
588
589 // CompareConstantExpr - This class is private to Constants.cpp, and is used
590 // behind the scenes to implement ICmp and FCmp constant expressions. This is
591 // needed in order to store the predicate value for these instructions.
592 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
593   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
594   // allocate space for exactly two operands
595   void *operator new(size_t s) {
596     return User::operator new(s, 2);
597   }
598   unsigned short predicate;
599   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
600                       unsigned short pred,  Constant* LHS, Constant* RHS)
601     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
602     Op<0>().init(LHS, this);
603     Op<1>().init(RHS, this);
604   }
605   /// Transparently provide more efficient getOperand methods.
606   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
607 };
608
609 } // end anonymous namespace
610
611 template <>
612 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
613 };
614 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
615
616 template <>
617 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
618 };
619 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
620
621 template <>
622 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
623 };
624 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
625
626 template <>
627 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
628 };
629 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
630
631 template <>
632 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
633 };
634 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
635
636 template <>
637 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
638 };
639 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
640
641 template <>
642 struct OperandTraits<ExtractValueConstantExpr> : VariadicOperandTraits<1> {
643 };
644
645 ExtractValueConstantExpr::ExtractValueConstantExpr
646   (Constant *Agg,
647    const std::vector<Constant*> &IdxList,
648    const Type *DestTy)
649     : ConstantExpr(DestTy, Instruction::ExtractValue,
650                    OperandTraits<ExtractValueConstantExpr>::op_end(this)
651                    - (IdxList.size()+1),
652                    IdxList.size()+1) {
653   OperandList[0].init(Agg, this);
654   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
655     OperandList[i+1].init(IdxList[i], this);
656 }
657
658 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
659
660 template <>
661 struct OperandTraits<InsertValueConstantExpr> : VariadicOperandTraits<2> {
662 };
663
664 InsertValueConstantExpr::InsertValueConstantExpr
665   (Constant *Agg, Constant *Val,
666    const std::vector<Constant*> &IdxList,
667    const Type *DestTy)
668     : ConstantExpr(DestTy, Instruction::InsertValue,
669                    OperandTraits<InsertValueConstantExpr>::op_end(this)
670                    - (IdxList.size()+2),
671                    IdxList.size()+2) {
672   OperandList[0].init(Agg, this);
673   OperandList[1].init(Val, this);
674   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
675     OperandList[i+2].init(IdxList[i], this);
676 }
677
678 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
679
680
681 template <>
682 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
683 };
684
685 GetElementPtrConstantExpr::GetElementPtrConstantExpr
686   (Constant *C,
687    const std::vector<Constant*> &IdxList,
688    const Type *DestTy)
689     : ConstantExpr(DestTy, Instruction::GetElementPtr,
690                    OperandTraits<GetElementPtrConstantExpr>::op_end(this)
691                    - (IdxList.size()+1),
692                    IdxList.size()+1) {
693   OperandList[0].init(C, this);
694   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
695     OperandList[i+1].init(IdxList[i], this);
696 }
697
698 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
699
700
701 template <>
702 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
703 };
704 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
705
706
707 } // End llvm namespace
708
709
710 // Utility function for determining if a ConstantExpr is a CastOp or not. This
711 // can't be inline because we don't want to #include Instruction.h into
712 // Constant.h
713 bool ConstantExpr::isCast() const {
714   return Instruction::isCast(getOpcode());
715 }
716
717 bool ConstantExpr::isCompare() const {
718   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
719 }
720
721 /// ConstantExpr::get* - Return some common constants without having to
722 /// specify the full Instruction::OPCODE identifier.
723 ///
724 Constant *ConstantExpr::getNeg(Constant *C) {
725   return get(Instruction::Sub,
726              ConstantExpr::getZeroValueForNegationExpr(C->getType()),
727              C);
728 }
729 Constant *ConstantExpr::getNot(Constant *C) {
730   assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
731   return get(Instruction::Xor, C,
732              ConstantInt::getAllOnesValue(C->getType()));
733 }
734 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
735   return get(Instruction::Add, C1, C2);
736 }
737 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
738   return get(Instruction::Sub, C1, C2);
739 }
740 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
741   return get(Instruction::Mul, C1, C2);
742 }
743 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
744   return get(Instruction::UDiv, C1, C2);
745 }
746 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
747   return get(Instruction::SDiv, C1, C2);
748 }
749 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
750   return get(Instruction::FDiv, C1, C2);
751 }
752 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
753   return get(Instruction::URem, C1, C2);
754 }
755 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
756   return get(Instruction::SRem, C1, C2);
757 }
758 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
759   return get(Instruction::FRem, C1, C2);
760 }
761 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
762   return get(Instruction::And, C1, C2);
763 }
764 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
765   return get(Instruction::Or, C1, C2);
766 }
767 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
768   return get(Instruction::Xor, C1, C2);
769 }
770 unsigned ConstantExpr::getPredicate() const {
771   assert(getOpcode() == Instruction::FCmp || 
772          getOpcode() == Instruction::ICmp ||
773          getOpcode() == Instruction::VFCmp ||
774          getOpcode() == Instruction::VICmp);
775   return ((const CompareConstantExpr*)this)->predicate;
776 }
777 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
778   return get(Instruction::Shl, C1, C2);
779 }
780 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
781   return get(Instruction::LShr, C1, C2);
782 }
783 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
784   return get(Instruction::AShr, C1, C2);
785 }
786
787 /// getWithOperandReplaced - Return a constant expression identical to this
788 /// one, but with the specified operand set to the specified value.
789 Constant *
790 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
791   assert(OpNo < getNumOperands() && "Operand num is out of range!");
792   assert(Op->getType() == getOperand(OpNo)->getType() &&
793          "Replacing operand with value of different type!");
794   if (getOperand(OpNo) == Op)
795     return const_cast<ConstantExpr*>(this);
796   
797   Constant *Op0, *Op1, *Op2;
798   switch (getOpcode()) {
799   case Instruction::Trunc:
800   case Instruction::ZExt:
801   case Instruction::SExt:
802   case Instruction::FPTrunc:
803   case Instruction::FPExt:
804   case Instruction::UIToFP:
805   case Instruction::SIToFP:
806   case Instruction::FPToUI:
807   case Instruction::FPToSI:
808   case Instruction::PtrToInt:
809   case Instruction::IntToPtr:
810   case Instruction::BitCast:
811     return ConstantExpr::getCast(getOpcode(), Op, getType());
812   case Instruction::Select:
813     Op0 = (OpNo == 0) ? Op : getOperand(0);
814     Op1 = (OpNo == 1) ? Op : getOperand(1);
815     Op2 = (OpNo == 2) ? Op : getOperand(2);
816     return ConstantExpr::getSelect(Op0, Op1, Op2);
817   case Instruction::InsertElement:
818     Op0 = (OpNo == 0) ? Op : getOperand(0);
819     Op1 = (OpNo == 1) ? Op : getOperand(1);
820     Op2 = (OpNo == 2) ? Op : getOperand(2);
821     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
822   case Instruction::ExtractElement:
823     Op0 = (OpNo == 0) ? Op : getOperand(0);
824     Op1 = (OpNo == 1) ? Op : getOperand(1);
825     return ConstantExpr::getExtractElement(Op0, Op1);
826   case Instruction::ShuffleVector:
827     Op0 = (OpNo == 0) ? Op : getOperand(0);
828     Op1 = (OpNo == 1) ? Op : getOperand(1);
829     Op2 = (OpNo == 2) ? Op : getOperand(2);
830     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
831   case Instruction::InsertValue: {
832     SmallVector<Constant*, 8> Ops;
833     Ops.resize(getNumOperands()-2);
834     for (unsigned i = 2, e = getNumOperands(); i != e; ++i)
835       Ops[i-2] = getOperand(i);
836     if (OpNo == 0)
837       return ConstantExpr::getInsertValue(Op, getOperand(1),
838                                           &Ops[0], Ops.size());
839     if (OpNo == 1)
840       return ConstantExpr::getInsertValue(getOperand(0), Op,
841                                           &Ops[0], Ops.size());
842     Ops[OpNo-2] = Op;
843     return ConstantExpr::getInsertValue(getOperand(0), getOperand(1),
844                                         &Ops[0], Ops.size());
845   }
846   case Instruction::ExtractValue: {
847     SmallVector<Constant*, 8> Ops;
848     Ops.resize(getNumOperands()-1);
849     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
850       Ops[i-1] = getOperand(i);
851     if (OpNo == 0)
852       return ConstantExpr::getExtractValue(Op, &Ops[0], Ops.size());
853     Ops[OpNo-1] = Op;
854     return ConstantExpr::getExtractValue(getOperand(0), &Ops[0], Ops.size());
855   }
856   case Instruction::GetElementPtr: {
857     SmallVector<Constant*, 8> Ops;
858     Ops.resize(getNumOperands()-1);
859     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
860       Ops[i-1] = getOperand(i);
861     if (OpNo == 0)
862       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
863     Ops[OpNo-1] = Op;
864     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
865   }
866   default:
867     assert(getNumOperands() == 2 && "Must be binary operator?");
868     Op0 = (OpNo == 0) ? Op : getOperand(0);
869     Op1 = (OpNo == 1) ? Op : getOperand(1);
870     return ConstantExpr::get(getOpcode(), Op0, Op1);
871   }
872 }
873
874 /// getWithOperands - This returns the current constant expression with the
875 /// operands replaced with the specified values.  The specified operands must
876 /// match count and type with the existing ones.
877 Constant *ConstantExpr::
878 getWithOperands(const std::vector<Constant*> &Ops) const {
879   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
880   bool AnyChange = false;
881   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
882     assert(Ops[i]->getType() == getOperand(i)->getType() &&
883            "Operand type mismatch!");
884     AnyChange |= Ops[i] != getOperand(i);
885   }
886   if (!AnyChange)  // No operands changed, return self.
887     return const_cast<ConstantExpr*>(this);
888
889   switch (getOpcode()) {
890   case Instruction::Trunc:
891   case Instruction::ZExt:
892   case Instruction::SExt:
893   case Instruction::FPTrunc:
894   case Instruction::FPExt:
895   case Instruction::UIToFP:
896   case Instruction::SIToFP:
897   case Instruction::FPToUI:
898   case Instruction::FPToSI:
899   case Instruction::PtrToInt:
900   case Instruction::IntToPtr:
901   case Instruction::BitCast:
902     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
903   case Instruction::Select:
904     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
905   case Instruction::InsertElement:
906     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
907   case Instruction::ExtractElement:
908     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
909   case Instruction::ShuffleVector:
910     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
911   case Instruction::InsertValue:
912     return ConstantExpr::getInsertValue(Ops[0], Ops[1], &Ops[2], Ops.size()-2);
913   case Instruction::ExtractValue:
914     return ConstantExpr::getExtractValue(Ops[0], &Ops[1], Ops.size()-1);
915   case Instruction::GetElementPtr:
916     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
917   case Instruction::ICmp:
918   case Instruction::FCmp:
919     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
920   default:
921     assert(getNumOperands() == 2 && "Must be binary operator?");
922     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
923   }
924 }
925
926
927 //===----------------------------------------------------------------------===//
928 //                      isValueValidForType implementations
929
930 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
931   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
932   if (Ty == Type::Int1Ty)
933     return Val == 0 || Val == 1;
934   if (NumBits >= 64)
935     return true; // always true, has to fit in largest type
936   uint64_t Max = (1ll << NumBits) - 1;
937   return Val <= Max;
938 }
939
940 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
941   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
942   if (Ty == Type::Int1Ty)
943     return Val == 0 || Val == 1 || Val == -1;
944   if (NumBits >= 64)
945     return true; // always true, has to fit in largest type
946   int64_t Min = -(1ll << (NumBits-1));
947   int64_t Max = (1ll << (NumBits-1)) - 1;
948   return (Val >= Min && Val <= Max);
949 }
950
951 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
952   // convert modifies in place, so make a copy.
953   APFloat Val2 = APFloat(Val);
954   switch (Ty->getTypeID()) {
955   default:
956     return false;         // These can't be represented as floating point!
957
958   // FIXME rounding mode needs to be more flexible
959   case Type::FloatTyID:
960     return &Val2.getSemantics() == &APFloat::IEEEsingle ||
961            Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) == 
962               APFloat::opOK;
963   case Type::DoubleTyID:
964     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
965            &Val2.getSemantics() == &APFloat::IEEEdouble ||
966            Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) == 
967              APFloat::opOK;
968   case Type::X86_FP80TyID:
969     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
970            &Val2.getSemantics() == &APFloat::IEEEdouble ||
971            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
972   case Type::FP128TyID:
973     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
974            &Val2.getSemantics() == &APFloat::IEEEdouble ||
975            &Val2.getSemantics() == &APFloat::IEEEquad;
976   case Type::PPC_FP128TyID:
977     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
978            &Val2.getSemantics() == &APFloat::IEEEdouble ||
979            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
980   }
981 }
982
983 //===----------------------------------------------------------------------===//
984 //                      Factory Function Implementation
985
986
987 // The number of operands for each ConstantCreator::create method is
988 // determined by the ConstantTraits template.
989 // ConstantCreator - A class that is used to create constants by
990 // ValueMap*.  This class should be partially specialized if there is
991 // something strange that needs to be done to interface to the ctor for the
992 // constant.
993 //
994 namespace llvm {
995   template<class ValType>
996   struct ConstantTraits;
997
998   template<typename T, typename Alloc>
999   struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1000     static unsigned uses(const std::vector<T, Alloc>& v) {
1001       return v.size();
1002     }
1003   };
1004
1005   template<class ConstantClass, class TypeClass, class ValType>
1006   struct VISIBILITY_HIDDEN ConstantCreator {
1007     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1008       return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1009     }
1010   };
1011
1012   template<class ConstantClass, class TypeClass>
1013   struct VISIBILITY_HIDDEN ConvertConstantType {
1014     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1015       assert(0 && "This type cannot be converted!\n");
1016       abort();
1017     }
1018   };
1019
1020   template<class ValType, class TypeClass, class ConstantClass,
1021            bool HasLargeKey = false  /*true for arrays and structs*/ >
1022   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1023   public:
1024     typedef std::pair<const Type*, ValType> MapKey;
1025     typedef std::map<MapKey, Constant *> MapTy;
1026     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1027     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1028   private:
1029     /// Map - This is the main map from the element descriptor to the Constants.
1030     /// This is the primary way we avoid creating two of the same shape
1031     /// constant.
1032     MapTy Map;
1033     
1034     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1035     /// from the constants to their element in Map.  This is important for
1036     /// removal of constants from the array, which would otherwise have to scan
1037     /// through the map with very large keys.
1038     InverseMapTy InverseMap;
1039
1040     /// AbstractTypeMap - Map for abstract type constants.
1041     ///
1042     AbstractTypeMapTy AbstractTypeMap;
1043
1044   public:
1045     typename MapTy::iterator map_end() { return Map.end(); }
1046     
1047     /// InsertOrGetItem - Return an iterator for the specified element.
1048     /// If the element exists in the map, the returned iterator points to the
1049     /// entry and Exists=true.  If not, the iterator points to the newly
1050     /// inserted entry and returns Exists=false.  Newly inserted entries have
1051     /// I->second == 0, and should be filled in.
1052     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1053                                    &InsertVal,
1054                                    bool &Exists) {
1055       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1056       Exists = !IP.second;
1057       return IP.first;
1058     }
1059     
1060 private:
1061     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1062       if (HasLargeKey) {
1063         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1064         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1065                IMI->second->second == CP &&
1066                "InverseMap corrupt!");
1067         return IMI->second;
1068       }
1069       
1070       typename MapTy::iterator I =
1071         Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
1072       if (I == Map.end() || I->second != CP) {
1073         // FIXME: This should not use a linear scan.  If this gets to be a
1074         // performance problem, someone should look at this.
1075         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1076           /* empty */;
1077       }
1078       return I;
1079     }
1080 public:
1081     
1082     /// getOrCreate - Return the specified constant from the map, creating it if
1083     /// necessary.
1084     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1085       MapKey Lookup(Ty, V);
1086       typename MapTy::iterator I = Map.lower_bound(Lookup);
1087       // Is it in the map?      
1088       if (I != Map.end() && I->first == Lookup)
1089         return static_cast<ConstantClass *>(I->second);  
1090
1091       // If no preexisting value, create one now...
1092       ConstantClass *Result =
1093         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1094
1095       /// FIXME: why does this assert fail when loading 176.gcc?
1096       //assert(Result->getType() == Ty && "Type specified is not correct!");
1097       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1098
1099       if (HasLargeKey)  // Remember the reverse mapping if needed.
1100         InverseMap.insert(std::make_pair(Result, I));
1101       
1102       // If the type of the constant is abstract, make sure that an entry exists
1103       // for it in the AbstractTypeMap.
1104       if (Ty->isAbstract()) {
1105         typename AbstractTypeMapTy::iterator TI =
1106           AbstractTypeMap.lower_bound(Ty);
1107
1108         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
1109           // Add ourselves to the ATU list of the type.
1110           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1111
1112           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1113         }
1114       }
1115       return Result;
1116     }
1117
1118     void remove(ConstantClass *CP) {
1119       typename MapTy::iterator I = FindExistingElement(CP);
1120       assert(I != Map.end() && "Constant not found in constant table!");
1121       assert(I->second == CP && "Didn't find correct element?");
1122
1123       if (HasLargeKey)  // Remember the reverse mapping if needed.
1124         InverseMap.erase(CP);
1125       
1126       // Now that we found the entry, make sure this isn't the entry that
1127       // the AbstractTypeMap points to.
1128       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1129       if (Ty->isAbstract()) {
1130         assert(AbstractTypeMap.count(Ty) &&
1131                "Abstract type not in AbstractTypeMap?");
1132         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1133         if (ATMEntryIt == I) {
1134           // Yes, we are removing the representative entry for this type.
1135           // See if there are any other entries of the same type.
1136           typename MapTy::iterator TmpIt = ATMEntryIt;
1137
1138           // First check the entry before this one...
1139           if (TmpIt != Map.begin()) {
1140             --TmpIt;
1141             if (TmpIt->first.first != Ty) // Not the same type, move back...
1142               ++TmpIt;
1143           }
1144
1145           // If we didn't find the same type, try to move forward...
1146           if (TmpIt == ATMEntryIt) {
1147             ++TmpIt;
1148             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1149               --TmpIt;   // No entry afterwards with the same type
1150           }
1151
1152           // If there is another entry in the map of the same abstract type,
1153           // update the AbstractTypeMap entry now.
1154           if (TmpIt != ATMEntryIt) {
1155             ATMEntryIt = TmpIt;
1156           } else {
1157             // Otherwise, we are removing the last instance of this type
1158             // from the table.  Remove from the ATM, and from user list.
1159             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1160             AbstractTypeMap.erase(Ty);
1161           }
1162         }
1163       }
1164
1165       Map.erase(I);
1166     }
1167
1168     
1169     /// MoveConstantToNewSlot - If we are about to change C to be the element
1170     /// specified by I, update our internal data structures to reflect this
1171     /// fact.
1172     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1173       // First, remove the old location of the specified constant in the map.
1174       typename MapTy::iterator OldI = FindExistingElement(C);
1175       assert(OldI != Map.end() && "Constant not found in constant table!");
1176       assert(OldI->second == C && "Didn't find correct element?");
1177       
1178       // If this constant is the representative element for its abstract type,
1179       // update the AbstractTypeMap so that the representative element is I.
1180       if (C->getType()->isAbstract()) {
1181         typename AbstractTypeMapTy::iterator ATI =
1182             AbstractTypeMap.find(C->getType());
1183         assert(ATI != AbstractTypeMap.end() &&
1184                "Abstract type not in AbstractTypeMap?");
1185         if (ATI->second == OldI)
1186           ATI->second = I;
1187       }
1188       
1189       // Remove the old entry from the map.
1190       Map.erase(OldI);
1191       
1192       // Update the inverse map so that we know that this constant is now
1193       // located at descriptor I.
1194       if (HasLargeKey) {
1195         assert(I->second == C && "Bad inversemap entry!");
1196         InverseMap[C] = I;
1197       }
1198     }
1199     
1200     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1201       typename AbstractTypeMapTy::iterator I =
1202         AbstractTypeMap.find(cast<Type>(OldTy));
1203
1204       assert(I != AbstractTypeMap.end() &&
1205              "Abstract type not in AbstractTypeMap?");
1206
1207       // Convert a constant at a time until the last one is gone.  The last one
1208       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1209       // eliminated eventually.
1210       do {
1211         ConvertConstantType<ConstantClass,
1212                             TypeClass>::convert(
1213                                 static_cast<ConstantClass *>(I->second->second),
1214                                                 cast<TypeClass>(NewTy));
1215
1216         I = AbstractTypeMap.find(cast<Type>(OldTy));
1217       } while (I != AbstractTypeMap.end());
1218     }
1219
1220     // If the type became concrete without being refined to any other existing
1221     // type, we just remove ourselves from the ATU list.
1222     void typeBecameConcrete(const DerivedType *AbsTy) {
1223       AbsTy->removeAbstractTypeUser(this);
1224     }
1225
1226     void dump() const {
1227       DOUT << "Constant.cpp: ValueMap\n";
1228     }
1229   };
1230 }
1231
1232
1233
1234 //---- ConstantAggregateZero::get() implementation...
1235 //
1236 namespace llvm {
1237   // ConstantAggregateZero does not take extra "value" argument...
1238   template<class ValType>
1239   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1240     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1241       return new ConstantAggregateZero(Ty);
1242     }
1243   };
1244
1245   template<>
1246   struct ConvertConstantType<ConstantAggregateZero, Type> {
1247     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1248       // Make everyone now use a constant of the new type...
1249       Constant *New = ConstantAggregateZero::get(NewTy);
1250       assert(New != OldC && "Didn't replace constant??");
1251       OldC->uncheckedReplaceAllUsesWith(New);
1252       OldC->destroyConstant();     // This constant is now dead, destroy it.
1253     }
1254   };
1255 }
1256
1257 static ManagedStatic<ValueMap<char, Type, 
1258                               ConstantAggregateZero> > AggZeroConstants;
1259
1260 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1261
1262 Constant *ConstantAggregateZero::get(const Type *Ty) {
1263   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1264          "Cannot create an aggregate zero of non-aggregate type!");
1265   return AggZeroConstants->getOrCreate(Ty, 0);
1266 }
1267
1268 // destroyConstant - Remove the constant from the constant table...
1269 //
1270 void ConstantAggregateZero::destroyConstant() {
1271   AggZeroConstants->remove(this);
1272   destroyConstantImpl();
1273 }
1274
1275 //---- ConstantArray::get() implementation...
1276 //
1277 namespace llvm {
1278   template<>
1279   struct ConvertConstantType<ConstantArray, ArrayType> {
1280     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1281       // Make everyone now use a constant of the new type...
1282       std::vector<Constant*> C;
1283       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1284         C.push_back(cast<Constant>(OldC->getOperand(i)));
1285       Constant *New = ConstantArray::get(NewTy, C);
1286       assert(New != OldC && "Didn't replace constant??");
1287       OldC->uncheckedReplaceAllUsesWith(New);
1288       OldC->destroyConstant();    // This constant is now dead, destroy it.
1289     }
1290   };
1291 }
1292
1293 static std::vector<Constant*> getValType(ConstantArray *CA) {
1294   std::vector<Constant*> Elements;
1295   Elements.reserve(CA->getNumOperands());
1296   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1297     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1298   return Elements;
1299 }
1300
1301 typedef ValueMap<std::vector<Constant*>, ArrayType, 
1302                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
1303 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1304
1305 Constant *ConstantArray::get(const ArrayType *Ty,
1306                              const std::vector<Constant*> &V) {
1307   // If this is an all-zero array, return a ConstantAggregateZero object
1308   if (!V.empty()) {
1309     Constant *C = V[0];
1310     if (!C->isNullValue())
1311       return ArrayConstants->getOrCreate(Ty, V);
1312     for (unsigned i = 1, e = V.size(); i != e; ++i)
1313       if (V[i] != C)
1314         return ArrayConstants->getOrCreate(Ty, V);
1315   }
1316   return ConstantAggregateZero::get(Ty);
1317 }
1318
1319 // destroyConstant - Remove the constant from the constant table...
1320 //
1321 void ConstantArray::destroyConstant() {
1322   ArrayConstants->remove(this);
1323   destroyConstantImpl();
1324 }
1325
1326 /// ConstantArray::get(const string&) - Return an array that is initialized to
1327 /// contain the specified string.  If length is zero then a null terminator is 
1328 /// added to the specified string so that it may be used in a natural way. 
1329 /// Otherwise, the length parameter specifies how much of the string to use 
1330 /// and it won't be null terminated.
1331 ///
1332 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1333   std::vector<Constant*> ElementVals;
1334   for (unsigned i = 0; i < Str.length(); ++i)
1335     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1336
1337   // Add a null terminator to the string...
1338   if (AddNull) {
1339     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1340   }
1341
1342   ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1343   return ConstantArray::get(ATy, ElementVals);
1344 }
1345
1346 /// isString - This method returns true if the array is an array of i8, and 
1347 /// if the elements of the array are all ConstantInt's.
1348 bool ConstantArray::isString() const {
1349   // Check the element type for i8...
1350   if (getType()->getElementType() != Type::Int8Ty)
1351     return false;
1352   // Check the elements to make sure they are all integers, not constant
1353   // expressions.
1354   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1355     if (!isa<ConstantInt>(getOperand(i)))
1356       return false;
1357   return true;
1358 }
1359
1360 /// isCString - This method returns true if the array is a string (see
1361 /// isString) and it ends in a null byte \0 and does not contains any other
1362 /// null bytes except its terminator.
1363 bool ConstantArray::isCString() const {
1364   // Check the element type for i8...
1365   if (getType()->getElementType() != Type::Int8Ty)
1366     return false;
1367   Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1368   // Last element must be a null.
1369   if (getOperand(getNumOperands()-1) != Zero)
1370     return false;
1371   // Other elements must be non-null integers.
1372   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1373     if (!isa<ConstantInt>(getOperand(i)))
1374       return false;
1375     if (getOperand(i) == Zero)
1376       return false;
1377   }
1378   return true;
1379 }
1380
1381
1382 // getAsString - If the sub-element type of this array is i8
1383 // then this method converts the array to an std::string and returns it.
1384 // Otherwise, it asserts out.
1385 //
1386 std::string ConstantArray::getAsString() const {
1387   assert(isString() && "Not a string!");
1388   std::string Result;
1389   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1390     Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1391   return Result;
1392 }
1393
1394
1395 //---- ConstantStruct::get() implementation...
1396 //
1397
1398 namespace llvm {
1399   template<>
1400   struct ConvertConstantType<ConstantStruct, StructType> {
1401     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1402       // Make everyone now use a constant of the new type...
1403       std::vector<Constant*> C;
1404       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1405         C.push_back(cast<Constant>(OldC->getOperand(i)));
1406       Constant *New = ConstantStruct::get(NewTy, C);
1407       assert(New != OldC && "Didn't replace constant??");
1408
1409       OldC->uncheckedReplaceAllUsesWith(New);
1410       OldC->destroyConstant();    // This constant is now dead, destroy it.
1411     }
1412   };
1413 }
1414
1415 typedef ValueMap<std::vector<Constant*>, StructType,
1416                  ConstantStruct, true /*largekey*/> StructConstantsTy;
1417 static ManagedStatic<StructConstantsTy> StructConstants;
1418
1419 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1420   std::vector<Constant*> Elements;
1421   Elements.reserve(CS->getNumOperands());
1422   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1423     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1424   return Elements;
1425 }
1426
1427 Constant *ConstantStruct::get(const StructType *Ty,
1428                               const std::vector<Constant*> &V) {
1429   // Create a ConstantAggregateZero value if all elements are zeros...
1430   for (unsigned i = 0, e = V.size(); i != e; ++i)
1431     if (!V[i]->isNullValue())
1432       return StructConstants->getOrCreate(Ty, V);
1433
1434   return ConstantAggregateZero::get(Ty);
1435 }
1436
1437 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1438   std::vector<const Type*> StructEls;
1439   StructEls.reserve(V.size());
1440   for (unsigned i = 0, e = V.size(); i != e; ++i)
1441     StructEls.push_back(V[i]->getType());
1442   return get(StructType::get(StructEls, packed), V);
1443 }
1444
1445 // destroyConstant - Remove the constant from the constant table...
1446 //
1447 void ConstantStruct::destroyConstant() {
1448   StructConstants->remove(this);
1449   destroyConstantImpl();
1450 }
1451
1452 //---- ConstantVector::get() implementation...
1453 //
1454 namespace llvm {
1455   template<>
1456   struct ConvertConstantType<ConstantVector, VectorType> {
1457     static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1458       // Make everyone now use a constant of the new type...
1459       std::vector<Constant*> C;
1460       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1461         C.push_back(cast<Constant>(OldC->getOperand(i)));
1462       Constant *New = ConstantVector::get(NewTy, C);
1463       assert(New != OldC && "Didn't replace constant??");
1464       OldC->uncheckedReplaceAllUsesWith(New);
1465       OldC->destroyConstant();    // This constant is now dead, destroy it.
1466     }
1467   };
1468 }
1469
1470 static std::vector<Constant*> getValType(ConstantVector *CP) {
1471   std::vector<Constant*> Elements;
1472   Elements.reserve(CP->getNumOperands());
1473   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1474     Elements.push_back(CP->getOperand(i));
1475   return Elements;
1476 }
1477
1478 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1479                               ConstantVector> > VectorConstants;
1480
1481 Constant *ConstantVector::get(const VectorType *Ty,
1482                               const std::vector<Constant*> &V) {
1483   // If this is an all-zero vector, return a ConstantAggregateZero object
1484   if (!V.empty()) {
1485     Constant *C = V[0];
1486     if (!C->isNullValue())
1487       return VectorConstants->getOrCreate(Ty, V);
1488     for (unsigned i = 1, e = V.size(); i != e; ++i)
1489       if (V[i] != C)
1490         return VectorConstants->getOrCreate(Ty, V);
1491   }
1492   return ConstantAggregateZero::get(Ty);
1493 }
1494
1495 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1496   assert(!V.empty() && "Cannot infer type if V is empty");
1497   return get(VectorType::get(V.front()->getType(),V.size()), V);
1498 }
1499
1500 // destroyConstant - Remove the constant from the constant table...
1501 //
1502 void ConstantVector::destroyConstant() {
1503   VectorConstants->remove(this);
1504   destroyConstantImpl();
1505 }
1506
1507 /// This function will return true iff every element in this vector constant
1508 /// is set to all ones.
1509 /// @returns true iff this constant's emements are all set to all ones.
1510 /// @brief Determine if the value is all ones.
1511 bool ConstantVector::isAllOnesValue() const {
1512   // Check out first element.
1513   const Constant *Elt = getOperand(0);
1514   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1515   if (!CI || !CI->isAllOnesValue()) return false;
1516   // Then make sure all remaining elements point to the same value.
1517   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1518     if (getOperand(I) != Elt) return false;
1519   }
1520   return true;
1521 }
1522
1523 /// getSplatValue - If this is a splat constant, where all of the
1524 /// elements have the same value, return that value. Otherwise return null.
1525 Constant *ConstantVector::getSplatValue() {
1526   // Check out first element.
1527   Constant *Elt = getOperand(0);
1528   // Then make sure all remaining elements point to the same value.
1529   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1530     if (getOperand(I) != Elt) return 0;
1531   return Elt;
1532 }
1533
1534 //---- ConstantPointerNull::get() implementation...
1535 //
1536
1537 namespace llvm {
1538   // ConstantPointerNull does not take extra "value" argument...
1539   template<class ValType>
1540   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1541     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1542       return new ConstantPointerNull(Ty);
1543     }
1544   };
1545
1546   template<>
1547   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1548     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1549       // Make everyone now use a constant of the new type...
1550       Constant *New = ConstantPointerNull::get(NewTy);
1551       assert(New != OldC && "Didn't replace constant??");
1552       OldC->uncheckedReplaceAllUsesWith(New);
1553       OldC->destroyConstant();     // This constant is now dead, destroy it.
1554     }
1555   };
1556 }
1557
1558 static ManagedStatic<ValueMap<char, PointerType, 
1559                               ConstantPointerNull> > NullPtrConstants;
1560
1561 static char getValType(ConstantPointerNull *) {
1562   return 0;
1563 }
1564
1565
1566 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1567   return NullPtrConstants->getOrCreate(Ty, 0);
1568 }
1569
1570 // destroyConstant - Remove the constant from the constant table...
1571 //
1572 void ConstantPointerNull::destroyConstant() {
1573   NullPtrConstants->remove(this);
1574   destroyConstantImpl();
1575 }
1576
1577
1578 //---- UndefValue::get() implementation...
1579 //
1580
1581 namespace llvm {
1582   // UndefValue does not take extra "value" argument...
1583   template<class ValType>
1584   struct ConstantCreator<UndefValue, Type, ValType> {
1585     static UndefValue *create(const Type *Ty, const ValType &V) {
1586       return new UndefValue(Ty);
1587     }
1588   };
1589
1590   template<>
1591   struct ConvertConstantType<UndefValue, Type> {
1592     static void convert(UndefValue *OldC, const Type *NewTy) {
1593       // Make everyone now use a constant of the new type.
1594       Constant *New = UndefValue::get(NewTy);
1595       assert(New != OldC && "Didn't replace constant??");
1596       OldC->uncheckedReplaceAllUsesWith(New);
1597       OldC->destroyConstant();     // This constant is now dead, destroy it.
1598     }
1599   };
1600 }
1601
1602 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1603
1604 static char getValType(UndefValue *) {
1605   return 0;
1606 }
1607
1608
1609 UndefValue *UndefValue::get(const Type *Ty) {
1610   return UndefValueConstants->getOrCreate(Ty, 0);
1611 }
1612
1613 // destroyConstant - Remove the constant from the constant table.
1614 //
1615 void UndefValue::destroyConstant() {
1616   UndefValueConstants->remove(this);
1617   destroyConstantImpl();
1618 }
1619
1620
1621 //---- ConstantExpr::get() implementations...
1622 //
1623
1624 namespace {
1625
1626 struct ExprMapKeyType {
1627   explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1628       unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1629   uint16_t opcode;
1630   uint16_t predicate;
1631   std::vector<Constant*> operands;
1632   bool operator==(const ExprMapKeyType& that) const {
1633     return this->opcode == that.opcode &&
1634            this->predicate == that.predicate &&
1635            this->operands == that.operands;
1636   }
1637   bool operator<(const ExprMapKeyType & that) const {
1638     return this->opcode < that.opcode ||
1639       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1640       (this->opcode == that.opcode && this->predicate == that.predicate &&
1641        this->operands < that.operands);
1642   }
1643
1644   bool operator!=(const ExprMapKeyType& that) const {
1645     return !(*this == that);
1646   }
1647 };
1648
1649 }
1650
1651 namespace llvm {
1652   template<>
1653   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1654     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1655         unsigned short pred = 0) {
1656       if (Instruction::isCast(V.opcode))
1657         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1658       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1659            V.opcode < Instruction::BinaryOpsEnd))
1660         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1661       if (V.opcode == Instruction::Select)
1662         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1663                                       V.operands[2]);
1664       if (V.opcode == Instruction::ExtractElement)
1665         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1666       if (V.opcode == Instruction::InsertElement)
1667         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1668                                              V.operands[2]);
1669       if (V.opcode == Instruction::ShuffleVector)
1670         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1671                                              V.operands[2]);
1672       if (V.opcode == Instruction::InsertValue) {
1673         std::vector<Constant*> IdxList(V.operands.begin()+2, V.operands.end());
1674         return InsertValueConstantExpr::Create(V.operands[0], V.operands[1],
1675                                                IdxList, Ty);
1676       }
1677       if (V.opcode == Instruction::ExtractValue) {
1678         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1679         return ExtractValueConstantExpr::Create(V.operands[0], IdxList, Ty);
1680       }
1681       if (V.opcode == Instruction::GetElementPtr) {
1682         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1683         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1684       }
1685
1686       // The compare instructions are weird. We have to encode the predicate
1687       // value and it is combined with the instruction opcode by multiplying
1688       // the opcode by one hundred. We must decode this to get the predicate.
1689       if (V.opcode == Instruction::ICmp)
1690         return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
1691                                        V.operands[0], V.operands[1]);
1692       if (V.opcode == Instruction::FCmp) 
1693         return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
1694                                        V.operands[0], V.operands[1]);
1695       if (V.opcode == Instruction::VICmp)
1696         return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate, 
1697                                        V.operands[0], V.operands[1]);
1698       if (V.opcode == Instruction::VFCmp) 
1699         return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate, 
1700                                        V.operands[0], V.operands[1]);
1701       assert(0 && "Invalid ConstantExpr!");
1702       return 0;
1703     }
1704   };
1705
1706   template<>
1707   struct ConvertConstantType<ConstantExpr, Type> {
1708     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1709       Constant *New;
1710       switch (OldC->getOpcode()) {
1711       case Instruction::Trunc:
1712       case Instruction::ZExt:
1713       case Instruction::SExt:
1714       case Instruction::FPTrunc:
1715       case Instruction::FPExt:
1716       case Instruction::UIToFP:
1717       case Instruction::SIToFP:
1718       case Instruction::FPToUI:
1719       case Instruction::FPToSI:
1720       case Instruction::PtrToInt:
1721       case Instruction::IntToPtr:
1722       case Instruction::BitCast:
1723         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1724                                     NewTy);
1725         break;
1726       case Instruction::Select:
1727         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1728                                         OldC->getOperand(1),
1729                                         OldC->getOperand(2));
1730         break;
1731       default:
1732         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1733                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1734         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1735                                   OldC->getOperand(1));
1736         break;
1737       case Instruction::GetElementPtr:
1738         // Make everyone now use a constant of the new type...
1739         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1740         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1741                                                &Idx[0], Idx.size());
1742         break;
1743       }
1744
1745       assert(New != OldC && "Didn't replace constant??");
1746       OldC->uncheckedReplaceAllUsesWith(New);
1747       OldC->destroyConstant();    // This constant is now dead, destroy it.
1748     }
1749   };
1750 } // end namespace llvm
1751
1752
1753 static ExprMapKeyType getValType(ConstantExpr *CE) {
1754   std::vector<Constant*> Operands;
1755   Operands.reserve(CE->getNumOperands());
1756   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1757     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1758   return ExprMapKeyType(CE->getOpcode(), Operands, 
1759       CE->isCompare() ? CE->getPredicate() : 0);
1760 }
1761
1762 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1763                               ConstantExpr> > ExprConstants;
1764
1765 /// This is a utility function to handle folding of casts and lookup of the
1766 /// cast in the ExprConstants map. It is used by the various get* methods below.
1767 static inline Constant *getFoldedCast(
1768   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1769   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1770   // Fold a few common cases
1771   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1772     return FC;
1773
1774   // Look up the constant in the table first to ensure uniqueness
1775   std::vector<Constant*> argVec(1, C);
1776   ExprMapKeyType Key(opc, argVec);
1777   return ExprConstants->getOrCreate(Ty, Key);
1778 }
1779  
1780 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1781   Instruction::CastOps opc = Instruction::CastOps(oc);
1782   assert(Instruction::isCast(opc) && "opcode out of range");
1783   assert(C && Ty && "Null arguments to getCast");
1784   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1785
1786   switch (opc) {
1787     default:
1788       assert(0 && "Invalid cast opcode");
1789       break;
1790     case Instruction::Trunc:    return getTrunc(C, Ty);
1791     case Instruction::ZExt:     return getZExt(C, Ty);
1792     case Instruction::SExt:     return getSExt(C, Ty);
1793     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1794     case Instruction::FPExt:    return getFPExtend(C, Ty);
1795     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1796     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1797     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1798     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1799     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1800     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1801     case Instruction::BitCast:  return getBitCast(C, Ty);
1802   }
1803   return 0;
1804
1805
1806 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1807   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1808     return getCast(Instruction::BitCast, C, Ty);
1809   return getCast(Instruction::ZExt, C, Ty);
1810 }
1811
1812 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1813   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1814     return getCast(Instruction::BitCast, C, Ty);
1815   return getCast(Instruction::SExt, C, Ty);
1816 }
1817
1818 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1819   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1820     return getCast(Instruction::BitCast, C, Ty);
1821   return getCast(Instruction::Trunc, C, Ty);
1822 }
1823
1824 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1825   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1826   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1827
1828   if (Ty->isInteger())
1829     return getCast(Instruction::PtrToInt, S, Ty);
1830   return getCast(Instruction::BitCast, S, Ty);
1831 }
1832
1833 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1834                                        bool isSigned) {
1835   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1836   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1837   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1838   Instruction::CastOps opcode =
1839     (SrcBits == DstBits ? Instruction::BitCast :
1840      (SrcBits > DstBits ? Instruction::Trunc :
1841       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1842   return getCast(opcode, C, Ty);
1843 }
1844
1845 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1846   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
1847          "Invalid cast");
1848   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1849   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1850   if (SrcBits == DstBits)
1851     return C; // Avoid a useless cast
1852   Instruction::CastOps opcode =
1853      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1854   return getCast(opcode, C, Ty);
1855 }
1856
1857 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1858   assert(C->getType()->isInteger() && "Trunc operand must be integer");
1859   assert(Ty->isInteger() && "Trunc produces only integral");
1860   assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1861          "SrcTy must be larger than DestTy for Trunc!");
1862
1863   return getFoldedCast(Instruction::Trunc, C, Ty);
1864 }
1865
1866 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1867   assert(C->getType()->isInteger() && "SEXt operand must be integral");
1868   assert(Ty->isInteger() && "SExt produces only integer");
1869   assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1870          "SrcTy must be smaller than DestTy for SExt!");
1871
1872   return getFoldedCast(Instruction::SExt, C, Ty);
1873 }
1874
1875 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1876   assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1877   assert(Ty->isInteger() && "ZExt produces only integer");
1878   assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1879          "SrcTy must be smaller than DestTy for ZExt!");
1880
1881   return getFoldedCast(Instruction::ZExt, C, Ty);
1882 }
1883
1884 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1885   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1886          C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1887          "This is an illegal floating point truncation!");
1888   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1889 }
1890
1891 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1892   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1893          C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1894          "This is an illegal floating point extension!");
1895   return getFoldedCast(Instruction::FPExt, C, Ty);
1896 }
1897
1898 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1899   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1900   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1901   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1902   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1903          "This is an illegal uint to floating point cast!");
1904   return getFoldedCast(Instruction::UIToFP, C, Ty);
1905 }
1906
1907 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1908   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1909   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1910   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1911   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1912          "This is an illegal sint to floating point cast!");
1913   return getFoldedCast(Instruction::SIToFP, C, Ty);
1914 }
1915
1916 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1917   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1918   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1919   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1920   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1921          "This is an illegal floating point to uint cast!");
1922   return getFoldedCast(Instruction::FPToUI, C, Ty);
1923 }
1924
1925 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1926   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1927   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1928   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1929   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1930          "This is an illegal floating point to sint cast!");
1931   return getFoldedCast(Instruction::FPToSI, C, Ty);
1932 }
1933
1934 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1935   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1936   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1937   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1938 }
1939
1940 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1941   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1942   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1943   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1944 }
1945
1946 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1947   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1948   // can't cast pointers to anything but pointers.
1949   const Type *SrcTy = C->getType();
1950   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1951          "BitCast cannot cast pointer to non-pointer and vice versa");
1952
1953   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1954   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1955   // destination bit widths are identical.
1956   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1957   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1958   assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1959   return getFoldedCast(Instruction::BitCast, C, DstTy);
1960 }
1961
1962 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1963   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1964   Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1965   Constant *GEP =
1966     getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1967   return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1968 }
1969
1970 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1971                               Constant *C1, Constant *C2) {
1972   // Check the operands for consistency first
1973   assert(Opcode >= Instruction::BinaryOpsBegin &&
1974          Opcode <  Instruction::BinaryOpsEnd   &&
1975          "Invalid opcode in binary constant expression");
1976   assert(C1->getType() == C2->getType() &&
1977          "Operand types in binary constant expression should match");
1978
1979   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1980     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1981       return FC;          // Fold a few common cases...
1982
1983   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1984   ExprMapKeyType Key(Opcode, argVec);
1985   return ExprConstants->getOrCreate(ReqTy, Key);
1986 }
1987
1988 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1989                                      Constant *C1, Constant *C2) {
1990   switch (predicate) {
1991     default: assert(0 && "Invalid CmpInst predicate");
1992     case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1993     case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1994     case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1995     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1996     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1997     case FCmpInst::FCMP_TRUE:
1998       return getFCmp(predicate, C1, C2);
1999     case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
2000     case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
2001     case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
2002     case ICmpInst::ICMP_SLE:
2003       return getICmp(predicate, C1, C2);
2004   }
2005 }
2006
2007 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2008 #ifndef NDEBUG
2009   switch (Opcode) {
2010   case Instruction::Add: 
2011   case Instruction::Sub:
2012   case Instruction::Mul: 
2013     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2014     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
2015             isa<VectorType>(C1->getType())) &&
2016            "Tried to create an arithmetic operation on a non-arithmetic type!");
2017     break;
2018   case Instruction::UDiv: 
2019   case Instruction::SDiv: 
2020     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2021     assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2022       cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2023            "Tried to create an arithmetic operation on a non-arithmetic type!");
2024     break;
2025   case Instruction::FDiv:
2026     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2027     assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2028       && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint())) 
2029       && "Tried to create an arithmetic operation on a non-arithmetic type!");
2030     break;
2031   case Instruction::URem: 
2032   case Instruction::SRem: 
2033     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2034     assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2035       cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2036            "Tried to create an arithmetic operation on a non-arithmetic type!");
2037     break;
2038   case Instruction::FRem:
2039     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2040     assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2041       && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint())) 
2042       && "Tried to create an arithmetic operation on a non-arithmetic type!");
2043     break;
2044   case Instruction::And:
2045   case Instruction::Or:
2046   case Instruction::Xor:
2047     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2048     assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
2049            "Tried to create a logical operation on a non-integral type!");
2050     break;
2051   case Instruction::Shl:
2052   case Instruction::LShr:
2053   case Instruction::AShr:
2054     assert(C1->getType() == C2->getType() && "Op types should be identical!");
2055     assert(C1->getType()->isInteger() &&
2056            "Tried to create a shift operation on a non-integer type!");
2057     break;
2058   default:
2059     break;
2060   }
2061 #endif
2062
2063   return getTy(C1->getType(), Opcode, C1, C2);
2064 }
2065
2066 Constant *ConstantExpr::getCompare(unsigned short pred, 
2067                             Constant *C1, Constant *C2) {
2068   assert(C1->getType() == C2->getType() && "Op types should be identical!");
2069   return getCompareTy(pred, C1, C2);
2070 }
2071
2072 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2073                                     Constant *V1, Constant *V2) {
2074   assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
2075   assert(V1->getType() == V2->getType() && "Select value types must match!");
2076   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
2077
2078   if (ReqTy == V1->getType())
2079     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2080       return SC;        // Fold common cases
2081
2082   std::vector<Constant*> argVec(3, C);
2083   argVec[1] = V1;
2084   argVec[2] = V2;
2085   ExprMapKeyType Key(Instruction::Select, argVec);
2086   return ExprConstants->getOrCreate(ReqTy, Key);
2087 }
2088
2089 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2090                                            Value* const *Idxs,
2091                                            unsigned NumIdx) {
2092   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2093                                            Idxs+NumIdx) ==
2094          cast<PointerType>(ReqTy)->getElementType() &&
2095          "GEP indices invalid!");
2096
2097   if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2098     return FC;          // Fold a few common cases...
2099
2100   assert(isa<PointerType>(C->getType()) &&
2101          "Non-pointer type for constant GetElementPtr expression");
2102   // Look up the constant in the table first to ensure uniqueness
2103   std::vector<Constant*> ArgVec;
2104   ArgVec.reserve(NumIdx+1);
2105   ArgVec.push_back(C);
2106   for (unsigned i = 0; i != NumIdx; ++i)
2107     ArgVec.push_back(cast<Constant>(Idxs[i]));
2108   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2109   return ExprConstants->getOrCreate(ReqTy, Key);
2110 }
2111
2112 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2113                                          unsigned NumIdx) {
2114   // Get the result type of the getelementptr!
2115   const Type *Ty = 
2116     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2117   assert(Ty && "GEP indices invalid!");
2118   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2119   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2120 }
2121
2122 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2123                                          unsigned NumIdx) {
2124   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2125 }
2126
2127
2128 Constant *
2129 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2130   assert(LHS->getType() == RHS->getType());
2131   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
2132          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2133
2134   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2135     return FC;          // Fold a few common cases...
2136
2137   // Look up the constant in the table first to ensure uniqueness
2138   std::vector<Constant*> ArgVec;
2139   ArgVec.push_back(LHS);
2140   ArgVec.push_back(RHS);
2141   // Get the key type with both the opcode and predicate
2142   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2143   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2144 }
2145
2146 Constant *
2147 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2148   assert(LHS->getType() == RHS->getType());
2149   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2150
2151   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2152     return FC;          // Fold a few common cases...
2153
2154   // Look up the constant in the table first to ensure uniqueness
2155   std::vector<Constant*> ArgVec;
2156   ArgVec.push_back(LHS);
2157   ArgVec.push_back(RHS);
2158   // Get the key type with both the opcode and predicate
2159   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2160   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2161 }
2162
2163 Constant *
2164 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2165   assert(isa<VectorType>(LHS->getType()) &&
2166          "Tried to create vicmp operation on non-vector type!");
2167   assert(LHS->getType() == RHS->getType());
2168   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
2169          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2170
2171   const VectorType *VTy = cast<VectorType>(LHS->getType());
2172   const Type *EltTy = VTy->getElementType();
2173   unsigned NumElts = VTy->getNumElements();
2174
2175   SmallVector<Constant *, 8> Elts;
2176   for (unsigned i = 0; i != NumElts; ++i) {
2177     Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2178                                                         RHS->getOperand(i));
2179     if (FC) {
2180       uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2181       if (Val != 0ULL)
2182         Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2183       else
2184         Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2185     }
2186   }
2187   if (Elts.size() == NumElts)
2188     return ConstantVector::get(&Elts[0], Elts.size());
2189
2190   // Look up the constant in the table first to ensure uniqueness
2191   std::vector<Constant*> ArgVec;
2192   ArgVec.push_back(LHS);
2193   ArgVec.push_back(RHS);
2194   // Get the key type with both the opcode and predicate
2195   const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2196   return ExprConstants->getOrCreate(LHS->getType(), Key);
2197 }
2198
2199 Constant *
2200 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2201   assert(isa<VectorType>(LHS->getType()) &&
2202          "Tried to create vfcmp operation on non-vector type!");
2203   assert(LHS->getType() == RHS->getType());
2204   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2205
2206   const VectorType *VTy = cast<VectorType>(LHS->getType());
2207   unsigned NumElts = VTy->getNumElements();
2208   const Type *EltTy = VTy->getElementType();
2209   const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2210   const Type *ResultTy = VectorType::get(REltTy, NumElts);
2211
2212   SmallVector<Constant *, 8> Elts;
2213   for (unsigned i = 0; i != NumElts; ++i) {
2214     Constant *FC = ConstantFoldCompareInstruction(pred, LHS->getOperand(i),
2215                                                         RHS->getOperand(i));
2216     if (FC) {
2217       uint64_t Val = cast<ConstantInt>(FC)->getZExtValue();
2218       if (Val != 0ULL)
2219         Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2220       else
2221         Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2222     }
2223   }
2224   if (Elts.size() == NumElts)
2225     return ConstantVector::get(&Elts[0], Elts.size());
2226
2227   // Look up the constant in the table first to ensure uniqueness
2228   std::vector<Constant*> ArgVec;
2229   ArgVec.push_back(LHS);
2230   ArgVec.push_back(RHS);
2231   // Get the key type with both the opcode and predicate
2232   const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2233   return ExprConstants->getOrCreate(ResultTy, Key);
2234 }
2235
2236 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2237                                             Constant *Idx) {
2238   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2239     return FC;          // Fold a few common cases...
2240   // Look up the constant in the table first to ensure uniqueness
2241   std::vector<Constant*> ArgVec(1, Val);
2242   ArgVec.push_back(Idx);
2243   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2244   return ExprConstants->getOrCreate(ReqTy, Key);
2245 }
2246
2247 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2248   assert(isa<VectorType>(Val->getType()) &&
2249          "Tried to create extractelement operation on non-vector type!");
2250   assert(Idx->getType() == Type::Int32Ty &&
2251          "Extractelement index must be i32 type!");
2252   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2253                              Val, Idx);
2254 }
2255
2256 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2257                                            Constant *Elt, Constant *Idx) {
2258   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2259     return FC;          // Fold a few common cases...
2260   // Look up the constant in the table first to ensure uniqueness
2261   std::vector<Constant*> ArgVec(1, Val);
2262   ArgVec.push_back(Elt);
2263   ArgVec.push_back(Idx);
2264   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2265   return ExprConstants->getOrCreate(ReqTy, Key);
2266 }
2267
2268 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
2269                                          Constant *Idx) {
2270   assert(isa<VectorType>(Val->getType()) &&
2271          "Tried to create insertelement operation on non-vector type!");
2272   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2273          && "Insertelement types must match!");
2274   assert(Idx->getType() == Type::Int32Ty &&
2275          "Insertelement index must be i32 type!");
2276   return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2277                             Val, Elt, Idx);
2278 }
2279
2280 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2281                                            Constant *V2, Constant *Mask) {
2282   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2283     return FC;          // Fold a few common cases...
2284   // Look up the constant in the table first to ensure uniqueness
2285   std::vector<Constant*> ArgVec(1, V1);
2286   ArgVec.push_back(V2);
2287   ArgVec.push_back(Mask);
2288   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2289   return ExprConstants->getOrCreate(ReqTy, Key);
2290 }
2291
2292 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
2293                                          Constant *Mask) {
2294   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2295          "Invalid shuffle vector constant expr operands!");
2296   return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2297 }
2298
2299 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2300                                          Constant *Val,
2301                                        Constant *const *Idxs, unsigned NumIdx) {
2302   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2303                                           Idxs+NumIdx) == Val->getType() &&
2304          "insertvalue indices invalid!");
2305   assert(Agg->getType() == ReqTy &&
2306          "insertvalue type invalid!");
2307
2308   if (Constant *FC = ConstantFoldInsertValue(Agg, Val, Idxs, NumIdx))
2309     return FC;          // Fold a few common cases...
2310
2311   assert(isa<PointerType>(Agg->getType()) &&
2312          "Non-pointer type for constant InsertValue expression");
2313   // Look up the constant in the table first to ensure uniqueness
2314   std::vector<Constant*> ArgVec;
2315   ArgVec.reserve(NumIdx+2);
2316   ArgVec.push_back(Agg);
2317   ArgVec.push_back(Val);
2318   for (unsigned i = 0; i != NumIdx; ++i)
2319     ArgVec.push_back(cast<Constant>(Idxs[i]));
2320   const ExprMapKeyType Key(Instruction::InsertValue, ArgVec);
2321   return ExprConstants->getOrCreate(ReqTy, Key);
2322 }
2323
2324 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2325                                     Constant* const *IdxList, unsigned NumIdx) {
2326   assert((isa<StructType>(Agg->getType()) || isa<ArrayType>(Agg->getType()) ||
2327           isa<VectorType>(Agg->getType())) &&
2328          "Tried to create insertelement operation on non-aggregate type!");
2329
2330   const Type *ReqTy =
2331     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2332   assert(ReqTy && "insertvalue indices invalid!");
2333   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2334 }
2335
2336 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2337                                        Constant *const *Idxs, unsigned NumIdx) {
2338   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2339                                           Idxs+NumIdx) == ReqTy &&
2340          "extractvalue indices invalid!");
2341
2342   if (Constant *FC = ConstantFoldExtractValue(Agg, Idxs, NumIdx))
2343     return FC;          // Fold a few common cases...
2344
2345   assert(isa<PointerType>(Agg->getType()) &&
2346          "Non-pointer type for constant ExtractValue expression");
2347   // Look up the constant in the table first to ensure uniqueness
2348   std::vector<Constant*> ArgVec;
2349   ArgVec.reserve(NumIdx+1);
2350   ArgVec.push_back(Agg);
2351   for (unsigned i = 0; i != NumIdx; ++i)
2352     ArgVec.push_back(cast<Constant>(Idxs[i]));
2353   const ExprMapKeyType Key(Instruction::ExtractValue, ArgVec);
2354   return ExprConstants->getOrCreate(ReqTy, Key);
2355 }
2356
2357 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2358                                     Constant* const *IdxList, unsigned NumIdx) {
2359   assert((isa<StructType>(Agg->getType()) || isa<ArrayType>(Agg->getType()) ||
2360           isa<VectorType>(Agg->getType())) &&
2361          "Tried to create extractelement operation on non-aggregate type!");
2362
2363   const Type *ReqTy =
2364     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2365   assert(ReqTy && "extractvalue indices invalid!");
2366   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2367 }
2368
2369 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2370   if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2371     if (PTy->getElementType()->isFloatingPoint()) {
2372       std::vector<Constant*> zeros(PTy->getNumElements(),
2373                            ConstantFP::getNegativeZero(PTy->getElementType()));
2374       return ConstantVector::get(PTy, zeros);
2375     }
2376
2377   if (Ty->isFloatingPoint()) 
2378     return ConstantFP::getNegativeZero(Ty);
2379
2380   return Constant::getNullValue(Ty);
2381 }
2382
2383 // destroyConstant - Remove the constant from the constant table...
2384 //
2385 void ConstantExpr::destroyConstant() {
2386   ExprConstants->remove(this);
2387   destroyConstantImpl();
2388 }
2389
2390 const char *ConstantExpr::getOpcodeName() const {
2391   return Instruction::getOpcodeName(getOpcode());
2392 }
2393
2394 //===----------------------------------------------------------------------===//
2395 //                replaceUsesOfWithOnConstant implementations
2396
2397 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2398 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2399 /// etc.
2400 ///
2401 /// Note that we intentionally replace all uses of From with To here.  Consider
2402 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2403 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2404 /// single invocation handles all 1000 uses.  Handling them one at a time would
2405 /// work, but would be really slow because it would have to unique each updated
2406 /// array instance.
2407 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2408                                                 Use *U) {
2409   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2410   Constant *ToC = cast<Constant>(To);
2411
2412   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2413   Lookup.first.first = getType();
2414   Lookup.second = this;
2415
2416   std::vector<Constant*> &Values = Lookup.first.second;
2417   Values.reserve(getNumOperands());  // Build replacement array.
2418
2419   // Fill values with the modified operands of the constant array.  Also, 
2420   // compute whether this turns into an all-zeros array.
2421   bool isAllZeros = false;
2422   unsigned NumUpdated = 0;
2423   if (!ToC->isNullValue()) {
2424     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2425       Constant *Val = cast<Constant>(O->get());
2426       if (Val == From) {
2427         Val = ToC;
2428         ++NumUpdated;
2429       }
2430       Values.push_back(Val);
2431     }
2432   } else {
2433     isAllZeros = true;
2434     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2435       Constant *Val = cast<Constant>(O->get());
2436       if (Val == From) {
2437         Val = ToC;
2438         ++NumUpdated;
2439       }
2440       Values.push_back(Val);
2441       if (isAllZeros) isAllZeros = Val->isNullValue();
2442     }
2443   }
2444   
2445   Constant *Replacement = 0;
2446   if (isAllZeros) {
2447     Replacement = ConstantAggregateZero::get(getType());
2448   } else {
2449     // Check to see if we have this array type already.
2450     bool Exists;
2451     ArrayConstantsTy::MapTy::iterator I =
2452       ArrayConstants->InsertOrGetItem(Lookup, Exists);
2453     
2454     if (Exists) {
2455       Replacement = I->second;
2456     } else {
2457       // Okay, the new shape doesn't exist in the system yet.  Instead of
2458       // creating a new constant array, inserting it, replaceallusesof'ing the
2459       // old with the new, then deleting the old... just update the current one
2460       // in place!
2461       ArrayConstants->MoveConstantToNewSlot(this, I);
2462       
2463       // Update to the new value.  Optimize for the case when we have a single
2464       // operand that we're changing, but handle bulk updates efficiently.
2465       if (NumUpdated == 1) {
2466         unsigned OperandToUpdate = U-OperandList;
2467         assert(getOperand(OperandToUpdate) == From &&
2468                "ReplaceAllUsesWith broken!");
2469         setOperand(OperandToUpdate, ToC);
2470       } else {
2471         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2472           if (getOperand(i) == From)
2473             setOperand(i, ToC);
2474       }
2475       return;
2476     }
2477   }
2478  
2479   // Otherwise, I do need to replace this with an existing value.
2480   assert(Replacement != this && "I didn't contain From!");
2481   
2482   // Everyone using this now uses the replacement.
2483   uncheckedReplaceAllUsesWith(Replacement);
2484   
2485   // Delete the old constant!
2486   destroyConstant();
2487 }
2488
2489 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2490                                                  Use *U) {
2491   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2492   Constant *ToC = cast<Constant>(To);
2493
2494   unsigned OperandToUpdate = U-OperandList;
2495   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2496
2497   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2498   Lookup.first.first = getType();
2499   Lookup.second = this;
2500   std::vector<Constant*> &Values = Lookup.first.second;
2501   Values.reserve(getNumOperands());  // Build replacement struct.
2502   
2503   
2504   // Fill values with the modified operands of the constant struct.  Also, 
2505   // compute whether this turns into an all-zeros struct.
2506   bool isAllZeros = false;
2507   if (!ToC->isNullValue()) {
2508     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2509       Values.push_back(cast<Constant>(O->get()));
2510   } else {
2511     isAllZeros = true;
2512     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2513       Constant *Val = cast<Constant>(O->get());
2514       Values.push_back(Val);
2515       if (isAllZeros) isAllZeros = Val->isNullValue();
2516     }
2517   }
2518   Values[OperandToUpdate] = ToC;
2519   
2520   Constant *Replacement = 0;
2521   if (isAllZeros) {
2522     Replacement = ConstantAggregateZero::get(getType());
2523   } else {
2524     // Check to see if we have this array type already.
2525     bool Exists;
2526     StructConstantsTy::MapTy::iterator I =
2527       StructConstants->InsertOrGetItem(Lookup, Exists);
2528     
2529     if (Exists) {
2530       Replacement = I->second;
2531     } else {
2532       // Okay, the new shape doesn't exist in the system yet.  Instead of
2533       // creating a new constant struct, inserting it, replaceallusesof'ing the
2534       // old with the new, then deleting the old... just update the current one
2535       // in place!
2536       StructConstants->MoveConstantToNewSlot(this, I);
2537       
2538       // Update to the new value.
2539       setOperand(OperandToUpdate, ToC);
2540       return;
2541     }
2542   }
2543   
2544   assert(Replacement != this && "I didn't contain From!");
2545   
2546   // Everyone using this now uses the replacement.
2547   uncheckedReplaceAllUsesWith(Replacement);
2548   
2549   // Delete the old constant!
2550   destroyConstant();
2551 }
2552
2553 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2554                                                  Use *U) {
2555   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2556   
2557   std::vector<Constant*> Values;
2558   Values.reserve(getNumOperands());  // Build replacement array...
2559   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2560     Constant *Val = getOperand(i);
2561     if (Val == From) Val = cast<Constant>(To);
2562     Values.push_back(Val);
2563   }
2564   
2565   Constant *Replacement = ConstantVector::get(getType(), Values);
2566   assert(Replacement != this && "I didn't contain From!");
2567   
2568   // Everyone using this now uses the replacement.
2569   uncheckedReplaceAllUsesWith(Replacement);
2570   
2571   // Delete the old constant!
2572   destroyConstant();
2573 }
2574
2575 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2576                                                Use *U) {
2577   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2578   Constant *To = cast<Constant>(ToV);
2579   
2580   Constant *Replacement = 0;
2581   if (getOpcode() == Instruction::GetElementPtr) {
2582     SmallVector<Constant*, 8> Indices;
2583     Constant *Pointer = getOperand(0);
2584     Indices.reserve(getNumOperands()-1);
2585     if (Pointer == From) Pointer = To;
2586     
2587     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2588       Constant *Val = getOperand(i);
2589       if (Val == From) Val = To;
2590       Indices.push_back(Val);
2591     }
2592     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2593                                                  &Indices[0], Indices.size());
2594   } else if (getOpcode() == Instruction::ExtractValue) {
2595     SmallVector<Constant*, 8> Indices;
2596     Constant *Agg = getOperand(0);
2597     Indices.reserve(getNumOperands()-1);
2598     if (Agg == From) Agg = To;
2599     
2600     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2601       Constant *Val = getOperand(i);
2602       if (Val == From) Val = To;
2603       Indices.push_back(Val);
2604     }
2605     Replacement = ConstantExpr::getExtractValue(Agg,
2606                                                 &Indices[0], Indices.size());
2607   } else if (getOpcode() == Instruction::InsertValue) {
2608     SmallVector<Constant*, 8> Indices;
2609     Constant *Agg = getOperand(0);
2610     Constant *Val = getOperand(1);
2611     Indices.reserve(getNumOperands()-2);
2612     if (Agg == From) Agg = To;
2613     if (Val == From) Val = To;
2614     
2615     for (unsigned i = 2, e = getNumOperands(); i != e; ++i) {
2616       Constant *Val = getOperand(i);
2617       if (Val == From) Val = To;
2618       Indices.push_back(Val);
2619     }
2620     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2621                                                &Indices[0], Indices.size());
2622   } else if (isCast()) {
2623     assert(getOperand(0) == From && "Cast only has one use!");
2624     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2625   } else if (getOpcode() == Instruction::Select) {
2626     Constant *C1 = getOperand(0);
2627     Constant *C2 = getOperand(1);
2628     Constant *C3 = getOperand(2);
2629     if (C1 == From) C1 = To;
2630     if (C2 == From) C2 = To;
2631     if (C3 == From) C3 = To;
2632     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2633   } else if (getOpcode() == Instruction::ExtractElement) {
2634     Constant *C1 = getOperand(0);
2635     Constant *C2 = getOperand(1);
2636     if (C1 == From) C1 = To;
2637     if (C2 == From) C2 = To;
2638     Replacement = ConstantExpr::getExtractElement(C1, C2);
2639   } else if (getOpcode() == Instruction::InsertElement) {
2640     Constant *C1 = getOperand(0);
2641     Constant *C2 = getOperand(1);
2642     Constant *C3 = getOperand(1);
2643     if (C1 == From) C1 = To;
2644     if (C2 == From) C2 = To;
2645     if (C3 == From) C3 = To;
2646     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2647   } else if (getOpcode() == Instruction::ShuffleVector) {
2648     Constant *C1 = getOperand(0);
2649     Constant *C2 = getOperand(1);
2650     Constant *C3 = getOperand(2);
2651     if (C1 == From) C1 = To;
2652     if (C2 == From) C2 = To;
2653     if (C3 == From) C3 = To;
2654     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2655   } else if (isCompare()) {
2656     Constant *C1 = getOperand(0);
2657     Constant *C2 = getOperand(1);
2658     if (C1 == From) C1 = To;
2659     if (C2 == From) C2 = To;
2660     if (getOpcode() == Instruction::ICmp)
2661       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2662     else
2663       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2664   } else if (getNumOperands() == 2) {
2665     Constant *C1 = getOperand(0);
2666     Constant *C2 = getOperand(1);
2667     if (C1 == From) C1 = To;
2668     if (C2 == From) C2 = To;
2669     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2670   } else {
2671     assert(0 && "Unknown ConstantExpr type!");
2672     return;
2673   }
2674   
2675   assert(Replacement != this && "I didn't contain From!");
2676   
2677   // Everyone using this now uses the replacement.
2678   uncheckedReplaceAllUsesWith(Replacement);
2679   
2680   // Delete the old constant!
2681   destroyConstant();
2682 }
2683
2684
2685 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2686 /// global into a string value.  Return an empty string if we can't do it.
2687 /// Parameter Chop determines if the result is chopped at the first null
2688 /// terminator.
2689 ///
2690 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2691   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2692     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2693       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2694       if (Init->isString()) {
2695         std::string Result = Init->getAsString();
2696         if (Offset < Result.size()) {
2697           // If we are pointing INTO The string, erase the beginning...
2698           Result.erase(Result.begin(), Result.begin()+Offset);
2699
2700           // Take off the null terminator, and any string fragments after it.
2701           if (Chop) {
2702             std::string::size_type NullPos = Result.find_first_of((char)0);
2703             if (NullPos != std::string::npos)
2704               Result.erase(Result.begin()+NullPos, Result.end());
2705           }
2706           return Result;
2707         }
2708       }
2709     }
2710   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2711     if (CE->getOpcode() == Instruction::GetElementPtr) {
2712       // Turn a gep into the specified offset.
2713       if (CE->getNumOperands() == 3 &&
2714           cast<Constant>(CE->getOperand(1))->isNullValue() &&
2715           isa<ConstantInt>(CE->getOperand(2))) {
2716         Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2717         return CE->getOperand(0)->getStringValue(Chop, Offset);
2718       }
2719     }
2720   }
2721   return "";
2722 }