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