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