0b8fcc43258c2c52b8d2cd762af3ec38cb35f041
[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, new Use[V.size()], V.size()) {
358   assert(V.size() == T->getNumElements() &&
359          "Invalid initializer vector for constant array");
360   Use *OL = OperandList;
361   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
362        I != E; ++I, ++OL) {
363     Constant *C = *I;
364     assert((C->getType() == T->getElementType() ||
365             (T->isAbstract() &&
366              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
367            "Initializer for array element doesn't match array element type!");
368     OL->init(C, this);
369   }
370 }
371
372 ConstantArray::~ConstantArray() {
373   delete [] OperandList;
374 }
375
376 ConstantStruct::ConstantStruct(const StructType *T,
377                                const std::vector<Constant*> &V)
378   : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
379   assert(V.size() == T->getNumElements() &&
380          "Invalid initializer vector for constant structure");
381   Use *OL = OperandList;
382   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
383        I != E; ++I, ++OL) {
384     Constant *C = *I;
385     assert((C->getType() == T->getElementType(I-V.begin()) ||
386             ((T->getElementType(I-V.begin())->isAbstract() ||
387               C->getType()->isAbstract()) &&
388              T->getElementType(I-V.begin())->getTypeID() == 
389                    C->getType()->getTypeID())) &&
390            "Initializer for struct element doesn't match struct element type!");
391     OL->init(C, this);
392   }
393 }
394
395 ConstantStruct::~ConstantStruct() {
396   delete [] OperandList;
397 }
398
399
400 ConstantVector::ConstantVector(const VectorType *T,
401                                const std::vector<Constant*> &V)
402   : Constant(T, ConstantVectorVal, new Use[V.size()], V.size()) {
403   Use *OL = OperandList;
404     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
405          I != E; ++I, ++OL) {
406       Constant *C = *I;
407       assert((C->getType() == T->getElementType() ||
408             (T->isAbstract() &&
409              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
410            "Initializer for vector element doesn't match vector element type!");
411     OL->init(C, this);
412   }
413 }
414
415 ConstantVector::~ConstantVector() {
416   delete [] OperandList;
417 }
418
419 // We declare several classes private to this file, so use an anonymous
420 // namespace
421 namespace {
422
423 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
424 /// behind the scenes to implement unary constant exprs.
425 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
426   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
427   Use Op;
428 public:
429   // allocate space for exactly one operand
430   void *operator new(size_t s) {
431     return User::operator new(s, 1);
432   }
433   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
434     : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
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   Use Ops[2];
442 public:
443   // allocate space for exactly two operands
444   void *operator new(size_t s) {
445     return User::operator new(s, 2);
446   }
447   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
448     : ConstantExpr(C1->getType(), Opcode, Ops, 2) {
449     Ops[0].init(C1, this);
450     Ops[1].init(C2, this);
451   }
452 };
453
454 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
455 /// behind the scenes to implement select constant exprs.
456 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
457   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
458   Use Ops[3];
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, Ops, 3) {
466     Ops[0].init(C1, this);
467     Ops[1].init(C2, this);
468     Ops[2].init(C3, this);
469   }
470 };
471
472 /// ExtractElementConstantExpr - This class is private to
473 /// Constants.cpp, and is used behind the scenes to implement
474 /// extractelement constant exprs.
475 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
476   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
477   Use Ops[2];
478 public:
479   // allocate space for exactly two operands
480   void *operator new(size_t s) {
481     return User::operator new(s, 2);
482   }
483   ExtractElementConstantExpr(Constant *C1, Constant *C2)
484     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
485                    Instruction::ExtractElement, Ops, 2) {
486     Ops[0].init(C1, this);
487     Ops[1].init(C2, this);
488   }
489 };
490
491 /// InsertElementConstantExpr - This class is private to
492 /// Constants.cpp, and is used behind the scenes to implement
493 /// insertelement constant exprs.
494 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
495   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
496   Use Ops[3];
497 public:
498   // allocate space for exactly three operands
499   void *operator new(size_t s) {
500     return User::operator new(s, 3);
501   }
502   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
503     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
504                    Ops, 3) {
505     Ops[0].init(C1, this);
506     Ops[1].init(C2, this);
507     Ops[2].init(C3, this);
508   }
509 };
510
511 /// ShuffleVectorConstantExpr - This class is private to
512 /// Constants.cpp, and is used behind the scenes to implement
513 /// shufflevector constant exprs.
514 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
515   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
516   Use Ops[3];
517 public:
518   // allocate space for exactly three operands
519   void *operator new(size_t s) {
520     return User::operator new(s, 3);
521   }
522   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
523   : ConstantExpr(C1->getType(), Instruction::ShuffleVector, 
524                  Ops, 3) {
525     Ops[0].init(C1, this);
526     Ops[1].init(C2, this);
527     Ops[2].init(C3, this);
528   }
529 };
530
531 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
532 /// used behind the scenes to implement getelementpr constant exprs.
533 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
534   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
535                             const Type *DestTy)
536     : ConstantExpr(DestTy, Instruction::GetElementPtr,
537                    new Use[IdxList.size()+1], IdxList.size()+1) {
538     OperandList[0].init(C, this);
539     for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
540       OperandList[i+1].init(IdxList[i], this);
541   }
542 public:
543   static GetElementPtrConstantExpr *Create(Constant *C, const std::vector<Constant*> &IdxList,
544                                     const Type *DestTy) {
545     return new(IdxList.size() + 1/*FIXME*/) GetElementPtrConstantExpr(C, IdxList, DestTy);
546   }
547   ~GetElementPtrConstantExpr() {
548     delete [] OperandList;
549   }
550 };
551
552 // CompareConstantExpr - This class is private to Constants.cpp, and is used
553 // behind the scenes to implement ICmp and FCmp constant expressions. This is
554 // needed in order to store the predicate value for these instructions.
555 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
556   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
557   // allocate space for exactly two operands
558   void *operator new(size_t s) {
559     return User::operator new(s, 2);
560   }
561   unsigned short predicate;
562   Use Ops[2];
563   CompareConstantExpr(Instruction::OtherOps opc, unsigned short pred, 
564                       Constant* LHS, Constant* RHS)
565     : ConstantExpr(Type::Int1Ty, opc, Ops, 2), predicate(pred) {
566     OperandList[0].init(LHS, this);
567     OperandList[1].init(RHS, this);
568   }
569 };
570
571 } // end anonymous namespace
572
573
574 // Utility function for determining if a ConstantExpr is a CastOp or not. This
575 // can't be inline because we don't want to #include Instruction.h into
576 // Constant.h
577 bool ConstantExpr::isCast() const {
578   return Instruction::isCast(getOpcode());
579 }
580
581 bool ConstantExpr::isCompare() const {
582   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
583 }
584
585 /// ConstantExpr::get* - Return some common constants without having to
586 /// specify the full Instruction::OPCODE identifier.
587 ///
588 Constant *ConstantExpr::getNeg(Constant *C) {
589   return get(Instruction::Sub,
590              ConstantExpr::getZeroValueForNegationExpr(C->getType()),
591              C);
592 }
593 Constant *ConstantExpr::getNot(Constant *C) {
594   assert(isa<IntegerType>(C->getType()) && "Cannot NOT a nonintegral value!");
595   return get(Instruction::Xor, C,
596              ConstantInt::getAllOnesValue(C->getType()));
597 }
598 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
599   return get(Instruction::Add, C1, C2);
600 }
601 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
602   return get(Instruction::Sub, C1, C2);
603 }
604 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
605   return get(Instruction::Mul, C1, C2);
606 }
607 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
608   return get(Instruction::UDiv, C1, C2);
609 }
610 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
611   return get(Instruction::SDiv, C1, C2);
612 }
613 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
614   return get(Instruction::FDiv, C1, C2);
615 }
616 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
617   return get(Instruction::URem, C1, C2);
618 }
619 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
620   return get(Instruction::SRem, C1, C2);
621 }
622 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
623   return get(Instruction::FRem, C1, C2);
624 }
625 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
626   return get(Instruction::And, C1, C2);
627 }
628 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
629   return get(Instruction::Or, C1, C2);
630 }
631 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
632   return get(Instruction::Xor, C1, C2);
633 }
634 unsigned ConstantExpr::getPredicate() const {
635   assert(getOpcode() == Instruction::FCmp || getOpcode() == Instruction::ICmp);
636   return ((const CompareConstantExpr*)this)->predicate;
637 }
638 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
639   return get(Instruction::Shl, C1, C2);
640 }
641 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
642   return get(Instruction::LShr, C1, C2);
643 }
644 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
645   return get(Instruction::AShr, C1, C2);
646 }
647
648 /// getWithOperandReplaced - Return a constant expression identical to this
649 /// one, but with the specified operand set to the specified value.
650 Constant *
651 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
652   assert(OpNo < getNumOperands() && "Operand num is out of range!");
653   assert(Op->getType() == getOperand(OpNo)->getType() &&
654          "Replacing operand with value of different type!");
655   if (getOperand(OpNo) == Op)
656     return const_cast<ConstantExpr*>(this);
657   
658   Constant *Op0, *Op1, *Op2;
659   switch (getOpcode()) {
660   case Instruction::Trunc:
661   case Instruction::ZExt:
662   case Instruction::SExt:
663   case Instruction::FPTrunc:
664   case Instruction::FPExt:
665   case Instruction::UIToFP:
666   case Instruction::SIToFP:
667   case Instruction::FPToUI:
668   case Instruction::FPToSI:
669   case Instruction::PtrToInt:
670   case Instruction::IntToPtr:
671   case Instruction::BitCast:
672     return ConstantExpr::getCast(getOpcode(), Op, getType());
673   case Instruction::Select:
674     Op0 = (OpNo == 0) ? Op : getOperand(0);
675     Op1 = (OpNo == 1) ? Op : getOperand(1);
676     Op2 = (OpNo == 2) ? Op : getOperand(2);
677     return ConstantExpr::getSelect(Op0, Op1, Op2);
678   case Instruction::InsertElement:
679     Op0 = (OpNo == 0) ? Op : getOperand(0);
680     Op1 = (OpNo == 1) ? Op : getOperand(1);
681     Op2 = (OpNo == 2) ? Op : getOperand(2);
682     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
683   case Instruction::ExtractElement:
684     Op0 = (OpNo == 0) ? Op : getOperand(0);
685     Op1 = (OpNo == 1) ? Op : getOperand(1);
686     return ConstantExpr::getExtractElement(Op0, Op1);
687   case Instruction::ShuffleVector:
688     Op0 = (OpNo == 0) ? Op : getOperand(0);
689     Op1 = (OpNo == 1) ? Op : getOperand(1);
690     Op2 = (OpNo == 2) ? Op : getOperand(2);
691     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
692   case Instruction::GetElementPtr: {
693     SmallVector<Constant*, 8> Ops;
694     Ops.resize(getNumOperands());
695     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
696       Ops[i] = getOperand(i);
697     if (OpNo == 0)
698       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
699     Ops[OpNo-1] = Op;
700     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
701   }
702   default:
703     assert(getNumOperands() == 2 && "Must be binary operator?");
704     Op0 = (OpNo == 0) ? Op : getOperand(0);
705     Op1 = (OpNo == 1) ? Op : getOperand(1);
706     return ConstantExpr::get(getOpcode(), Op0, Op1);
707   }
708 }
709
710 /// getWithOperands - This returns the current constant expression with the
711 /// operands replaced with the specified values.  The specified operands must
712 /// match count and type with the existing ones.
713 Constant *ConstantExpr::
714 getWithOperands(const std::vector<Constant*> &Ops) const {
715   assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
716   bool AnyChange = false;
717   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
718     assert(Ops[i]->getType() == getOperand(i)->getType() &&
719            "Operand type mismatch!");
720     AnyChange |= Ops[i] != getOperand(i);
721   }
722   if (!AnyChange)  // No operands changed, return self.
723     return const_cast<ConstantExpr*>(this);
724
725   switch (getOpcode()) {
726   case Instruction::Trunc:
727   case Instruction::ZExt:
728   case Instruction::SExt:
729   case Instruction::FPTrunc:
730   case Instruction::FPExt:
731   case Instruction::UIToFP:
732   case Instruction::SIToFP:
733   case Instruction::FPToUI:
734   case Instruction::FPToSI:
735   case Instruction::PtrToInt:
736   case Instruction::IntToPtr:
737   case Instruction::BitCast:
738     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
739   case Instruction::Select:
740     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
741   case Instruction::InsertElement:
742     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
743   case Instruction::ExtractElement:
744     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
745   case Instruction::ShuffleVector:
746     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
747   case Instruction::GetElementPtr:
748     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
749   case Instruction::ICmp:
750   case Instruction::FCmp:
751     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
752   default:
753     assert(getNumOperands() == 2 && "Must be binary operator?");
754     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
755   }
756 }
757
758
759 //===----------------------------------------------------------------------===//
760 //                      isValueValidForType implementations
761
762 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
763   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
764   if (Ty == Type::Int1Ty)
765     return Val == 0 || Val == 1;
766   if (NumBits >= 64)
767     return true; // always true, has to fit in largest type
768   uint64_t Max = (1ll << NumBits) - 1;
769   return Val <= Max;
770 }
771
772 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
773   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
774   if (Ty == Type::Int1Ty)
775     return Val == 0 || Val == 1 || Val == -1;
776   if (NumBits >= 64)
777     return true; // always true, has to fit in largest type
778   int64_t Min = -(1ll << (NumBits-1));
779   int64_t Max = (1ll << (NumBits-1)) - 1;
780   return (Val >= Min && Val <= Max);
781 }
782
783 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
784   // convert modifies in place, so make a copy.
785   APFloat Val2 = APFloat(Val);
786   switch (Ty->getTypeID()) {
787   default:
788     return false;         // These can't be represented as floating point!
789
790   // FIXME rounding mode needs to be more flexible
791   case Type::FloatTyID:
792     return &Val2.getSemantics() == &APFloat::IEEEsingle ||
793            Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) == 
794               APFloat::opOK;
795   case Type::DoubleTyID:
796     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
797            &Val2.getSemantics() == &APFloat::IEEEdouble ||
798            Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) == 
799              APFloat::opOK;
800   case Type::X86_FP80TyID:
801     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
802            &Val2.getSemantics() == &APFloat::IEEEdouble ||
803            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
804   case Type::FP128TyID:
805     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
806            &Val2.getSemantics() == &APFloat::IEEEdouble ||
807            &Val2.getSemantics() == &APFloat::IEEEquad;
808   case Type::PPC_FP128TyID:
809     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
810            &Val2.getSemantics() == &APFloat::IEEEdouble ||
811            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
812   }
813 }
814
815 //===----------------------------------------------------------------------===//
816 //                      Factory Function Implementation
817
818 // ConstantCreator - A class that is used to create constants by
819 // ValueMap*.  This class should be partially specialized if there is
820 // something strange that needs to be done to interface to the ctor for the
821 // constant.
822 //
823 namespace llvm {
824   template<class ConstantClass, class TypeClass, class ValType>
825   struct VISIBILITY_HIDDEN ConstantCreator {
826     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
827       unsigned FIXME = 0; // = traits<ValType>::uses(V)
828       return new(FIXME) ConstantClass(Ty, V);
829     }
830   };
831
832   template<class ConstantClass, class TypeClass>
833   struct VISIBILITY_HIDDEN ConvertConstantType {
834     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
835       assert(0 && "This type cannot be converted!\n");
836       abort();
837     }
838   };
839
840   template<class ValType, class TypeClass, class ConstantClass,
841            bool HasLargeKey = false  /*true for arrays and structs*/ >
842   class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
843   public:
844     typedef std::pair<const Type*, ValType> MapKey;
845     typedef std::map<MapKey, Constant *> MapTy;
846     typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
847     typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
848   private:
849     /// Map - This is the main map from the element descriptor to the Constants.
850     /// This is the primary way we avoid creating two of the same shape
851     /// constant.
852     MapTy Map;
853     
854     /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
855     /// from the constants to their element in Map.  This is important for
856     /// removal of constants from the array, which would otherwise have to scan
857     /// through the map with very large keys.
858     InverseMapTy InverseMap;
859
860     /// AbstractTypeMap - Map for abstract type constants.
861     ///
862     AbstractTypeMapTy AbstractTypeMap;
863
864   public:
865     typename MapTy::iterator map_end() { return Map.end(); }
866     
867     /// InsertOrGetItem - Return an iterator for the specified element.
868     /// If the element exists in the map, the returned iterator points to the
869     /// entry and Exists=true.  If not, the iterator points to the newly
870     /// inserted entry and returns Exists=false.  Newly inserted entries have
871     /// I->second == 0, and should be filled in.
872     typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
873                                    &InsertVal,
874                                    bool &Exists) {
875       std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
876       Exists = !IP.second;
877       return IP.first;
878     }
879     
880 private:
881     typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
882       if (HasLargeKey) {
883         typename InverseMapTy::iterator IMI = InverseMap.find(CP);
884         assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
885                IMI->second->second == CP &&
886                "InverseMap corrupt!");
887         return IMI->second;
888       }
889       
890       typename MapTy::iterator I =
891         Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
892       if (I == Map.end() || I->second != CP) {
893         // FIXME: This should not use a linear scan.  If this gets to be a
894         // performance problem, someone should look at this.
895         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
896           /* empty */;
897       }
898       return I;
899     }
900 public:
901     
902     /// getOrCreate - Return the specified constant from the map, creating it if
903     /// necessary.
904     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
905       MapKey Lookup(Ty, V);
906       typename MapTy::iterator I = Map.lower_bound(Lookup);
907       // Is it in the map?      
908       if (I != Map.end() && I->first == Lookup)
909         return static_cast<ConstantClass *>(I->second);  
910
911       // If no preexisting value, create one now...
912       ConstantClass *Result =
913         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
914
915       /// FIXME: why does this assert fail when loading 176.gcc?
916       //assert(Result->getType() == Ty && "Type specified is not correct!");
917       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
918
919       if (HasLargeKey)  // Remember the reverse mapping if needed.
920         InverseMap.insert(std::make_pair(Result, I));
921       
922       // If the type of the constant is abstract, make sure that an entry exists
923       // for it in the AbstractTypeMap.
924       if (Ty->isAbstract()) {
925         typename AbstractTypeMapTy::iterator TI =
926           AbstractTypeMap.lower_bound(Ty);
927
928         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
929           // Add ourselves to the ATU list of the type.
930           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
931
932           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
933         }
934       }
935       return Result;
936     }
937
938     void remove(ConstantClass *CP) {
939       typename MapTy::iterator I = FindExistingElement(CP);
940       assert(I != Map.end() && "Constant not found in constant table!");
941       assert(I->second == CP && "Didn't find correct element?");
942
943       if (HasLargeKey)  // Remember the reverse mapping if needed.
944         InverseMap.erase(CP);
945       
946       // Now that we found the entry, make sure this isn't the entry that
947       // the AbstractTypeMap points to.
948       const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
949       if (Ty->isAbstract()) {
950         assert(AbstractTypeMap.count(Ty) &&
951                "Abstract type not in AbstractTypeMap?");
952         typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
953         if (ATMEntryIt == I) {
954           // Yes, we are removing the representative entry for this type.
955           // See if there are any other entries of the same type.
956           typename MapTy::iterator TmpIt = ATMEntryIt;
957
958           // First check the entry before this one...
959           if (TmpIt != Map.begin()) {
960             --TmpIt;
961             if (TmpIt->first.first != Ty) // Not the same type, move back...
962               ++TmpIt;
963           }
964
965           // If we didn't find the same type, try to move forward...
966           if (TmpIt == ATMEntryIt) {
967             ++TmpIt;
968             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
969               --TmpIt;   // No entry afterwards with the same type
970           }
971
972           // If there is another entry in the map of the same abstract type,
973           // update the AbstractTypeMap entry now.
974           if (TmpIt != ATMEntryIt) {
975             ATMEntryIt = TmpIt;
976           } else {
977             // Otherwise, we are removing the last instance of this type
978             // from the table.  Remove from the ATM, and from user list.
979             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
980             AbstractTypeMap.erase(Ty);
981           }
982         }
983       }
984
985       Map.erase(I);
986     }
987
988     
989     /// MoveConstantToNewSlot - If we are about to change C to be the element
990     /// specified by I, update our internal data structures to reflect this
991     /// fact.
992     void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
993       // First, remove the old location of the specified constant in the map.
994       typename MapTy::iterator OldI = FindExistingElement(C);
995       assert(OldI != Map.end() && "Constant not found in constant table!");
996       assert(OldI->second == C && "Didn't find correct element?");
997       
998       // If this constant is the representative element for its abstract type,
999       // update the AbstractTypeMap so that the representative element is I.
1000       if (C->getType()->isAbstract()) {
1001         typename AbstractTypeMapTy::iterator ATI =
1002             AbstractTypeMap.find(C->getType());
1003         assert(ATI != AbstractTypeMap.end() &&
1004                "Abstract type not in AbstractTypeMap?");
1005         if (ATI->second == OldI)
1006           ATI->second = I;
1007       }
1008       
1009       // Remove the old entry from the map.
1010       Map.erase(OldI);
1011       
1012       // Update the inverse map so that we know that this constant is now
1013       // located at descriptor I.
1014       if (HasLargeKey) {
1015         assert(I->second == C && "Bad inversemap entry!");
1016         InverseMap[C] = I;
1017       }
1018     }
1019     
1020     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1021       typename AbstractTypeMapTy::iterator I =
1022         AbstractTypeMap.find(cast<Type>(OldTy));
1023
1024       assert(I != AbstractTypeMap.end() &&
1025              "Abstract type not in AbstractTypeMap?");
1026
1027       // Convert a constant at a time until the last one is gone.  The last one
1028       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1029       // eliminated eventually.
1030       do {
1031         ConvertConstantType<ConstantClass,
1032                             TypeClass>::convert(
1033                                 static_cast<ConstantClass *>(I->second->second),
1034                                                 cast<TypeClass>(NewTy));
1035
1036         I = AbstractTypeMap.find(cast<Type>(OldTy));
1037       } while (I != AbstractTypeMap.end());
1038     }
1039
1040     // If the type became concrete without being refined to any other existing
1041     // type, we just remove ourselves from the ATU list.
1042     void typeBecameConcrete(const DerivedType *AbsTy) {
1043       AbsTy->removeAbstractTypeUser(this);
1044     }
1045
1046     void dump() const {
1047       DOUT << "Constant.cpp: ValueMap\n";
1048     }
1049   };
1050 }
1051
1052
1053
1054 //---- ConstantAggregateZero::get() implementation...
1055 //
1056 namespace llvm {
1057   // ConstantAggregateZero does not take extra "value" argument...
1058   template<class ValType>
1059   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1060     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1061       return new ConstantAggregateZero(Ty);
1062     }
1063   };
1064
1065   template<>
1066   struct ConvertConstantType<ConstantAggregateZero, Type> {
1067     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1068       // Make everyone now use a constant of the new type...
1069       Constant *New = ConstantAggregateZero::get(NewTy);
1070       assert(New != OldC && "Didn't replace constant??");
1071       OldC->uncheckedReplaceAllUsesWith(New);
1072       OldC->destroyConstant();     // This constant is now dead, destroy it.
1073     }
1074   };
1075 }
1076
1077 static ManagedStatic<ValueMap<char, Type, 
1078                               ConstantAggregateZero> > AggZeroConstants;
1079
1080 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1081
1082 Constant *ConstantAggregateZero::get(const Type *Ty) {
1083   assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1084          "Cannot create an aggregate zero of non-aggregate type!");
1085   return AggZeroConstants->getOrCreate(Ty, 0);
1086 }
1087
1088 // destroyConstant - Remove the constant from the constant table...
1089 //
1090 void ConstantAggregateZero::destroyConstant() {
1091   AggZeroConstants->remove(this);
1092   destroyConstantImpl();
1093 }
1094
1095 //---- ConstantArray::get() implementation...
1096 //
1097 namespace llvm {
1098   template<>
1099   struct ConvertConstantType<ConstantArray, ArrayType> {
1100     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1101       // Make everyone now use a constant of the new type...
1102       std::vector<Constant*> C;
1103       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1104         C.push_back(cast<Constant>(OldC->getOperand(i)));
1105       Constant *New = ConstantArray::get(NewTy, C);
1106       assert(New != OldC && "Didn't replace constant??");
1107       OldC->uncheckedReplaceAllUsesWith(New);
1108       OldC->destroyConstant();    // This constant is now dead, destroy it.
1109     }
1110   };
1111 }
1112
1113 static std::vector<Constant*> getValType(ConstantArray *CA) {
1114   std::vector<Constant*> Elements;
1115   Elements.reserve(CA->getNumOperands());
1116   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1117     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1118   return Elements;
1119 }
1120
1121 typedef ValueMap<std::vector<Constant*>, ArrayType, 
1122                  ConstantArray, true /*largekey*/> ArrayConstantsTy;
1123 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1124
1125 Constant *ConstantArray::get(const ArrayType *Ty,
1126                              const std::vector<Constant*> &V) {
1127   // If this is an all-zero array, return a ConstantAggregateZero object
1128   if (!V.empty()) {
1129     Constant *C = V[0];
1130     if (!C->isNullValue())
1131       return ArrayConstants->getOrCreate(Ty, V);
1132     for (unsigned i = 1, e = V.size(); i != e; ++i)
1133       if (V[i] != C)
1134         return ArrayConstants->getOrCreate(Ty, V);
1135   }
1136   return ConstantAggregateZero::get(Ty);
1137 }
1138
1139 // destroyConstant - Remove the constant from the constant table...
1140 //
1141 void ConstantArray::destroyConstant() {
1142   ArrayConstants->remove(this);
1143   destroyConstantImpl();
1144 }
1145
1146 /// ConstantArray::get(const string&) - Return an array that is initialized to
1147 /// contain the specified string.  If length is zero then a null terminator is 
1148 /// added to the specified string so that it may be used in a natural way. 
1149 /// Otherwise, the length parameter specifies how much of the string to use 
1150 /// and it won't be null terminated.
1151 ///
1152 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1153   std::vector<Constant*> ElementVals;
1154   for (unsigned i = 0; i < Str.length(); ++i)
1155     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1156
1157   // Add a null terminator to the string...
1158   if (AddNull) {
1159     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1160   }
1161
1162   ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1163   return ConstantArray::get(ATy, ElementVals);
1164 }
1165
1166 /// isString - This method returns true if the array is an array of i8, and 
1167 /// if the elements of the array are all ConstantInt's.
1168 bool ConstantArray::isString() const {
1169   // Check the element type for i8...
1170   if (getType()->getElementType() != Type::Int8Ty)
1171     return false;
1172   // Check the elements to make sure they are all integers, not constant
1173   // expressions.
1174   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1175     if (!isa<ConstantInt>(getOperand(i)))
1176       return false;
1177   return true;
1178 }
1179
1180 /// isCString - This method returns true if the array is a string (see
1181 /// isString) and it ends in a null byte \0 and does not contains any other
1182 /// null bytes except its terminator.
1183 bool ConstantArray::isCString() const {
1184   // Check the element type for i8...
1185   if (getType()->getElementType() != Type::Int8Ty)
1186     return false;
1187   Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1188   // Last element must be a null.
1189   if (getOperand(getNumOperands()-1) != Zero)
1190     return false;
1191   // Other elements must be non-null integers.
1192   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1193     if (!isa<ConstantInt>(getOperand(i)))
1194       return false;
1195     if (getOperand(i) == Zero)
1196       return false;
1197   }
1198   return true;
1199 }
1200
1201
1202 // getAsString - If the sub-element type of this array is i8
1203 // then this method converts the array to an std::string and returns it.
1204 // Otherwise, it asserts out.
1205 //
1206 std::string ConstantArray::getAsString() const {
1207   assert(isString() && "Not a string!");
1208   std::string Result;
1209   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1210     Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1211   return Result;
1212 }
1213
1214
1215 //---- ConstantStruct::get() implementation...
1216 //
1217
1218 namespace llvm {
1219   template<>
1220   struct ConvertConstantType<ConstantStruct, StructType> {
1221     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1222       // Make everyone now use a constant of the new type...
1223       std::vector<Constant*> C;
1224       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1225         C.push_back(cast<Constant>(OldC->getOperand(i)));
1226       Constant *New = ConstantStruct::get(NewTy, C);
1227       assert(New != OldC && "Didn't replace constant??");
1228
1229       OldC->uncheckedReplaceAllUsesWith(New);
1230       OldC->destroyConstant();    // This constant is now dead, destroy it.
1231     }
1232   };
1233 }
1234
1235 typedef ValueMap<std::vector<Constant*>, StructType,
1236                  ConstantStruct, true /*largekey*/> StructConstantsTy;
1237 static ManagedStatic<StructConstantsTy> StructConstants;
1238
1239 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1240   std::vector<Constant*> Elements;
1241   Elements.reserve(CS->getNumOperands());
1242   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1243     Elements.push_back(cast<Constant>(CS->getOperand(i)));
1244   return Elements;
1245 }
1246
1247 Constant *ConstantStruct::get(const StructType *Ty,
1248                               const std::vector<Constant*> &V) {
1249   // Create a ConstantAggregateZero value if all elements are zeros...
1250   for (unsigned i = 0, e = V.size(); i != e; ++i)
1251     if (!V[i]->isNullValue())
1252       return StructConstants->getOrCreate(Ty, V);
1253
1254   return ConstantAggregateZero::get(Ty);
1255 }
1256
1257 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1258   std::vector<const Type*> StructEls;
1259   StructEls.reserve(V.size());
1260   for (unsigned i = 0, e = V.size(); i != e; ++i)
1261     StructEls.push_back(V[i]->getType());
1262   return get(StructType::get(StructEls, packed), V);
1263 }
1264
1265 // destroyConstant - Remove the constant from the constant table...
1266 //
1267 void ConstantStruct::destroyConstant() {
1268   StructConstants->remove(this);
1269   destroyConstantImpl();
1270 }
1271
1272 //---- ConstantVector::get() implementation...
1273 //
1274 namespace llvm {
1275   template<>
1276   struct ConvertConstantType<ConstantVector, VectorType> {
1277     static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1278       // Make everyone now use a constant of the new type...
1279       std::vector<Constant*> C;
1280       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1281         C.push_back(cast<Constant>(OldC->getOperand(i)));
1282       Constant *New = ConstantVector::get(NewTy, C);
1283       assert(New != OldC && "Didn't replace constant??");
1284       OldC->uncheckedReplaceAllUsesWith(New);
1285       OldC->destroyConstant();    // This constant is now dead, destroy it.
1286     }
1287   };
1288 }
1289
1290 static std::vector<Constant*> getValType(ConstantVector *CP) {
1291   std::vector<Constant*> Elements;
1292   Elements.reserve(CP->getNumOperands());
1293   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1294     Elements.push_back(CP->getOperand(i));
1295   return Elements;
1296 }
1297
1298 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1299                               ConstantVector> > VectorConstants;
1300
1301 Constant *ConstantVector::get(const VectorType *Ty,
1302                               const std::vector<Constant*> &V) {
1303   // If this is an all-zero vector, return a ConstantAggregateZero object
1304   if (!V.empty()) {
1305     Constant *C = V[0];
1306     if (!C->isNullValue())
1307       return VectorConstants->getOrCreate(Ty, V);
1308     for (unsigned i = 1, e = V.size(); i != e; ++i)
1309       if (V[i] != C)
1310         return VectorConstants->getOrCreate(Ty, V);
1311   }
1312   return ConstantAggregateZero::get(Ty);
1313 }
1314
1315 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1316   assert(!V.empty() && "Cannot infer type if V is empty");
1317   return get(VectorType::get(V.front()->getType(),V.size()), V);
1318 }
1319
1320 // destroyConstant - Remove the constant from the constant table...
1321 //
1322 void ConstantVector::destroyConstant() {
1323   VectorConstants->remove(this);
1324   destroyConstantImpl();
1325 }
1326
1327 /// This function will return true iff every element in this vector constant
1328 /// is set to all ones.
1329 /// @returns true iff this constant's emements are all set to all ones.
1330 /// @brief Determine if the value is all ones.
1331 bool ConstantVector::isAllOnesValue() const {
1332   // Check out first element.
1333   const Constant *Elt = getOperand(0);
1334   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1335   if (!CI || !CI->isAllOnesValue()) return false;
1336   // Then make sure all remaining elements point to the same value.
1337   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1338     if (getOperand(I) != Elt) return false;
1339   }
1340   return true;
1341 }
1342
1343 /// getSplatValue - If this is a splat constant, where all of the
1344 /// elements have the same value, return that value. Otherwise return null.
1345 Constant *ConstantVector::getSplatValue() {
1346   // Check out first element.
1347   Constant *Elt = getOperand(0);
1348   // Then make sure all remaining elements point to the same value.
1349   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1350     if (getOperand(I) != Elt) return 0;
1351   return Elt;
1352 }
1353
1354 //---- ConstantPointerNull::get() implementation...
1355 //
1356
1357 namespace llvm {
1358   // ConstantPointerNull does not take extra "value" argument...
1359   template<class ValType>
1360   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1361     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1362       return new ConstantPointerNull(Ty);
1363     }
1364   };
1365
1366   template<>
1367   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1368     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1369       // Make everyone now use a constant of the new type...
1370       Constant *New = ConstantPointerNull::get(NewTy);
1371       assert(New != OldC && "Didn't replace constant??");
1372       OldC->uncheckedReplaceAllUsesWith(New);
1373       OldC->destroyConstant();     // This constant is now dead, destroy it.
1374     }
1375   };
1376 }
1377
1378 static ManagedStatic<ValueMap<char, PointerType, 
1379                               ConstantPointerNull> > NullPtrConstants;
1380
1381 static char getValType(ConstantPointerNull *) {
1382   return 0;
1383 }
1384
1385
1386 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1387   return NullPtrConstants->getOrCreate(Ty, 0);
1388 }
1389
1390 // destroyConstant - Remove the constant from the constant table...
1391 //
1392 void ConstantPointerNull::destroyConstant() {
1393   NullPtrConstants->remove(this);
1394   destroyConstantImpl();
1395 }
1396
1397
1398 //---- UndefValue::get() implementation...
1399 //
1400
1401 namespace llvm {
1402   // UndefValue does not take extra "value" argument...
1403   template<class ValType>
1404   struct ConstantCreator<UndefValue, Type, ValType> {
1405     static UndefValue *create(const Type *Ty, const ValType &V) {
1406       return new UndefValue(Ty);
1407     }
1408   };
1409
1410   template<>
1411   struct ConvertConstantType<UndefValue, Type> {
1412     static void convert(UndefValue *OldC, const Type *NewTy) {
1413       // Make everyone now use a constant of the new type.
1414       Constant *New = UndefValue::get(NewTy);
1415       assert(New != OldC && "Didn't replace constant??");
1416       OldC->uncheckedReplaceAllUsesWith(New);
1417       OldC->destroyConstant();     // This constant is now dead, destroy it.
1418     }
1419   };
1420 }
1421
1422 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1423
1424 static char getValType(UndefValue *) {
1425   return 0;
1426 }
1427
1428
1429 UndefValue *UndefValue::get(const Type *Ty) {
1430   return UndefValueConstants->getOrCreate(Ty, 0);
1431 }
1432
1433 // destroyConstant - Remove the constant from the constant table.
1434 //
1435 void UndefValue::destroyConstant() {
1436   UndefValueConstants->remove(this);
1437   destroyConstantImpl();
1438 }
1439
1440
1441 //---- ConstantExpr::get() implementations...
1442 //
1443
1444 struct ExprMapKeyType {
1445   explicit ExprMapKeyType(unsigned opc, std::vector<Constant*> ops,
1446       unsigned short pred = 0) : opcode(opc), predicate(pred), operands(ops) { }
1447   uint16_t opcode;
1448   uint16_t predicate;
1449   std::vector<Constant*> operands;
1450   bool operator==(const ExprMapKeyType& that) const {
1451     return this->opcode == that.opcode &&
1452            this->predicate == that.predicate &&
1453            this->operands == that.operands;
1454   }
1455   bool operator<(const ExprMapKeyType & that) const {
1456     return this->opcode < that.opcode ||
1457       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1458       (this->opcode == that.opcode && this->predicate == that.predicate &&
1459        this->operands < that.operands);
1460   }
1461
1462   bool operator!=(const ExprMapKeyType& that) const {
1463     return !(*this == that);
1464   }
1465 };
1466
1467 namespace llvm {
1468   template<>
1469   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1470     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1471         unsigned short pred = 0) {
1472       if (Instruction::isCast(V.opcode))
1473         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1474       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1475            V.opcode < Instruction::BinaryOpsEnd))
1476         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1477       if (V.opcode == Instruction::Select)
1478         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1479                                       V.operands[2]);
1480       if (V.opcode == Instruction::ExtractElement)
1481         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1482       if (V.opcode == Instruction::InsertElement)
1483         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1484                                              V.operands[2]);
1485       if (V.opcode == Instruction::ShuffleVector)
1486         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1487                                              V.operands[2]);
1488       if (V.opcode == Instruction::GetElementPtr) {
1489         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1490         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1491       }
1492
1493       // The compare instructions are weird. We have to encode the predicate
1494       // value and it is combined with the instruction opcode by multiplying
1495       // the opcode by one hundred. We must decode this to get the predicate.
1496       if (V.opcode == Instruction::ICmp)
1497         return new CompareConstantExpr(Instruction::ICmp, V.predicate, 
1498                                        V.operands[0], V.operands[1]);
1499       if (V.opcode == Instruction::FCmp) 
1500         return new CompareConstantExpr(Instruction::FCmp, V.predicate, 
1501                                        V.operands[0], V.operands[1]);
1502       assert(0 && "Invalid ConstantExpr!");
1503       return 0;
1504     }
1505   };
1506
1507   template<>
1508   struct ConvertConstantType<ConstantExpr, Type> {
1509     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1510       Constant *New;
1511       switch (OldC->getOpcode()) {
1512       case Instruction::Trunc:
1513       case Instruction::ZExt:
1514       case Instruction::SExt:
1515       case Instruction::FPTrunc:
1516       case Instruction::FPExt:
1517       case Instruction::UIToFP:
1518       case Instruction::SIToFP:
1519       case Instruction::FPToUI:
1520       case Instruction::FPToSI:
1521       case Instruction::PtrToInt:
1522       case Instruction::IntToPtr:
1523       case Instruction::BitCast:
1524         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1525                                     NewTy);
1526         break;
1527       case Instruction::Select:
1528         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1529                                         OldC->getOperand(1),
1530                                         OldC->getOperand(2));
1531         break;
1532       default:
1533         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1534                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1535         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1536                                   OldC->getOperand(1));
1537         break;
1538       case Instruction::GetElementPtr:
1539         // Make everyone now use a constant of the new type...
1540         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1541         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1542                                                &Idx[0], Idx.size());
1543         break;
1544       }
1545
1546       assert(New != OldC && "Didn't replace constant??");
1547       OldC->uncheckedReplaceAllUsesWith(New);
1548       OldC->destroyConstant();    // This constant is now dead, destroy it.
1549     }
1550   };
1551 } // end namespace llvm
1552
1553
1554 static ExprMapKeyType getValType(ConstantExpr *CE) {
1555   std::vector<Constant*> Operands;
1556   Operands.reserve(CE->getNumOperands());
1557   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1558     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1559   return ExprMapKeyType(CE->getOpcode(), Operands, 
1560       CE->isCompare() ? CE->getPredicate() : 0);
1561 }
1562
1563 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1564                               ConstantExpr> > ExprConstants;
1565
1566 /// This is a utility function to handle folding of casts and lookup of the
1567 /// cast in the ExprConstants map. It is used by the various get* methods below.
1568 static inline Constant *getFoldedCast(
1569   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1570   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1571   // Fold a few common cases
1572   if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1573     return FC;
1574
1575   // Look up the constant in the table first to ensure uniqueness
1576   std::vector<Constant*> argVec(1, C);
1577   ExprMapKeyType Key(opc, argVec);
1578   return ExprConstants->getOrCreate(Ty, Key);
1579 }
1580  
1581 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1582   Instruction::CastOps opc = Instruction::CastOps(oc);
1583   assert(Instruction::isCast(opc) && "opcode out of range");
1584   assert(C && Ty && "Null arguments to getCast");
1585   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1586
1587   switch (opc) {
1588     default:
1589       assert(0 && "Invalid cast opcode");
1590       break;
1591     case Instruction::Trunc:    return getTrunc(C, Ty);
1592     case Instruction::ZExt:     return getZExt(C, Ty);
1593     case Instruction::SExt:     return getSExt(C, Ty);
1594     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1595     case Instruction::FPExt:    return getFPExtend(C, Ty);
1596     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1597     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1598     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1599     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1600     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1601     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1602     case Instruction::BitCast:  return getBitCast(C, Ty);
1603   }
1604   return 0;
1605
1606
1607 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1608   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1609     return getCast(Instruction::BitCast, C, Ty);
1610   return getCast(Instruction::ZExt, C, Ty);
1611 }
1612
1613 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1614   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1615     return getCast(Instruction::BitCast, C, Ty);
1616   return getCast(Instruction::SExt, C, Ty);
1617 }
1618
1619 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1620   if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1621     return getCast(Instruction::BitCast, C, Ty);
1622   return getCast(Instruction::Trunc, C, Ty);
1623 }
1624
1625 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1626   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1627   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1628
1629   if (Ty->isInteger())
1630     return getCast(Instruction::PtrToInt, S, Ty);
1631   return getCast(Instruction::BitCast, S, Ty);
1632 }
1633
1634 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1635                                        bool isSigned) {
1636   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1637   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1638   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1639   Instruction::CastOps opcode =
1640     (SrcBits == DstBits ? Instruction::BitCast :
1641      (SrcBits > DstBits ? Instruction::Trunc :
1642       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1643   return getCast(opcode, C, Ty);
1644 }
1645
1646 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1647   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
1648          "Invalid cast");
1649   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1650   unsigned DstBits = Ty->getPrimitiveSizeInBits();
1651   if (SrcBits == DstBits)
1652     return C; // Avoid a useless cast
1653   Instruction::CastOps opcode =
1654      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1655   return getCast(opcode, C, Ty);
1656 }
1657
1658 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1659   assert(C->getType()->isInteger() && "Trunc operand must be integer");
1660   assert(Ty->isInteger() && "Trunc produces only integral");
1661   assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1662          "SrcTy must be larger than DestTy for Trunc!");
1663
1664   return getFoldedCast(Instruction::Trunc, C, Ty);
1665 }
1666
1667 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1668   assert(C->getType()->isInteger() && "SEXt operand must be integral");
1669   assert(Ty->isInteger() && "SExt produces only integer");
1670   assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1671          "SrcTy must be smaller than DestTy for SExt!");
1672
1673   return getFoldedCast(Instruction::SExt, C, Ty);
1674 }
1675
1676 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1677   assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1678   assert(Ty->isInteger() && "ZExt produces only integer");
1679   assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1680          "SrcTy must be smaller than DestTy for ZExt!");
1681
1682   return getFoldedCast(Instruction::ZExt, C, Ty);
1683 }
1684
1685 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1686   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1687          C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1688          "This is an illegal floating point truncation!");
1689   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1690 }
1691
1692 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1693   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1694          C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1695          "This is an illegal floating point extension!");
1696   return getFoldedCast(Instruction::FPExt, C, Ty);
1697 }
1698
1699 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1700   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1701   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1702   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1703   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1704          "This is an illegal uint to floating point cast!");
1705   return getFoldedCast(Instruction::UIToFP, C, Ty);
1706 }
1707
1708 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1709   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1710   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1711   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1712   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1713          "This is an illegal sint to floating point cast!");
1714   return getFoldedCast(Instruction::SIToFP, C, Ty);
1715 }
1716
1717 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1718   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1719   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1720   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1721   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1722          "This is an illegal floating point to uint cast!");
1723   return getFoldedCast(Instruction::FPToUI, C, Ty);
1724 }
1725
1726 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1727   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1728   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1729   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1730   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1731          "This is an illegal floating point to sint cast!");
1732   return getFoldedCast(Instruction::FPToSI, C, Ty);
1733 }
1734
1735 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1736   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1737   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1738   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1739 }
1740
1741 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1742   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1743   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1744   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1745 }
1746
1747 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1748   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1749   // can't cast pointers to anything but pointers.
1750   const Type *SrcTy = C->getType();
1751   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1752          "BitCast cannot cast pointer to non-pointer and vice versa");
1753
1754   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1755   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1756   // destination bit widths are identical.
1757   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1758   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1759   assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1760   return getFoldedCast(Instruction::BitCast, C, DstTy);
1761 }
1762
1763 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1764   // sizeof is implemented as: (i64) gep (Ty*)null, 1
1765   Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1766   Constant *GEP =
1767     getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1768   return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1769 }
1770
1771 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1772                               Constant *C1, Constant *C2) {
1773   // Check the operands for consistency first
1774   assert(Opcode >= Instruction::BinaryOpsBegin &&
1775          Opcode <  Instruction::BinaryOpsEnd   &&
1776          "Invalid opcode in binary constant expression");
1777   assert(C1->getType() == C2->getType() &&
1778          "Operand types in binary constant expression should match");
1779
1780   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1781     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1782       return FC;          // Fold a few common cases...
1783
1784   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1785   ExprMapKeyType Key(Opcode, argVec);
1786   return ExprConstants->getOrCreate(ReqTy, Key);
1787 }
1788
1789 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1790                                      Constant *C1, Constant *C2) {
1791   switch (predicate) {
1792     default: assert(0 && "Invalid CmpInst predicate");
1793     case FCmpInst::FCMP_FALSE: case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_OGT:
1794     case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OLE:
1795     case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_ORD: case FCmpInst::FCMP_UNO:
1796     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UGT: case FCmpInst::FCMP_UGE:
1797     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_ULE: case FCmpInst::FCMP_UNE:
1798     case FCmpInst::FCMP_TRUE:
1799       return getFCmp(predicate, C1, C2);
1800     case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGT:
1801     case ICmpInst::ICMP_UGE: case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE:
1802     case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_SGE: case ICmpInst::ICMP_SLT:
1803     case ICmpInst::ICMP_SLE:
1804       return getICmp(predicate, C1, C2);
1805   }
1806 }
1807
1808 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1809 #ifndef NDEBUG
1810   switch (Opcode) {
1811   case Instruction::Add: 
1812   case Instruction::Sub:
1813   case Instruction::Mul: 
1814     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1815     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1816             isa<VectorType>(C1->getType())) &&
1817            "Tried to create an arithmetic operation on a non-arithmetic type!");
1818     break;
1819   case Instruction::UDiv: 
1820   case Instruction::SDiv: 
1821     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1822     assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1823       cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1824            "Tried to create an arithmetic operation on a non-arithmetic type!");
1825     break;
1826   case Instruction::FDiv:
1827     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1828     assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1829       && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint())) 
1830       && "Tried to create an arithmetic operation on a non-arithmetic type!");
1831     break;
1832   case Instruction::URem: 
1833   case Instruction::SRem: 
1834     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1835     assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
1836       cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
1837            "Tried to create an arithmetic operation on a non-arithmetic type!");
1838     break;
1839   case Instruction::FRem:
1840     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1841     assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
1842       && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint())) 
1843       && "Tried to create an arithmetic operation on a non-arithmetic type!");
1844     break;
1845   case Instruction::And:
1846   case Instruction::Or:
1847   case Instruction::Xor:
1848     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1849     assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
1850            "Tried to create a logical operation on a non-integral type!");
1851     break;
1852   case Instruction::Shl:
1853   case Instruction::LShr:
1854   case Instruction::AShr:
1855     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1856     assert(C1->getType()->isInteger() &&
1857            "Tried to create a shift operation on a non-integer type!");
1858     break;
1859   default:
1860     break;
1861   }
1862 #endif
1863
1864   return getTy(C1->getType(), Opcode, C1, C2);
1865 }
1866
1867 Constant *ConstantExpr::getCompare(unsigned short pred, 
1868                             Constant *C1, Constant *C2) {
1869   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1870   return getCompareTy(pred, C1, C2);
1871 }
1872
1873 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1874                                     Constant *V1, Constant *V2) {
1875   assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
1876   assert(V1->getType() == V2->getType() && "Select value types must match!");
1877   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1878
1879   if (ReqTy == V1->getType())
1880     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1881       return SC;        // Fold common cases
1882
1883   std::vector<Constant*> argVec(3, C);
1884   argVec[1] = V1;
1885   argVec[2] = V2;
1886   ExprMapKeyType Key(Instruction::Select, argVec);
1887   return ExprConstants->getOrCreate(ReqTy, Key);
1888 }
1889
1890 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1891                                            Value* const *Idxs,
1892                                            unsigned NumIdx) {
1893   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true) &&
1894          "GEP indices invalid!");
1895
1896   if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
1897     return FC;          // Fold a few common cases...
1898
1899   assert(isa<PointerType>(C->getType()) &&
1900          "Non-pointer type for constant GetElementPtr expression");
1901   // Look up the constant in the table first to ensure uniqueness
1902   std::vector<Constant*> ArgVec;
1903   ArgVec.reserve(NumIdx+1);
1904   ArgVec.push_back(C);
1905   for (unsigned i = 0; i != NumIdx; ++i)
1906     ArgVec.push_back(cast<Constant>(Idxs[i]));
1907   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1908   return ExprConstants->getOrCreate(ReqTy, Key);
1909 }
1910
1911 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1912                                          unsigned NumIdx) {
1913   // Get the result type of the getelementptr!
1914   const Type *Ty = 
1915     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx, true);
1916   assert(Ty && "GEP indices invalid!");
1917   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1918   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1919 }
1920
1921 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1922                                          unsigned NumIdx) {
1923   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1924 }
1925
1926
1927 Constant *
1928 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1929   assert(LHS->getType() == RHS->getType());
1930   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1931          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1932
1933   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1934     return FC;          // Fold a few common cases...
1935
1936   // Look up the constant in the table first to ensure uniqueness
1937   std::vector<Constant*> ArgVec;
1938   ArgVec.push_back(LHS);
1939   ArgVec.push_back(RHS);
1940   // Get the key type with both the opcode and predicate
1941   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1942   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1943 }
1944
1945 Constant *
1946 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1947   assert(LHS->getType() == RHS->getType());
1948   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1949
1950   if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1951     return FC;          // Fold a few common cases...
1952
1953   // Look up the constant in the table first to ensure uniqueness
1954   std::vector<Constant*> ArgVec;
1955   ArgVec.push_back(LHS);
1956   ArgVec.push_back(RHS);
1957   // Get the key type with both the opcode and predicate
1958   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1959   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1960 }
1961
1962 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1963                                             Constant *Idx) {
1964   if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1965     return FC;          // Fold a few common cases...
1966   // Look up the constant in the table first to ensure uniqueness
1967   std::vector<Constant*> ArgVec(1, Val);
1968   ArgVec.push_back(Idx);
1969   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1970   return ExprConstants->getOrCreate(ReqTy, Key);
1971 }
1972
1973 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1974   assert(isa<VectorType>(Val->getType()) &&
1975          "Tried to create extractelement operation on non-vector type!");
1976   assert(Idx->getType() == Type::Int32Ty &&
1977          "Extractelement index must be i32 type!");
1978   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1979                              Val, Idx);
1980 }
1981
1982 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1983                                            Constant *Elt, Constant *Idx) {
1984   if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1985     return FC;          // Fold a few common cases...
1986   // Look up the constant in the table first to ensure uniqueness
1987   std::vector<Constant*> ArgVec(1, Val);
1988   ArgVec.push_back(Elt);
1989   ArgVec.push_back(Idx);
1990   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1991   return ExprConstants->getOrCreate(ReqTy, Key);
1992 }
1993
1994 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1995                                          Constant *Idx) {
1996   assert(isa<VectorType>(Val->getType()) &&
1997          "Tried to create insertelement operation on non-vector type!");
1998   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1999          && "Insertelement types must match!");
2000   assert(Idx->getType() == Type::Int32Ty &&
2001          "Insertelement index must be i32 type!");
2002   return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2003                             Val, Elt, Idx);
2004 }
2005
2006 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2007                                            Constant *V2, Constant *Mask) {
2008   if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2009     return FC;          // Fold a few common cases...
2010   // Look up the constant in the table first to ensure uniqueness
2011   std::vector<Constant*> ArgVec(1, V1);
2012   ArgVec.push_back(V2);
2013   ArgVec.push_back(Mask);
2014   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2015   return ExprConstants->getOrCreate(ReqTy, Key);
2016 }
2017
2018 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
2019                                          Constant *Mask) {
2020   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2021          "Invalid shuffle vector constant expr operands!");
2022   return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2023 }
2024
2025 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2026   if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2027     if (PTy->getElementType()->isFloatingPoint()) {
2028       std::vector<Constant*> zeros(PTy->getNumElements(),
2029                            ConstantFP::getNegativeZero(PTy->getElementType()));
2030       return ConstantVector::get(PTy, zeros);
2031     }
2032
2033   if (Ty->isFloatingPoint()) 
2034     return ConstantFP::getNegativeZero(Ty);
2035
2036   return Constant::getNullValue(Ty);
2037 }
2038
2039 // destroyConstant - Remove the constant from the constant table...
2040 //
2041 void ConstantExpr::destroyConstant() {
2042   ExprConstants->remove(this);
2043   destroyConstantImpl();
2044 }
2045
2046 const char *ConstantExpr::getOpcodeName() const {
2047   return Instruction::getOpcodeName(getOpcode());
2048 }
2049
2050 //===----------------------------------------------------------------------===//
2051 //                replaceUsesOfWithOnConstant implementations
2052
2053 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2054 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
2055 /// etc.
2056 ///
2057 /// Note that we intentionally replace all uses of From with To here.  Consider
2058 /// a large array that uses 'From' 1000 times.  By handling this case all here,
2059 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2060 /// single invocation handles all 1000 uses.  Handling them one at a time would
2061 /// work, but would be really slow because it would have to unique each updated
2062 /// array instance.
2063 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2064                                                 Use *U) {
2065   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2066   Constant *ToC = cast<Constant>(To);
2067
2068   std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2069   Lookup.first.first = getType();
2070   Lookup.second = this;
2071
2072   std::vector<Constant*> &Values = Lookup.first.second;
2073   Values.reserve(getNumOperands());  // Build replacement array.
2074
2075   // Fill values with the modified operands of the constant array.  Also, 
2076   // compute whether this turns into an all-zeros array.
2077   bool isAllZeros = false;
2078   unsigned NumUpdated = 0;
2079   if (!ToC->isNullValue()) {
2080     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2081       Constant *Val = cast<Constant>(O->get());
2082       if (Val == From) {
2083         Val = ToC;
2084         ++NumUpdated;
2085       }
2086       Values.push_back(Val);
2087     }
2088   } else {
2089     isAllZeros = true;
2090     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2091       Constant *Val = cast<Constant>(O->get());
2092       if (Val == From) {
2093         Val = ToC;
2094         ++NumUpdated;
2095       }
2096       Values.push_back(Val);
2097       if (isAllZeros) isAllZeros = Val->isNullValue();
2098     }
2099   }
2100   
2101   Constant *Replacement = 0;
2102   if (isAllZeros) {
2103     Replacement = ConstantAggregateZero::get(getType());
2104   } else {
2105     // Check to see if we have this array type already.
2106     bool Exists;
2107     ArrayConstantsTy::MapTy::iterator I =
2108       ArrayConstants->InsertOrGetItem(Lookup, Exists);
2109     
2110     if (Exists) {
2111       Replacement = I->second;
2112     } else {
2113       // Okay, the new shape doesn't exist in the system yet.  Instead of
2114       // creating a new constant array, inserting it, replaceallusesof'ing the
2115       // old with the new, then deleting the old... just update the current one
2116       // in place!
2117       ArrayConstants->MoveConstantToNewSlot(this, I);
2118       
2119       // Update to the new value.  Optimize for the case when we have a single
2120       // operand that we're changing, but handle bulk updates efficiently.
2121       if (NumUpdated == 1) {
2122         unsigned OperandToUpdate = U-OperandList;
2123         assert(getOperand(OperandToUpdate) == From &&
2124                "ReplaceAllUsesWith broken!");
2125         setOperand(OperandToUpdate, ToC);
2126       } else {
2127         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2128           if (getOperand(i) == From)
2129             setOperand(i, ToC);
2130       }
2131       return;
2132     }
2133   }
2134  
2135   // Otherwise, I do need to replace this with an existing value.
2136   assert(Replacement != this && "I didn't contain From!");
2137   
2138   // Everyone using this now uses the replacement.
2139   uncheckedReplaceAllUsesWith(Replacement);
2140   
2141   // Delete the old constant!
2142   destroyConstant();
2143 }
2144
2145 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2146                                                  Use *U) {
2147   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2148   Constant *ToC = cast<Constant>(To);
2149
2150   unsigned OperandToUpdate = U-OperandList;
2151   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2152
2153   std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2154   Lookup.first.first = getType();
2155   Lookup.second = this;
2156   std::vector<Constant*> &Values = Lookup.first.second;
2157   Values.reserve(getNumOperands());  // Build replacement struct.
2158   
2159   
2160   // Fill values with the modified operands of the constant struct.  Also, 
2161   // compute whether this turns into an all-zeros struct.
2162   bool isAllZeros = false;
2163   if (!ToC->isNullValue()) {
2164     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2165       Values.push_back(cast<Constant>(O->get()));
2166   } else {
2167     isAllZeros = true;
2168     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2169       Constant *Val = cast<Constant>(O->get());
2170       Values.push_back(Val);
2171       if (isAllZeros) isAllZeros = Val->isNullValue();
2172     }
2173   }
2174   Values[OperandToUpdate] = ToC;
2175   
2176   Constant *Replacement = 0;
2177   if (isAllZeros) {
2178     Replacement = ConstantAggregateZero::get(getType());
2179   } else {
2180     // Check to see if we have this array type already.
2181     bool Exists;
2182     StructConstantsTy::MapTy::iterator I =
2183       StructConstants->InsertOrGetItem(Lookup, Exists);
2184     
2185     if (Exists) {
2186       Replacement = I->second;
2187     } else {
2188       // Okay, the new shape doesn't exist in the system yet.  Instead of
2189       // creating a new constant struct, inserting it, replaceallusesof'ing the
2190       // old with the new, then deleting the old... just update the current one
2191       // in place!
2192       StructConstants->MoveConstantToNewSlot(this, I);
2193       
2194       // Update to the new value.
2195       setOperand(OperandToUpdate, ToC);
2196       return;
2197     }
2198   }
2199   
2200   assert(Replacement != this && "I didn't contain From!");
2201   
2202   // Everyone using this now uses the replacement.
2203   uncheckedReplaceAllUsesWith(Replacement);
2204   
2205   // Delete the old constant!
2206   destroyConstant();
2207 }
2208
2209 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2210                                                  Use *U) {
2211   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2212   
2213   std::vector<Constant*> Values;
2214   Values.reserve(getNumOperands());  // Build replacement array...
2215   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2216     Constant *Val = getOperand(i);
2217     if (Val == From) Val = cast<Constant>(To);
2218     Values.push_back(Val);
2219   }
2220   
2221   Constant *Replacement = ConstantVector::get(getType(), Values);
2222   assert(Replacement != this && "I didn't contain From!");
2223   
2224   // Everyone using this now uses the replacement.
2225   uncheckedReplaceAllUsesWith(Replacement);
2226   
2227   // Delete the old constant!
2228   destroyConstant();
2229 }
2230
2231 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2232                                                Use *U) {
2233   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2234   Constant *To = cast<Constant>(ToV);
2235   
2236   Constant *Replacement = 0;
2237   if (getOpcode() == Instruction::GetElementPtr) {
2238     SmallVector<Constant*, 8> Indices;
2239     Constant *Pointer = getOperand(0);
2240     Indices.reserve(getNumOperands()-1);
2241     if (Pointer == From) Pointer = To;
2242     
2243     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2244       Constant *Val = getOperand(i);
2245       if (Val == From) Val = To;
2246       Indices.push_back(Val);
2247     }
2248     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2249                                                  &Indices[0], Indices.size());
2250   } else if (isCast()) {
2251     assert(getOperand(0) == From && "Cast only has one use!");
2252     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2253   } else if (getOpcode() == Instruction::Select) {
2254     Constant *C1 = getOperand(0);
2255     Constant *C2 = getOperand(1);
2256     Constant *C3 = getOperand(2);
2257     if (C1 == From) C1 = To;
2258     if (C2 == From) C2 = To;
2259     if (C3 == From) C3 = To;
2260     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2261   } else if (getOpcode() == Instruction::ExtractElement) {
2262     Constant *C1 = getOperand(0);
2263     Constant *C2 = getOperand(1);
2264     if (C1 == From) C1 = To;
2265     if (C2 == From) C2 = To;
2266     Replacement = ConstantExpr::getExtractElement(C1, C2);
2267   } else if (getOpcode() == Instruction::InsertElement) {
2268     Constant *C1 = getOperand(0);
2269     Constant *C2 = getOperand(1);
2270     Constant *C3 = getOperand(1);
2271     if (C1 == From) C1 = To;
2272     if (C2 == From) C2 = To;
2273     if (C3 == From) C3 = To;
2274     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2275   } else if (getOpcode() == Instruction::ShuffleVector) {
2276     Constant *C1 = getOperand(0);
2277     Constant *C2 = getOperand(1);
2278     Constant *C3 = getOperand(2);
2279     if (C1 == From) C1 = To;
2280     if (C2 == From) C2 = To;
2281     if (C3 == From) C3 = To;
2282     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2283   } else if (isCompare()) {
2284     Constant *C1 = getOperand(0);
2285     Constant *C2 = getOperand(1);
2286     if (C1 == From) C1 = To;
2287     if (C2 == From) C2 = To;
2288     if (getOpcode() == Instruction::ICmp)
2289       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2290     else
2291       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2292   } else if (getNumOperands() == 2) {
2293     Constant *C1 = getOperand(0);
2294     Constant *C2 = getOperand(1);
2295     if (C1 == From) C1 = To;
2296     if (C2 == From) C2 = To;
2297     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2298   } else {
2299     assert(0 && "Unknown ConstantExpr type!");
2300     return;
2301   }
2302   
2303   assert(Replacement != this && "I didn't contain From!");
2304   
2305   // Everyone using this now uses the replacement.
2306   uncheckedReplaceAllUsesWith(Replacement);
2307   
2308   // Delete the old constant!
2309   destroyConstant();
2310 }
2311
2312
2313 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
2314 /// global into a string value.  Return an empty string if we can't do it.
2315 /// Parameter Chop determines if the result is chopped at the first null
2316 /// terminator.
2317 ///
2318 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
2319   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
2320     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
2321       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
2322       if (Init->isString()) {
2323         std::string Result = Init->getAsString();
2324         if (Offset < Result.size()) {
2325           // If we are pointing INTO The string, erase the beginning...
2326           Result.erase(Result.begin(), Result.begin()+Offset);
2327
2328           // Take off the null terminator, and any string fragments after it.
2329           if (Chop) {
2330             std::string::size_type NullPos = Result.find_first_of((char)0);
2331             if (NullPos != std::string::npos)
2332               Result.erase(Result.begin()+NullPos, Result.end());
2333           }
2334           return Result;
2335         }
2336       }
2337     }
2338   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
2339     if (CE->getOpcode() == Instruction::GetElementPtr) {
2340       // Turn a gep into the specified offset.
2341       if (CE->getNumOperands() == 3 &&
2342           cast<Constant>(CE->getOperand(1))->isNullValue() &&
2343           isa<ConstantInt>(CE->getOperand(2))) {
2344         Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
2345         return CE->getOperand(0)->getStringValue(Chop, Offset);
2346       }
2347     }
2348   }
2349   return "";
2350 }