0f3239baebed75e1fe7e72b810b177b8076dc610
[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/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/System/Mutex.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include <algorithm>
35 #include <map>
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 //                              Constant Class
40 //===----------------------------------------------------------------------===//
41
42 // Becomes a no-op when multithreading is disabled.
43 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
44
45 void Constant::destroyConstantImpl() {
46   // When a Constant is destroyed, there may be lingering
47   // references to the constant by other constants in the constant pool.  These
48   // constants are implicitly dependent on the module that is being deleted,
49   // but they don't know that.  Because we only find out when the CPV is
50   // deleted, we must now notify all of our users (that should only be
51   // Constants) that they are, in fact, invalid now and should be deleted.
52   //
53   while (!use_empty()) {
54     Value *V = use_back();
55 #ifndef NDEBUG      // Only in -g mode...
56     if (!isa<Constant>(V))
57       DOUT << "While deleting: " << *this
58            << "\n\nUse still stuck around after Def is destroyed: "
59            << *V << "\n\n";
60 #endif
61     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
62     Constant *CV = cast<Constant>(V);
63     CV->destroyConstant();
64
65     // The constant should remove itself from our use list...
66     assert((use_empty() || use_back() != V) && "Constant not removed!");
67   }
68
69   // Value has no outstanding references it is safe to delete it now...
70   delete this;
71 }
72
73 /// canTrap - Return true if evaluation of this constant could trap.  This is
74 /// true for things like constant expressions that could divide by zero.
75 bool Constant::canTrap() const {
76   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
77   // The only thing that could possibly trap are constant exprs.
78   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
79   if (!CE) return false;
80   
81   // ConstantExpr traps if any operands can trap. 
82   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
83     if (getOperand(i)->canTrap()) 
84       return true;
85
86   // Otherwise, only specific operations can trap.
87   switch (CE->getOpcode()) {
88   default:
89     return false;
90   case Instruction::UDiv:
91   case Instruction::SDiv:
92   case Instruction::FDiv:
93   case Instruction::URem:
94   case Instruction::SRem:
95   case Instruction::FRem:
96     // Div and rem can trap if the RHS is not known to be non-zero.
97     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
98       return true;
99     return false;
100   }
101 }
102
103 /// ContainsRelocations - Return true if the constant value contains relocations
104 /// which cannot be resolved at compile time. Kind argument is used to filter
105 /// only 'interesting' sorts of relocations.
106 bool Constant::ContainsRelocations(unsigned Kind) const {
107   if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
108     bool isLocal = GV->hasLocalLinkage();
109     if ((Kind & Reloc::Local) && isLocal) {
110       // Global has local linkage and 'local' kind of relocations are
111       // requested
112       return true;
113     }
114
115     if ((Kind & Reloc::Global) && !isLocal) {
116       // Global has non-local linkage and 'global' kind of relocations are
117       // requested
118       return true;
119     }
120
121     return false;
122   }
123
124   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
125     if (getOperand(i)->ContainsRelocations(Kind))
126       return true;
127
128   return false;
129 }
130
131 // Static constructor to create a '0' constant of arbitrary type...
132 static const uint64_t zero[2] = {0, 0};
133 Constant *Constant::getNullValue(const Type *Ty) {
134   switch (Ty->getTypeID()) {
135   case Type::IntegerTyID:
136     return ConstantInt::get(Ty, 0);
137   case Type::FloatTyID:
138     return ConstantFP::get(APFloat(APInt(32, 0)));
139   case Type::DoubleTyID:
140     return ConstantFP::get(APFloat(APInt(64, 0)));
141   case Type::X86_FP80TyID:
142     return ConstantFP::get(APFloat(APInt(80, 2, zero)));
143   case Type::FP128TyID:
144     return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
145   case Type::PPC_FP128TyID:
146     return ConstantFP::get(APFloat(APInt(128, 2, zero)));
147   case Type::PointerTyID:
148     return ConstantPointerNull::get(cast<PointerType>(Ty));
149   case Type::StructTyID:
150   case Type::ArrayTyID:
151   case Type::VectorTyID:
152     return ConstantAggregateZero::get(Ty);
153   default:
154     // Function, Label, or Opaque type?
155     assert(!"Cannot create a null constant of that type!");
156     return 0;
157   }
158 }
159
160 Constant *Constant::getAllOnesValue(const Type *Ty) {
161   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
162     return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
163   return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
164 }
165
166 // Static constructor to create an integral constant with all bits set
167 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
168   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
169     return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
170   return 0;
171 }
172
173 /// @returns the value for a vector integer constant of the given type that
174 /// has all its bits set to true.
175 /// @brief Get the all ones value
176 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
177   std::vector<Constant*> Elts;
178   Elts.resize(Ty->getNumElements(),
179               ConstantInt::getAllOnesValue(Ty->getElementType()));
180   assert(Elts[0] && "Not a vector integer type!");
181   return cast<ConstantVector>(ConstantVector::get(Elts));
182 }
183
184
185 /// getVectorElements - This method, which is only valid on constant of vector
186 /// type, returns the elements of the vector in the specified smallvector.
187 /// This handles breaking down a vector undef into undef elements, etc.  For
188 /// constant exprs and other cases we can't handle, we return an empty vector.
189 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
190   assert(isa<VectorType>(getType()) && "Not a vector constant!");
191   
192   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
193     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
194       Elts.push_back(CV->getOperand(i));
195     return;
196   }
197   
198   const VectorType *VT = cast<VectorType>(getType());
199   if (isa<ConstantAggregateZero>(this)) {
200     Elts.assign(VT->getNumElements(), 
201                 Constant::getNullValue(VT->getElementType()));
202     return;
203   }
204   
205   if (isa<UndefValue>(this)) {
206     Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
207     return;
208   }
209   
210   // Unknown type, must be constant expr etc.
211 }
212
213
214
215 //===----------------------------------------------------------------------===//
216 //                                ConstantInt
217 //===----------------------------------------------------------------------===//
218
219 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
220   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
221   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
222 }
223
224 ConstantInt *ConstantInt::TheTrueVal = 0;
225 ConstantInt *ConstantInt::TheFalseVal = 0;
226
227 namespace llvm {
228   void CleanupTrueFalse(void *) {
229     ConstantInt::ResetTrueFalse();
230   }
231 }
232
233 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
234
235 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
236   assert(TheTrueVal == 0 && TheFalseVal == 0);
237   TheTrueVal  = get(Type::Int1Ty, 1);
238   TheFalseVal = get(Type::Int1Ty, 0);
239   
240   // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
241   TrueFalseCleanup.Register();
242   
243   return WhichOne ? TheTrueVal : TheFalseVal;
244 }
245
246
247 namespace {
248   struct DenseMapAPIntKeyInfo {
249     struct KeyTy {
250       APInt val;
251       const Type* type;
252       KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
253       KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
254       bool operator==(const KeyTy& that) const {
255         return type == that.type && this->val == that.val;
256       }
257       bool operator!=(const KeyTy& that) const {
258         return !this->operator==(that);
259       }
260     };
261     static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
262     static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
263     static unsigned getHashValue(const KeyTy &Key) {
264       return DenseMapInfo<void*>::getHashValue(Key.type) ^ 
265         Key.val.getHashValue();
266     }
267     static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
268       return LHS == RHS;
269     }
270     static bool isPod() { return false; }
271   };
272 }
273
274
275 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*, 
276                  DenseMapAPIntKeyInfo> IntMapTy;
277 static ManagedStatic<IntMapTy> IntConstants;
278
279 ConstantInt *ConstantInt::get(const IntegerType *Ty,
280                               uint64_t V, bool isSigned) {
281   return get(APInt(Ty->getBitWidth(), V, isSigned));
282 }
283
284 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
285   Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
286
287   // For vectors, broadcast the value.
288   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
289     return
290       ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
291
292   return C;
293 }
294
295 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
296 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
297 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
298 // compare APInt's of different widths, which would violate an APInt class
299 // invariant which generates an assertion.
300 ConstantInt *ConstantInt::get(const APInt& V) {
301   // Get the corresponding integer type for the bit width of the value.
302   const IntegerType *ITy = IntegerType::get(V.getBitWidth());
303   // get an existing value or the insertion position
304   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
305   
306   ConstantsLock->reader_acquire();
307   ConstantInt *&Slot = (*IntConstants)[Key]; 
308   ConstantsLock->reader_release();
309     
310   if (!Slot) {
311     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
312     ConstantInt *&NewSlot = (*IntConstants)[Key]; 
313     if (!Slot) {
314       NewSlot = new ConstantInt(ITy, V);
315     }
316     
317     return NewSlot;
318   } else {
319     return Slot;
320   }
321 }
322
323 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
324   ConstantInt *C = ConstantInt::get(V);
325   assert(C->getType() == Ty->getScalarType() &&
326          "ConstantInt type doesn't match the type implied by its value!");
327
328   // For vectors, broadcast the value.
329   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
330     return
331       ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
332
333   return C;
334 }
335
336 //===----------------------------------------------------------------------===//
337 //                                ConstantFP
338 //===----------------------------------------------------------------------===//
339
340 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
341   if (Ty == Type::FloatTy)
342     return &APFloat::IEEEsingle;
343   if (Ty == Type::DoubleTy)
344     return &APFloat::IEEEdouble;
345   if (Ty == Type::X86_FP80Ty)
346     return &APFloat::x87DoubleExtended;
347   else if (Ty == Type::FP128Ty)
348     return &APFloat::IEEEquad;
349   
350   assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
351   return &APFloat::PPCDoubleDouble;
352 }
353
354 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
355   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
356   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
357          "FP type Mismatch");
358 }
359
360 bool ConstantFP::isNullValue() const {
361   return Val.isZero() && !Val.isNegative();
362 }
363
364 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
365   APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
366   apf.changeSign();
367   return ConstantFP::get(apf);
368 }
369
370 bool ConstantFP::isExactlyValue(const APFloat& V) const {
371   return Val.bitwiseIsEqual(V);
372 }
373
374 namespace {
375   struct DenseMapAPFloatKeyInfo {
376     struct KeyTy {
377       APFloat val;
378       KeyTy(const APFloat& V) : val(V){}
379       KeyTy(const KeyTy& that) : val(that.val) {}
380       bool operator==(const KeyTy& that) const {
381         return this->val.bitwiseIsEqual(that.val);
382       }
383       bool operator!=(const KeyTy& that) const {
384         return !this->operator==(that);
385       }
386     };
387     static inline KeyTy getEmptyKey() { 
388       return KeyTy(APFloat(APFloat::Bogus,1));
389     }
390     static inline KeyTy getTombstoneKey() { 
391       return KeyTy(APFloat(APFloat::Bogus,2)); 
392     }
393     static unsigned getHashValue(const KeyTy &Key) {
394       return Key.val.getHashValue();
395     }
396     static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
397       return LHS == RHS;
398     }
399     static bool isPod() { return false; }
400   };
401 }
402
403 //---- ConstantFP::get() implementation...
404 //
405 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*, 
406                  DenseMapAPFloatKeyInfo> FPMapTy;
407
408 static ManagedStatic<FPMapTy> FPConstants;
409
410 ConstantFP *ConstantFP::get(const APFloat &V) {
411   DenseMapAPFloatKeyInfo::KeyTy Key(V);
412   
413   ConstantsLock->reader_acquire();
414   ConstantFP *&Slot = (*FPConstants)[Key];
415   ConstantsLock->reader_release();
416     
417   if (!Slot) {
418     sys::SmartScopedWriter<true> Writer(*ConstantsLock);
419     ConstantFP *&NewSlot = (*FPConstants)[Key];
420     if (!NewSlot) {
421       const Type *Ty;
422       if (&V.getSemantics() == &APFloat::IEEEsingle)
423         Ty = Type::FloatTy;
424       else if (&V.getSemantics() == &APFloat::IEEEdouble)
425         Ty = Type::DoubleTy;
426       else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
427         Ty = Type::X86_FP80Ty;
428       else if (&V.getSemantics() == &APFloat::IEEEquad)
429         Ty = Type::FP128Ty;
430       else {
431         assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
432                "Unknown FP format");
433         Ty = Type::PPC_FP128Ty;
434       }
435       NewSlot = new ConstantFP(Ty, V);
436     }
437     
438     return NewSlot;
439   }
440   
441   return Slot;
442 }
443
444 /// get() - This returns a constant fp for the specified value in the
445 /// specified type.  This should only be used for simple constant values like
446 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
447 Constant *ConstantFP::get(const Type *Ty, double V) {
448   APFloat FV(V);
449   bool ignored;
450   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
451              APFloat::rmNearestTiesToEven, &ignored);
452   Constant *C = get(FV);
453
454   // For vectors, broadcast the value.
455   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
456     return
457       ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
458
459   return C;
460 }
461
462 //===----------------------------------------------------------------------===//
463 //                            ConstantXXX Classes
464 //===----------------------------------------------------------------------===//
465
466
467 ConstantArray::ConstantArray(const ArrayType *T,
468                              const std::vector<Constant*> &V)
469   : Constant(T, ConstantArrayVal,
470              OperandTraits<ConstantArray>::op_end(this) - V.size(),
471              V.size()) {
472   assert(V.size() == T->getNumElements() &&
473          "Invalid initializer vector for constant array");
474   Use *OL = OperandList;
475   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
476        I != E; ++I, ++OL) {
477     Constant *C = *I;
478     assert((C->getType() == T->getElementType() ||
479             (T->isAbstract() &&
480              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
481            "Initializer for array element doesn't match array element type!");
482     *OL = C;
483   }
484 }
485
486
487 ConstantStruct::ConstantStruct(const StructType *T,
488                                const std::vector<Constant*> &V)
489   : Constant(T, ConstantStructVal,
490              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
491              V.size()) {
492   assert(V.size() == T->getNumElements() &&
493          "Invalid initializer vector for constant structure");
494   Use *OL = OperandList;
495   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
496        I != E; ++I, ++OL) {
497     Constant *C = *I;
498     assert((C->getType() == T->getElementType(I-V.begin()) ||
499             ((T->getElementType(I-V.begin())->isAbstract() ||
500               C->getType()->isAbstract()) &&
501              T->getElementType(I-V.begin())->getTypeID() == 
502                    C->getType()->getTypeID())) &&
503            "Initializer for struct element doesn't match struct element type!");
504     *OL = C;
505   }
506 }
507
508
509 ConstantVector::ConstantVector(const VectorType *T,
510                                const std::vector<Constant*> &V)
511   : Constant(T, ConstantVectorVal,
512              OperandTraits<ConstantVector>::op_end(this) - V.size(),
513              V.size()) {
514   Use *OL = OperandList;
515     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
516          I != E; ++I, ++OL) {
517       Constant *C = *I;
518       assert((C->getType() == T->getElementType() ||
519             (T->isAbstract() &&
520              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
521            "Initializer for vector element doesn't match vector element type!");
522     *OL = C;
523   }
524 }
525
526
527 namespace llvm {
528 // We declare several classes private to this file, so use an anonymous
529 // namespace
530 namespace {
531
532 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
533 /// behind the scenes to implement unary constant exprs.
534 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
535   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
536 public:
537   // allocate space for exactly one operand
538   void *operator new(size_t s) {
539     return User::operator new(s, 1);
540   }
541   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
542     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
543     Op<0>() = C;
544   }
545   /// Transparently provide more efficient getOperand methods.
546   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
547 };
548
549 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
550 /// behind the scenes to implement binary constant exprs.
551 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
552   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
553 public:
554   // allocate space for exactly two operands
555   void *operator new(size_t s) {
556     return User::operator new(s, 2);
557   }
558   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
559     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
560     Op<0>() = C1;
561     Op<1>() = C2;
562   }
563   /// Transparently provide more efficient getOperand methods.
564   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
565 };
566
567 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
568 /// behind the scenes to implement select constant exprs.
569 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
570   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
571 public:
572   // allocate space for exactly three operands
573   void *operator new(size_t s) {
574     return User::operator new(s, 3);
575   }
576   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
577     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
578     Op<0>() = C1;
579     Op<1>() = C2;
580     Op<2>() = C3;
581   }
582   /// Transparently provide more efficient getOperand methods.
583   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
584 };
585
586 /// ExtractElementConstantExpr - This class is private to
587 /// Constants.cpp, and is used behind the scenes to implement
588 /// extractelement constant exprs.
589 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
590   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
591 public:
592   // allocate space for exactly two operands
593   void *operator new(size_t s) {
594     return User::operator new(s, 2);
595   }
596   ExtractElementConstantExpr(Constant *C1, Constant *C2)
597     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
598                    Instruction::ExtractElement, &Op<0>(), 2) {
599     Op<0>() = C1;
600     Op<1>() = C2;
601   }
602   /// Transparently provide more efficient getOperand methods.
603   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
604 };
605
606 /// InsertElementConstantExpr - This class is private to
607 /// Constants.cpp, and is used behind the scenes to implement
608 /// insertelement constant exprs.
609 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
610   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
611 public:
612   // allocate space for exactly three operands
613   void *operator new(size_t s) {
614     return User::operator new(s, 3);
615   }
616   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
617     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
618                    &Op<0>(), 3) {
619     Op<0>() = C1;
620     Op<1>() = C2;
621     Op<2>() = C3;
622   }
623   /// Transparently provide more efficient getOperand methods.
624   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
625 };
626
627 /// ShuffleVectorConstantExpr - This class is private to
628 /// Constants.cpp, and is used behind the scenes to implement
629 /// shufflevector constant exprs.
630 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
631   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
632 public:
633   // allocate space for exactly three operands
634   void *operator new(size_t s) {
635     return User::operator new(s, 3);
636   }
637   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
638   : ConstantExpr(VectorType::get(
639                    cast<VectorType>(C1->getType())->getElementType(),
640                    cast<VectorType>(C3->getType())->getNumElements()),
641                  Instruction::ShuffleVector, 
642                  &Op<0>(), 3) {
643     Op<0>() = C1;
644     Op<1>() = C2;
645     Op<2>() = C3;
646   }
647   /// Transparently provide more efficient getOperand methods.
648   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
649 };
650
651 /// ExtractValueConstantExpr - This class is private to
652 /// Constants.cpp, and is used behind the scenes to implement
653 /// extractvalue constant exprs.
654 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
655   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
656 public:
657   // allocate space for exactly one operand
658   void *operator new(size_t s) {
659     return User::operator new(s, 1);
660   }
661   ExtractValueConstantExpr(Constant *Agg,
662                            const SmallVector<unsigned, 4> &IdxList,
663                            const Type *DestTy)
664     : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
665       Indices(IdxList) {
666     Op<0>() = Agg;
667   }
668
669   /// Indices - These identify which value to extract.
670   const SmallVector<unsigned, 4> Indices;
671
672   /// Transparently provide more efficient getOperand methods.
673   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
674 };
675
676 /// InsertValueConstantExpr - This class is private to
677 /// Constants.cpp, and is used behind the scenes to implement
678 /// insertvalue constant exprs.
679 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
680   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
681 public:
682   // allocate space for exactly one operand
683   void *operator new(size_t s) {
684     return User::operator new(s, 2);
685   }
686   InsertValueConstantExpr(Constant *Agg, Constant *Val,
687                           const SmallVector<unsigned, 4> &IdxList,
688                           const Type *DestTy)
689     : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
690       Indices(IdxList) {
691     Op<0>() = Agg;
692     Op<1>() = Val;
693   }
694
695   /// Indices - These identify the position for the insertion.
696   const SmallVector<unsigned, 4> Indices;
697
698   /// Transparently provide more efficient getOperand methods.
699   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
700 };
701
702
703 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
704 /// used behind the scenes to implement getelementpr constant exprs.
705 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
706   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
707                             const Type *DestTy);
708 public:
709   static GetElementPtrConstantExpr *Create(Constant *C,
710                                            const std::vector<Constant*>&IdxList,
711                                            const Type *DestTy) {
712     return new(IdxList.size() + 1)
713       GetElementPtrConstantExpr(C, IdxList, DestTy);
714   }
715   /// Transparently provide more efficient getOperand methods.
716   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
717 };
718
719 // CompareConstantExpr - This class is private to Constants.cpp, and is used
720 // behind the scenes to implement ICmp and FCmp constant expressions. This is
721 // needed in order to store the predicate value for these instructions.
722 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
723   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
724   // allocate space for exactly two operands
725   void *operator new(size_t s) {
726     return User::operator new(s, 2);
727   }
728   unsigned short predicate;
729   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
730                       unsigned short pred,  Constant* LHS, Constant* RHS)
731     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
732     Op<0>() = LHS;
733     Op<1>() = RHS;
734   }
735   /// Transparently provide more efficient getOperand methods.
736   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
737 };
738
739 } // end anonymous namespace
740
741 template <>
742 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
743 };
744 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
745
746 template <>
747 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
748 };
749 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
750
751 template <>
752 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
753 };
754 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
755
756 template <>
757 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
758 };
759 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
760
761 template <>
762 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
763 };
764 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
765
766 template <>
767 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
768 };
769 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
770
771 template <>
772 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
773 };
774 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
775
776 template <>
777 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
778 };
779 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
780
781 template <>
782 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
783 };
784
785 GetElementPtrConstantExpr::GetElementPtrConstantExpr
786   (Constant *C,
787    const std::vector<Constant*> &IdxList,
788    const Type *DestTy)
789     : ConstantExpr(DestTy, Instruction::GetElementPtr,
790                    OperandTraits<GetElementPtrConstantExpr>::op_end(this)
791                    - (IdxList.size()+1),
792                    IdxList.size()+1) {
793   OperandList[0] = C;
794   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
795     OperandList[i+1] = IdxList[i];
796 }
797
798 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
799
800
801 template <>
802 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
803 };
804 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
805
806
807 } // End llvm namespace
808
809
810 // Utility function for determining if a ConstantExpr is a CastOp or not. This
811 // can't be inline because we don't want to #include Instruction.h into
812 // Constant.h
813 bool ConstantExpr::isCast() const {
814   return Instruction::isCast(getOpcode());
815 }
816
817 bool ConstantExpr::isCompare() const {
818   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
819 }
820
821 bool ConstantExpr::hasIndices() const {
822   return getOpcode() == Instruction::ExtractValue ||
823          getOpcode() == Instruction::InsertValue;
824 }
825
826 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
827   if (const ExtractValueConstantExpr *EVCE =
828         dyn_cast<ExtractValueConstantExpr>(this))
829     return EVCE->Indices;
830
831   return cast<InsertValueConstantExpr>(this)->Indices;
832 }
833
834 /// ConstantExpr::get* - Return some common constants without having to
835 /// specify the full Instruction::OPCODE identifier.
836 ///
837 Constant *ConstantExpr::getNeg(Constant *C) {
838   // API compatibility: Adjust integer opcodes to floating-point opcodes.
839   if (C->getType()->isFPOrFPVector())
840     return getFNeg(C);
841   assert(C->getType()->isIntOrIntVector() &&
842          "Cannot NEG a nonintegral value!");
843   return get(Instruction::Sub,
844              ConstantExpr::getZeroValueForNegationExpr(C->getType()),
845              C);
846 }
847 Constant *ConstantExpr::getFNeg(Constant *C) {
848   assert(C->getType()->isFPOrFPVector() &&
849          "Cannot FNEG a non-floating-point value!");
850   return get(Instruction::FSub,
851              ConstantExpr::getZeroValueForNegationExpr(C->getType()),
852              C);
853 }
854 Constant *ConstantExpr::getNot(Constant *C) {
855   assert(C->getType()->isIntOrIntVector() &&
856          "Cannot NOT a nonintegral value!");
857   return get(Instruction::Xor, C,
858              Constant::getAllOnesValue(C->getType()));
859 }
860 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
861   return get(Instruction::Add, C1, C2);
862 }
863 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
864   return get(Instruction::FAdd, C1, C2);
865 }
866 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
867   return get(Instruction::Sub, C1, C2);
868 }
869 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
870   return get(Instruction::FSub, C1, C2);
871 }
872 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
873   return get(Instruction::Mul, C1, C2);
874 }
875 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
876   return get(Instruction::FMul, C1, C2);
877 }
878 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
879   return get(Instruction::UDiv, C1, C2);
880 }
881 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
882   return get(Instruction::SDiv, C1, C2);
883 }
884 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
885   return get(Instruction::FDiv, C1, C2);
886 }
887 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
888   return get(Instruction::URem, C1, C2);
889 }
890 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
891   return get(Instruction::SRem, C1, C2);
892 }
893 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
894   return get(Instruction::FRem, C1, C2);
895 }
896 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
897   return get(Instruction::And, C1, C2);
898 }
899 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
900   return get(Instruction::Or, C1, C2);
901 }
902 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
903   return get(Instruction::Xor, C1, C2);
904 }
905 unsigned ConstantExpr::getPredicate() const {
906   assert(getOpcode() == Instruction::FCmp || 
907          getOpcode() == Instruction::ICmp);
908   return ((const CompareConstantExpr*)this)->predicate;
909 }
910 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
911   return get(Instruction::Shl, C1, C2);
912 }
913 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
914   return get(Instruction::LShr, C1, C2);
915 }
916 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
917   return get(Instruction::AShr, C1, C2);
918 }
919
920 /// getWithOperandReplaced - Return a constant expression identical to this
921 /// one, but with the specified operand set to the specified value.
922 Constant *
923 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
924   assert(OpNo < getNumOperands() && "Operand num is out of range!");
925   assert(Op->getType() == getOperand(OpNo)->getType() &&
926          "Replacing operand with value of different type!");
927   if (getOperand(OpNo) == Op)
928     return const_cast<ConstantExpr*>(this);
929   
930   Constant *Op0, *Op1, *Op2;
931   switch (getOpcode()) {
932   case Instruction::Trunc:
933   case Instruction::ZExt:
934   case Instruction::SExt:
935   case Instruction::FPTrunc:
936   case Instruction::FPExt:
937   case Instruction::UIToFP:
938   case Instruction::SIToFP:
939   case Instruction::FPToUI:
940   case Instruction::FPToSI:
941   case Instruction::PtrToInt:
942   case Instruction::IntToPtr:
943   case Instruction::BitCast:
944     return ConstantExpr::getCast(getOpcode(), Op, getType());
945   case Instruction::Select:
946     Op0 = (OpNo == 0) ? Op : getOperand(0);
947     Op1 = (OpNo == 1) ? Op : getOperand(1);
948     Op2 = (OpNo == 2) ? Op : getOperand(2);
949     return ConstantExpr::getSelect(Op0, Op1, Op2);
950   case Instruction::InsertElement:
951     Op0 = (OpNo == 0) ? Op : getOperand(0);
952     Op1 = (OpNo == 1) ? Op : getOperand(1);
953     Op2 = (OpNo == 2) ? Op : getOperand(2);
954     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
955   case Instruction::ExtractElement:
956     Op0 = (OpNo == 0) ? Op : getOperand(0);
957     Op1 = (OpNo == 1) ? Op : getOperand(1);
958     return ConstantExpr::getExtractElement(Op0, Op1);
959   case Instruction::ShuffleVector:
960     Op0 = (OpNo == 0) ? Op : getOperand(0);
961     Op1 = (OpNo == 1) ? Op : getOperand(1);
962     Op2 = (OpNo == 2) ? Op : getOperand(2);
963     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
964   case Instruction::GetElementPtr: {
965     SmallVector<Constant*, 8> Ops;
966     Ops.resize(getNumOperands()-1);
967     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
968       Ops[i-1] = getOperand(i);
969     if (OpNo == 0)
970       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
971     Ops[OpNo-1] = Op;
972     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
973   }
974   default:
975     assert(getNumOperands() == 2 && "Must be binary operator?");
976     Op0 = (OpNo == 0) ? Op : getOperand(0);
977     Op1 = (OpNo == 1) ? Op : getOperand(1);
978     return ConstantExpr::get(getOpcode(), Op0, Op1);
979   }
980 }
981
982 /// getWithOperands - This returns the current constant expression with the
983 /// operands replaced with the specified values.  The specified operands must
984 /// match count and type with the existing ones.
985 Constant *ConstantExpr::
986 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
987   assert(NumOps == getNumOperands() && "Operand count mismatch!");
988   bool AnyChange = false;
989   for (unsigned i = 0; i != NumOps; ++i) {
990     assert(Ops[i]->getType() == getOperand(i)->getType() &&
991            "Operand type mismatch!");
992     AnyChange |= Ops[i] != getOperand(i);
993   }
994   if (!AnyChange)  // No operands changed, return self.
995     return const_cast<ConstantExpr*>(this);
996
997   switch (getOpcode()) {
998   case Instruction::Trunc:
999   case Instruction::ZExt:
1000   case Instruction::SExt:
1001   case Instruction::FPTrunc:
1002   case Instruction::FPExt:
1003   case Instruction::UIToFP:
1004   case Instruction::SIToFP:
1005   case Instruction::FPToUI:
1006   case Instruction::FPToSI:
1007   case Instruction::PtrToInt:
1008   case Instruction::IntToPtr:
1009   case Instruction::BitCast:
1010     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
1011   case Instruction::Select:
1012     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1013   case Instruction::InsertElement:
1014     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1015   case Instruction::ExtractElement:
1016     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1017   case Instruction::ShuffleVector:
1018     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1019   case Instruction::GetElementPtr:
1020     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
1021   case Instruction::ICmp:
1022   case Instruction::FCmp:
1023     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1024   default:
1025     assert(getNumOperands() == 2 && "Must be binary operator?");
1026     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
1027   }
1028 }
1029
1030
1031 //===----------------------------------------------------------------------===//
1032 //                      isValueValidForType implementations
1033
1034 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
1035   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1036   if (Ty == Type::Int1Ty)
1037     return Val == 0 || Val == 1;
1038   if (NumBits >= 64)
1039     return true; // always true, has to fit in largest type
1040   uint64_t Max = (1ll << NumBits) - 1;
1041   return Val <= Max;
1042 }
1043
1044 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
1045   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1046   if (Ty == Type::Int1Ty)
1047     return Val == 0 || Val == 1 || Val == -1;
1048   if (NumBits >= 64)
1049     return true; // always true, has to fit in largest type
1050   int64_t Min = -(1ll << (NumBits-1));
1051   int64_t Max = (1ll << (NumBits-1)) - 1;
1052   return (Val >= Min && Val <= Max);
1053 }
1054
1055 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1056   // convert modifies in place, so make a copy.
1057   APFloat Val2 = APFloat(Val);
1058   bool losesInfo;
1059   switch (Ty->getTypeID()) {
1060   default:
1061     return false;         // These can't be represented as floating point!
1062
1063   // FIXME rounding mode needs to be more flexible
1064   case Type::FloatTyID: {
1065     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1066       return true;
1067     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1068     return !losesInfo;
1069   }
1070   case Type::DoubleTyID: {
1071     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1072         &Val2.getSemantics() == &APFloat::IEEEdouble)
1073       return true;
1074     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1075     return !losesInfo;
1076   }
1077   case Type::X86_FP80TyID:
1078     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
1079            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1080            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1081   case Type::FP128TyID:
1082     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
1083            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1084            &Val2.getSemantics() == &APFloat::IEEEquad;
1085   case Type::PPC_FP128TyID:
1086     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
1087            &Val2.getSemantics() == &APFloat::IEEEdouble ||
1088            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1089   }
1090 }
1091
1092 //===----------------------------------------------------------------------===//
1093 //                      Factory Function Implementation
1094
1095
1096 // The number of operands for each ConstantCreator::create method is
1097 // determined by the ConstantTraits template.
1098 // ConstantCreator - A class that is used to create constants by
1099 // ValueMap*.  This class should be partially specialized if there is
1100 // something strange that needs to be done to interface to the ctor for the
1101 // constant.
1102 //
1103 namespace llvm {
1104   template<class ValType>
1105   struct ConstantTraits;
1106
1107   template<typename T, typename Alloc>
1108   struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1109     static unsigned uses(const std::vector<T, Alloc>& v) {
1110       return v.size();
1111     }
1112   };
1113
1114   template<class ConstantClass, class TypeClass, class ValType>
1115   struct VISIBILITY_HIDDEN ConstantCreator {
1116     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1117       return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1118     }
1119   };
1120
1121   template<class ConstantClass, class TypeClass>
1122   struct VISIBILITY_HIDDEN ConvertConstantType {
1123     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1124       LLVM_UNREACHABLE("This type cannot be converted!\n");
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       LLVM_UNREACHABLE("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       LLVM_UNREACHABLE("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: LLVM_UNREACHABLE("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     LLVM_UNREACHABLE("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 }