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