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