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