ec1bf13e5d268203f8684c8efbdaaa69063ba7fd
[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 "LLVMContextImpl.h"
15 #include "llvm/Constants.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/MDNode.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ADT/FoldingSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/System/Mutex.h"
32 #include "llvm/System/RWMutex.h"
33 #include "llvm/System/Threading.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include <algorithm>
37 #include <map>
38 using namespace llvm;
39
40 //===----------------------------------------------------------------------===//
41 //                              Constant Class
42 //===----------------------------------------------------------------------===//
43
44 // Becomes a no-op when multithreading is disabled.
45 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
46
47 void Constant::destroyConstantImpl() {
48   // When a Constant is destroyed, there may be lingering
49   // references to the constant by other constants in the constant pool.  These
50   // constants are implicitly dependent on the module that is being deleted,
51   // but they don't know that.  Because we only find out when the CPV is
52   // deleted, we must now notify all of our users (that should only be
53   // Constants) that they are, in fact, invalid now and should be deleted.
54   //
55   while (!use_empty()) {
56     Value *V = use_back();
57 #ifndef NDEBUG      // Only in -g mode...
58     if (!isa<Constant>(V))
59       DOUT << "While deleting: " << *this
60            << "\n\nUse still stuck around after Def is destroyed: "
61            << *V << "\n\n";
62 #endif
63     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
64     Constant *CV = cast<Constant>(V);
65     CV->destroyConstant();
66
67     // The constant should remove itself from our use list...
68     assert((use_empty() || use_back() != V) && "Constant not removed!");
69   }
70
71   // Value has no outstanding references it is safe to delete it now...
72   delete this;
73 }
74
75 /// canTrap - Return true if evaluation of this constant could trap.  This is
76 /// true for things like constant expressions that could divide by zero.
77 bool Constant::canTrap() const {
78   assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
79   // The only thing that could possibly trap are constant exprs.
80   const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
81   if (!CE) return false;
82   
83   // ConstantExpr traps if any operands can trap. 
84   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
85     if (getOperand(i)->canTrap()) 
86       return true;
87
88   // Otherwise, only specific operations can trap.
89   switch (CE->getOpcode()) {
90   default:
91     return false;
92   case Instruction::UDiv:
93   case Instruction::SDiv:
94   case Instruction::FDiv:
95   case Instruction::URem:
96   case Instruction::SRem:
97   case Instruction::FRem:
98     // Div and rem can trap if the RHS is not known to be non-zero.
99     if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
100       return true;
101     return false;
102   }
103 }
104
105
106 /// getRelocationInfo - This method classifies the entry according to
107 /// whether or not it may generate a relocation entry.  This must be
108 /// conservative, so if it might codegen to a relocatable entry, it should say
109 /// so.  The return values are:
110 /// 
111 ///  NoRelocation: This constant pool entry is guaranteed to never have a
112 ///     relocation applied to it (because it holds a simple constant like
113 ///     '4').
114 ///  LocalRelocation: This entry has relocations, but the entries are
115 ///     guaranteed to be resolvable by the static linker, so the dynamic
116 ///     linker will never see them.
117 ///  GlobalRelocations: This entry may have arbitrary relocations.
118 ///
119 /// FIXME: This really should not be in VMCore.
120 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
121   if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
122     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
123       return LocalRelocation;  // Local to this file/library.
124     return GlobalRelocations;    // Global reference.
125   }
126   
127   PossibleRelocationsTy Result = NoRelocation;
128   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
129     Result = std::max(Result, getOperand(i)->getRelocationInfo());
130   
131   return Result;
132 }
133
134
135 /// getVectorElements - This method, which is only valid on constant of vector
136 /// type, returns the elements of the vector in the specified smallvector.
137 /// This handles breaking down a vector undef into undef elements, etc.  For
138 /// constant exprs and other cases we can't handle, we return an empty vector.
139 void Constant::getVectorElements(LLVMContext &Context,
140                                  SmallVectorImpl<Constant*> &Elts) const {
141   assert(isa<VectorType>(getType()) && "Not a vector constant!");
142   
143   if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
144     for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
145       Elts.push_back(CV->getOperand(i));
146     return;
147   }
148   
149   const VectorType *VT = cast<VectorType>(getType());
150   if (isa<ConstantAggregateZero>(this)) {
151     Elts.assign(VT->getNumElements(), 
152                 Context.getNullValue(VT->getElementType()));
153     return;
154   }
155   
156   if (isa<UndefValue>(this)) {
157     Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
158     return;
159   }
160   
161   // Unknown type, must be constant expr etc.
162 }
163
164
165
166 //===----------------------------------------------------------------------===//
167 //                                ConstantInt
168 //===----------------------------------------------------------------------===//
169
170 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
171   : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
172   assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
173 }
174
175 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap 
176 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
177 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
178 // compare APInt's of different widths, which would violate an APInt class
179 // invariant which generates an assertion.
180 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
181   // Get the corresponding integer type for the bit width of the value.
182   const IntegerType *ITy = Context.getIntegerType(V.getBitWidth());
183   // get an existing value or the insertion position
184   DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
185   
186   Context.pImpl->ConstantsLock.reader_acquire();
187   ConstantInt *&Slot = Context.pImpl->IntConstants[Key]; 
188   Context.pImpl->ConstantsLock.reader_release();
189     
190   if (!Slot) {
191     sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
192     ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key]; 
193     if (!Slot) {
194       NewSlot = new ConstantInt(ITy, V);
195     }
196     
197     return NewSlot;
198   } else {
199     return Slot;
200   }
201 }
202
203 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
204   Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
205                                V, isSigned);
206
207   // For vectors, broadcast the value.
208   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
209     return Ty->getContext().getConstantVector(
210       std::vector<Constant *>(VTy->getNumElements(), C));
211
212   return C;
213 }
214
215 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V, 
216                               bool isSigned) {
217   return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
218 }
219
220 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
221   return get(Ty, V, true);
222 }
223
224 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
225   return get(Ty, V, true);
226 }
227
228 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
229   ConstantInt *C = get(Ty->getContext(), V);
230   assert(C->getType() == Ty->getScalarType() &&
231          "ConstantInt type doesn't match the type implied by its value!");
232
233   // For vectors, broadcast the value.
234   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
235     return Ty->getContext().getConstantVector(
236       std::vector<Constant *>(VTy->getNumElements(), C));
237
238   return C;
239 }
240
241 //===----------------------------------------------------------------------===//
242 //                                ConstantFP
243 //===----------------------------------------------------------------------===//
244
245 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
246   if (Ty == Type::FloatTy)
247     return &APFloat::IEEEsingle;
248   if (Ty == Type::DoubleTy)
249     return &APFloat::IEEEdouble;
250   if (Ty == Type::X86_FP80Ty)
251     return &APFloat::x87DoubleExtended;
252   else if (Ty == Type::FP128Ty)
253     return &APFloat::IEEEquad;
254   
255   assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
256   return &APFloat::PPCDoubleDouble;
257 }
258
259 /// get() - This returns a constant fp for the specified value in the
260 /// specified type.  This should only be used for simple constant values like
261 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
262 Constant* ConstantFP::get(const Type* Ty, double V) {
263   LLVMContext &Context = Ty->getContext();
264   
265   APFloat FV(V);
266   bool ignored;
267   FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
268              APFloat::rmNearestTiesToEven, &ignored);
269   Constant *C = get(Context, FV);
270
271   // For vectors, broadcast the value.
272   if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
273     return Context.getConstantVector(
274       std::vector<Constant *>(VTy->getNumElements(), C));
275
276   return C;
277 }
278
279 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
280   LLVMContext &Context = Ty->getContext();
281   APFloat apf = cast <ConstantFP>(Context.getNullValue(Ty))->getValueAPF();
282   apf.changeSign();
283   return get(Context, apf);
284 }
285
286
287 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
288   LLVMContext &Context = Ty->getContext();
289   if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
290     if (PTy->getElementType()->isFloatingPoint()) {
291       std::vector<Constant*> zeros(PTy->getNumElements(),
292                            getNegativeZero(PTy->getElementType()));
293       return Context.getConstantVector(PTy, zeros);
294     }
295
296   if (Ty->isFloatingPoint()) 
297     return getNegativeZero(Ty);
298
299   return Context.getNullValue(Ty);
300 }
301
302
303 // ConstantFP accessors.
304 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
305   DenseMapAPFloatKeyInfo::KeyTy Key(V);
306   
307   LLVMContextImpl* pImpl = Context.pImpl;
308   
309   pImpl->ConstantsLock.reader_acquire();
310   ConstantFP *&Slot = pImpl->FPConstants[Key];
311   pImpl->ConstantsLock.reader_release();
312     
313   if (!Slot) {
314     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
315     ConstantFP *&NewSlot = pImpl->FPConstants[Key];
316     if (!NewSlot) {
317       const Type *Ty;
318       if (&V.getSemantics() == &APFloat::IEEEsingle)
319         Ty = Type::FloatTy;
320       else if (&V.getSemantics() == &APFloat::IEEEdouble)
321         Ty = Type::DoubleTy;
322       else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
323         Ty = Type::X86_FP80Ty;
324       else if (&V.getSemantics() == &APFloat::IEEEquad)
325         Ty = Type::FP128Ty;
326       else {
327         assert(&V.getSemantics() == &APFloat::PPCDoubleDouble && 
328                "Unknown FP format");
329         Ty = Type::PPC_FP128Ty;
330       }
331       NewSlot = new ConstantFP(Ty, V);
332     }
333     
334     return NewSlot;
335   }
336   
337   return Slot;
338 }
339
340 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
341   : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
342   assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
343          "FP type Mismatch");
344 }
345
346 bool ConstantFP::isNullValue() const {
347   return Val.isZero() && !Val.isNegative();
348 }
349
350 bool ConstantFP::isExactlyValue(const APFloat& V) const {
351   return Val.bitwiseIsEqual(V);
352 }
353
354 //===----------------------------------------------------------------------===//
355 //                            ConstantXXX Classes
356 //===----------------------------------------------------------------------===//
357
358
359 ConstantArray::ConstantArray(const ArrayType *T,
360                              const std::vector<Constant*> &V)
361   : Constant(T, ConstantArrayVal,
362              OperandTraits<ConstantArray>::op_end(this) - V.size(),
363              V.size()) {
364   assert(V.size() == T->getNumElements() &&
365          "Invalid initializer vector for constant array");
366   Use *OL = OperandList;
367   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
368        I != E; ++I, ++OL) {
369     Constant *C = *I;
370     assert((C->getType() == T->getElementType() ||
371             (T->isAbstract() &&
372              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
373            "Initializer for array element doesn't match array element type!");
374     *OL = C;
375   }
376 }
377
378 Constant *ConstantArray::get(const ArrayType *Ty, 
379                              const std::vector<Constant*> &V) {
380   LLVMContextImpl *pImpl = Ty->getContext().pImpl;
381   // If this is an all-zero array, return a ConstantAggregateZero object
382   if (!V.empty()) {
383     Constant *C = V[0];
384     if (!C->isNullValue()) {
385       // Implicitly locked.
386       return pImpl->ArrayConstants.getOrCreate(Ty, V);
387     }
388     for (unsigned i = 1, e = V.size(); i != e; ++i)
389       if (V[i] != C) {
390         // Implicitly locked.
391         return pImpl->ArrayConstants.getOrCreate(Ty, V);
392       }
393   }
394   
395   return Ty->getContext().getConstantAggregateZero(Ty);
396 }
397
398
399 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
400                              unsigned NumVals) {
401   // FIXME: make this the primary ctor method.
402   return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
403 }
404
405 /// ConstantArray::get(const string&) - Return an array that is initialized to
406 /// contain the specified string.  If length is zero then a null terminator is 
407 /// added to the specified string so that it may be used in a natural way. 
408 /// Otherwise, the length parameter specifies how much of the string to use 
409 /// and it won't be null terminated.
410 ///
411 Constant* ConstantArray::get(const StringRef &Str, bool AddNull) {
412   std::vector<Constant*> ElementVals;
413   for (unsigned i = 0; i < Str.size(); ++i)
414     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
415
416   // Add a null terminator to the string...
417   if (AddNull) {
418     ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
419   }
420
421   ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
422   return get(ATy, ElementVals);
423 }
424
425
426
427 ConstantStruct::ConstantStruct(const StructType *T,
428                                const std::vector<Constant*> &V)
429   : Constant(T, ConstantStructVal,
430              OperandTraits<ConstantStruct>::op_end(this) - V.size(),
431              V.size()) {
432   assert(V.size() == T->getNumElements() &&
433          "Invalid initializer vector for constant structure");
434   Use *OL = OperandList;
435   for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
436        I != E; ++I, ++OL) {
437     Constant *C = *I;
438     assert((C->getType() == T->getElementType(I-V.begin()) ||
439             ((T->getElementType(I-V.begin())->isAbstract() ||
440               C->getType()->isAbstract()) &&
441              T->getElementType(I-V.begin())->getTypeID() == 
442                    C->getType()->getTypeID())) &&
443            "Initializer for struct element doesn't match struct element type!");
444     *OL = C;
445   }
446 }
447
448 // ConstantStruct accessors.
449 Constant* ConstantStruct::get(const StructType* T,
450                               const std::vector<Constant*>& V) {
451   LLVMContextImpl* pImpl = T->getContext().pImpl;
452   
453   // Create a ConstantAggregateZero value if all elements are zeros...
454   for (unsigned i = 0, e = V.size(); i != e; ++i)
455     if (!V[i]->isNullValue())
456       // Implicitly locked.
457       return pImpl->StructConstants.getOrCreate(T, V);
458
459   return T->getContext().getConstantAggregateZero(T);
460 }
461
462 Constant* ConstantStruct::get(const std::vector<Constant*>& V, bool packed) {
463   std::vector<const Type*> StructEls;
464   StructEls.reserve(V.size());
465   for (unsigned i = 0, e = V.size(); i != e; ++i)
466     StructEls.push_back(V[i]->getType());
467   return get(StructType::get(StructEls, packed), V);
468 }
469
470 Constant* ConstantStruct::get(Constant* const *Vals, unsigned NumVals,
471                               bool Packed) {
472   // FIXME: make this the primary ctor method.
473   return get(std::vector<Constant*>(Vals, Vals+NumVals), Packed);
474 }
475
476 ConstantVector::ConstantVector(const VectorType *T,
477                                const std::vector<Constant*> &V)
478   : Constant(T, ConstantVectorVal,
479              OperandTraits<ConstantVector>::op_end(this) - V.size(),
480              V.size()) {
481   Use *OL = OperandList;
482     for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
483          I != E; ++I, ++OL) {
484       Constant *C = *I;
485       assert((C->getType() == T->getElementType() ||
486             (T->isAbstract() &&
487              C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
488            "Initializer for vector element doesn't match vector element type!");
489     *OL = C;
490   }
491 }
492
493
494 namespace llvm {
495 // We declare several classes private to this file, so use an anonymous
496 // namespace
497 namespace {
498
499 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
500 /// behind the scenes to implement unary constant exprs.
501 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
502   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
503 public:
504   // allocate space for exactly one operand
505   void *operator new(size_t s) {
506     return User::operator new(s, 1);
507   }
508   UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
509     : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
510     Op<0>() = C;
511   }
512   /// Transparently provide more efficient getOperand methods.
513   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
514 };
515
516 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
517 /// behind the scenes to implement binary constant exprs.
518 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
519   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
520 public:
521   // allocate space for exactly two operands
522   void *operator new(size_t s) {
523     return User::operator new(s, 2);
524   }
525   BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
526     : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
527     Op<0>() = C1;
528     Op<1>() = C2;
529   }
530   /// Transparently provide more efficient getOperand methods.
531   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
532 };
533
534 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
535 /// behind the scenes to implement select constant exprs.
536 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
537   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
538 public:
539   // allocate space for exactly three operands
540   void *operator new(size_t s) {
541     return User::operator new(s, 3);
542   }
543   SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
544     : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
545     Op<0>() = C1;
546     Op<1>() = C2;
547     Op<2>() = C3;
548   }
549   /// Transparently provide more efficient getOperand methods.
550   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
551 };
552
553 /// ExtractElementConstantExpr - This class is private to
554 /// Constants.cpp, and is used behind the scenes to implement
555 /// extractelement constant exprs.
556 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
557   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
558 public:
559   // allocate space for exactly two operands
560   void *operator new(size_t s) {
561     return User::operator new(s, 2);
562   }
563   ExtractElementConstantExpr(Constant *C1, Constant *C2)
564     : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(), 
565                    Instruction::ExtractElement, &Op<0>(), 2) {
566     Op<0>() = C1;
567     Op<1>() = C2;
568   }
569   /// Transparently provide more efficient getOperand methods.
570   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
571 };
572
573 /// InsertElementConstantExpr - This class is private to
574 /// Constants.cpp, and is used behind the scenes to implement
575 /// insertelement constant exprs.
576 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
577   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
578 public:
579   // allocate space for exactly three operands
580   void *operator new(size_t s) {
581     return User::operator new(s, 3);
582   }
583   InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
584     : ConstantExpr(C1->getType(), Instruction::InsertElement, 
585                    &Op<0>(), 3) {
586     Op<0>() = C1;
587     Op<1>() = C2;
588     Op<2>() = C3;
589   }
590   /// Transparently provide more efficient getOperand methods.
591   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
592 };
593
594 /// ShuffleVectorConstantExpr - This class is private to
595 /// Constants.cpp, and is used behind the scenes to implement
596 /// shufflevector constant exprs.
597 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
598   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
599 public:
600   // allocate space for exactly three operands
601   void *operator new(size_t s) {
602     return User::operator new(s, 3);
603   }
604   ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
605   : ConstantExpr(VectorType::get(
606                    cast<VectorType>(C1->getType())->getElementType(),
607                    cast<VectorType>(C3->getType())->getNumElements()),
608                  Instruction::ShuffleVector, 
609                  &Op<0>(), 3) {
610     Op<0>() = C1;
611     Op<1>() = C2;
612     Op<2>() = C3;
613   }
614   /// Transparently provide more efficient getOperand methods.
615   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
616 };
617
618 /// ExtractValueConstantExpr - This class is private to
619 /// Constants.cpp, and is used behind the scenes to implement
620 /// extractvalue constant exprs.
621 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
622   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
623 public:
624   // allocate space for exactly one operand
625   void *operator new(size_t s) {
626     return User::operator new(s, 1);
627   }
628   ExtractValueConstantExpr(Constant *Agg,
629                            const SmallVector<unsigned, 4> &IdxList,
630                            const Type *DestTy)
631     : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
632       Indices(IdxList) {
633     Op<0>() = Agg;
634   }
635
636   /// Indices - These identify which value to extract.
637   const SmallVector<unsigned, 4> Indices;
638
639   /// Transparently provide more efficient getOperand methods.
640   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
641 };
642
643 /// InsertValueConstantExpr - This class is private to
644 /// Constants.cpp, and is used behind the scenes to implement
645 /// insertvalue constant exprs.
646 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
647   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
648 public:
649   // allocate space for exactly one operand
650   void *operator new(size_t s) {
651     return User::operator new(s, 2);
652   }
653   InsertValueConstantExpr(Constant *Agg, Constant *Val,
654                           const SmallVector<unsigned, 4> &IdxList,
655                           const Type *DestTy)
656     : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
657       Indices(IdxList) {
658     Op<0>() = Agg;
659     Op<1>() = Val;
660   }
661
662   /// Indices - These identify the position for the insertion.
663   const SmallVector<unsigned, 4> Indices;
664
665   /// Transparently provide more efficient getOperand methods.
666   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
667 };
668
669
670 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
671 /// used behind the scenes to implement getelementpr constant exprs.
672 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
673   GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
674                             const Type *DestTy);
675 public:
676   static GetElementPtrConstantExpr *Create(Constant *C,
677                                            const std::vector<Constant*>&IdxList,
678                                            const Type *DestTy) {
679     return
680       new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
681   }
682   /// Transparently provide more efficient getOperand methods.
683   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
684 };
685
686 // CompareConstantExpr - This class is private to Constants.cpp, and is used
687 // behind the scenes to implement ICmp and FCmp constant expressions. This is
688 // needed in order to store the predicate value for these instructions.
689 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
690   void *operator new(size_t, unsigned);  // DO NOT IMPLEMENT
691   // allocate space for exactly two operands
692   void *operator new(size_t s) {
693     return User::operator new(s, 2);
694   }
695   unsigned short predicate;
696   CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
697                       unsigned short pred,  Constant* LHS, Constant* RHS)
698     : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
699     Op<0>() = LHS;
700     Op<1>() = RHS;
701   }
702   /// Transparently provide more efficient getOperand methods.
703   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
704 };
705
706 } // end anonymous namespace
707
708 template <>
709 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
710 };
711 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
712
713 template <>
714 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
715 };
716 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
717
718 template <>
719 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
720 };
721 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
722
723 template <>
724 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
725 };
726 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
727
728 template <>
729 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
730 };
731 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
732
733 template <>
734 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
735 };
736 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
737
738 template <>
739 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
740 };
741 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
742
743 template <>
744 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
745 };
746 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
747
748 template <>
749 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
750 };
751
752 GetElementPtrConstantExpr::GetElementPtrConstantExpr
753   (Constant *C,
754    const std::vector<Constant*> &IdxList,
755    const Type *DestTy)
756     : ConstantExpr(DestTy, Instruction::GetElementPtr,
757                    OperandTraits<GetElementPtrConstantExpr>::op_end(this)
758                    - (IdxList.size()+1),
759                    IdxList.size()+1) {
760   OperandList[0] = C;
761   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
762     OperandList[i+1] = IdxList[i];
763 }
764
765 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
766
767
768 template <>
769 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
770 };
771 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
772
773
774 } // End llvm namespace
775
776
777 // Utility function for determining if a ConstantExpr is a CastOp or not. This
778 // can't be inline because we don't want to #include Instruction.h into
779 // Constant.h
780 bool ConstantExpr::isCast() const {
781   return Instruction::isCast(getOpcode());
782 }
783
784 bool ConstantExpr::isCompare() const {
785   return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
786 }
787
788 bool ConstantExpr::hasIndices() const {
789   return getOpcode() == Instruction::ExtractValue ||
790          getOpcode() == Instruction::InsertValue;
791 }
792
793 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
794   if (const ExtractValueConstantExpr *EVCE =
795         dyn_cast<ExtractValueConstantExpr>(this))
796     return EVCE->Indices;
797
798   return cast<InsertValueConstantExpr>(this)->Indices;
799 }
800
801 unsigned ConstantExpr::getPredicate() const {
802   assert(getOpcode() == Instruction::FCmp || 
803          getOpcode() == Instruction::ICmp);
804   return ((const CompareConstantExpr*)this)->predicate;
805 }
806
807 /// getWithOperandReplaced - Return a constant expression identical to this
808 /// one, but with the specified operand set to the specified value.
809 Constant *
810 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
811   assert(OpNo < getNumOperands() && "Operand num is out of range!");
812   assert(Op->getType() == getOperand(OpNo)->getType() &&
813          "Replacing operand with value of different type!");
814   if (getOperand(OpNo) == Op)
815     return const_cast<ConstantExpr*>(this);
816   
817   Constant *Op0, *Op1, *Op2;
818   switch (getOpcode()) {
819   case Instruction::Trunc:
820   case Instruction::ZExt:
821   case Instruction::SExt:
822   case Instruction::FPTrunc:
823   case Instruction::FPExt:
824   case Instruction::UIToFP:
825   case Instruction::SIToFP:
826   case Instruction::FPToUI:
827   case Instruction::FPToSI:
828   case Instruction::PtrToInt:
829   case Instruction::IntToPtr:
830   case Instruction::BitCast:
831     return ConstantExpr::getCast(getOpcode(), Op, getType());
832   case Instruction::Select:
833     Op0 = (OpNo == 0) ? Op : getOperand(0);
834     Op1 = (OpNo == 1) ? Op : getOperand(1);
835     Op2 = (OpNo == 2) ? Op : getOperand(2);
836     return ConstantExpr::getSelect(Op0, Op1, Op2);
837   case Instruction::InsertElement:
838     Op0 = (OpNo == 0) ? Op : getOperand(0);
839     Op1 = (OpNo == 1) ? Op : getOperand(1);
840     Op2 = (OpNo == 2) ? Op : getOperand(2);
841     return ConstantExpr::getInsertElement(Op0, Op1, Op2);
842   case Instruction::ExtractElement:
843     Op0 = (OpNo == 0) ? Op : getOperand(0);
844     Op1 = (OpNo == 1) ? Op : getOperand(1);
845     return ConstantExpr::getExtractElement(Op0, Op1);
846   case Instruction::ShuffleVector:
847     Op0 = (OpNo == 0) ? Op : getOperand(0);
848     Op1 = (OpNo == 1) ? Op : getOperand(1);
849     Op2 = (OpNo == 2) ? Op : getOperand(2);
850     return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
851   case Instruction::GetElementPtr: {
852     SmallVector<Constant*, 8> Ops;
853     Ops.resize(getNumOperands()-1);
854     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
855       Ops[i-1] = getOperand(i);
856     if (OpNo == 0)
857       return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
858     Ops[OpNo-1] = Op;
859     return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
860   }
861   default:
862     assert(getNumOperands() == 2 && "Must be binary operator?");
863     Op0 = (OpNo == 0) ? Op : getOperand(0);
864     Op1 = (OpNo == 1) ? Op : getOperand(1);
865     return ConstantExpr::get(getOpcode(), Op0, Op1);
866   }
867 }
868
869 /// getWithOperands - This returns the current constant expression with the
870 /// operands replaced with the specified values.  The specified operands must
871 /// match count and type with the existing ones.
872 Constant *ConstantExpr::
873 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
874   assert(NumOps == getNumOperands() && "Operand count mismatch!");
875   bool AnyChange = false;
876   for (unsigned i = 0; i != NumOps; ++i) {
877     assert(Ops[i]->getType() == getOperand(i)->getType() &&
878            "Operand type mismatch!");
879     AnyChange |= Ops[i] != getOperand(i);
880   }
881   if (!AnyChange)  // No operands changed, return self.
882     return const_cast<ConstantExpr*>(this);
883
884   switch (getOpcode()) {
885   case Instruction::Trunc:
886   case Instruction::ZExt:
887   case Instruction::SExt:
888   case Instruction::FPTrunc:
889   case Instruction::FPExt:
890   case Instruction::UIToFP:
891   case Instruction::SIToFP:
892   case Instruction::FPToUI:
893   case Instruction::FPToSI:
894   case Instruction::PtrToInt:
895   case Instruction::IntToPtr:
896   case Instruction::BitCast:
897     return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
898   case Instruction::Select:
899     return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
900   case Instruction::InsertElement:
901     return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
902   case Instruction::ExtractElement:
903     return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
904   case Instruction::ShuffleVector:
905     return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
906   case Instruction::GetElementPtr:
907     return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
908   case Instruction::ICmp:
909   case Instruction::FCmp:
910     return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
911   default:
912     assert(getNumOperands() == 2 && "Must be binary operator?");
913     return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
914   }
915 }
916
917
918 //===----------------------------------------------------------------------===//
919 //                      isValueValidForType implementations
920
921 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
922   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
923   if (Ty == Type::Int1Ty)
924     return Val == 0 || Val == 1;
925   if (NumBits >= 64)
926     return true; // always true, has to fit in largest type
927   uint64_t Max = (1ll << NumBits) - 1;
928   return Val <= Max;
929 }
930
931 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
932   unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
933   if (Ty == Type::Int1Ty)
934     return Val == 0 || Val == 1 || Val == -1;
935   if (NumBits >= 64)
936     return true; // always true, has to fit in largest type
937   int64_t Min = -(1ll << (NumBits-1));
938   int64_t Max = (1ll << (NumBits-1)) - 1;
939   return (Val >= Min && Val <= Max);
940 }
941
942 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
943   // convert modifies in place, so make a copy.
944   APFloat Val2 = APFloat(Val);
945   bool losesInfo;
946   switch (Ty->getTypeID()) {
947   default:
948     return false;         // These can't be represented as floating point!
949
950   // FIXME rounding mode needs to be more flexible
951   case Type::FloatTyID: {
952     if (&Val2.getSemantics() == &APFloat::IEEEsingle)
953       return true;
954     Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
955     return !losesInfo;
956   }
957   case Type::DoubleTyID: {
958     if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
959         &Val2.getSemantics() == &APFloat::IEEEdouble)
960       return true;
961     Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
962     return !losesInfo;
963   }
964   case Type::X86_FP80TyID:
965     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
966            &Val2.getSemantics() == &APFloat::IEEEdouble ||
967            &Val2.getSemantics() == &APFloat::x87DoubleExtended;
968   case Type::FP128TyID:
969     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
970            &Val2.getSemantics() == &APFloat::IEEEdouble ||
971            &Val2.getSemantics() == &APFloat::IEEEquad;
972   case Type::PPC_FP128TyID:
973     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
974            &Val2.getSemantics() == &APFloat::IEEEdouble ||
975            &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
976   }
977 }
978
979 //===----------------------------------------------------------------------===//
980 //                      Factory Function Implementation
981
982 /// destroyConstant - Remove the constant from the constant table...
983 ///
984 void ConstantAggregateZero::destroyConstant() {
985   // Implicitly locked.
986   getType()->getContext().erase(this);
987   destroyConstantImpl();
988 }
989
990 /// destroyConstant - Remove the constant from the constant table...
991 ///
992 void ConstantArray::destroyConstant() {
993   // Implicitly locked.
994   getType()->getContext().pImpl->ArrayConstants.remove(this);
995   destroyConstantImpl();
996 }
997
998 /// isString - This method returns true if the array is an array of i8, and 
999 /// if the elements of the array are all ConstantInt's.
1000 bool ConstantArray::isString() const {
1001   // Check the element type for i8...
1002   if (getType()->getElementType() != Type::Int8Ty)
1003     return false;
1004   // Check the elements to make sure they are all integers, not constant
1005   // expressions.
1006   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1007     if (!isa<ConstantInt>(getOperand(i)))
1008       return false;
1009   return true;
1010 }
1011
1012 /// isCString - This method returns true if the array is a string (see
1013 /// isString) and it ends in a null byte \\0 and does not contains any other
1014 /// null bytes except its terminator.
1015 bool ConstantArray::isCString() const {
1016   // Check the element type for i8...
1017   if (getType()->getElementType() != Type::Int8Ty)
1018     return false;
1019
1020   // Last element must be a null.
1021   if (!getOperand(getNumOperands()-1)->isNullValue())
1022     return false;
1023   // Other elements must be non-null integers.
1024   for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1025     if (!isa<ConstantInt>(getOperand(i)))
1026       return false;
1027     if (getOperand(i)->isNullValue())
1028       return false;
1029   }
1030   return true;
1031 }
1032
1033
1034 /// getAsString - If the sub-element type of this array is i8
1035 /// then this method converts the array to an std::string and returns it.
1036 /// Otherwise, it asserts out.
1037 ///
1038 std::string ConstantArray::getAsString() const {
1039   assert(isString() && "Not a string!");
1040   std::string Result;
1041   Result.reserve(getNumOperands());
1042   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1043     Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1044   return Result;
1045 }
1046
1047
1048 //---- ConstantStruct::get() implementation...
1049 //
1050
1051 namespace llvm {
1052
1053 }
1054
1055 // destroyConstant - Remove the constant from the constant table...
1056 //
1057 void ConstantStruct::destroyConstant() {
1058   // Implicitly locked.
1059   getType()->getContext().pImpl->StructConstants.remove(this);
1060   destroyConstantImpl();
1061 }
1062
1063 // destroyConstant - Remove the constant from the constant table...
1064 //
1065 void ConstantVector::destroyConstant() {
1066   // Implicitly locked.
1067   getType()->getContext().erase(this);
1068   destroyConstantImpl();
1069 }
1070
1071 /// This function will return true iff every element in this vector constant
1072 /// is set to all ones.
1073 /// @returns true iff this constant's emements are all set to all ones.
1074 /// @brief Determine if the value is all ones.
1075 bool ConstantVector::isAllOnesValue() const {
1076   // Check out first element.
1077   const Constant *Elt = getOperand(0);
1078   const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1079   if (!CI || !CI->isAllOnesValue()) return false;
1080   // Then make sure all remaining elements point to the same value.
1081   for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1082     if (getOperand(I) != Elt) return false;
1083   }
1084   return true;
1085 }
1086
1087 /// getSplatValue - If this is a splat constant, where all of the
1088 /// elements have the same value, return that value. Otherwise return null.
1089 Constant *ConstantVector::getSplatValue() {
1090   // Check out first element.
1091   Constant *Elt = getOperand(0);
1092   // Then make sure all remaining elements point to the same value.
1093   for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1094     if (getOperand(I) != Elt) return 0;
1095   return Elt;
1096 }
1097
1098 //---- ConstantPointerNull::get() implementation...
1099 //
1100
1101 namespace llvm {
1102   // ConstantPointerNull does not take extra "value" argument...
1103   template<class ValType>
1104   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1105     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1106       return new ConstantPointerNull(Ty);
1107     }
1108   };
1109
1110   template<>
1111   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1112     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1113       // Make everyone now use a constant of the new type...
1114       Constant *New = ConstantPointerNull::get(NewTy);
1115       assert(New != OldC && "Didn't replace constant??");
1116       OldC->uncheckedReplaceAllUsesWith(New);
1117       OldC->destroyConstant();     // This constant is now dead, destroy it.
1118     }
1119   };
1120 }
1121
1122 static ManagedStatic<ValueMap<char, PointerType, 
1123                               ConstantPointerNull> > NullPtrConstants;
1124
1125 static char getValType(ConstantPointerNull *) {
1126   return 0;
1127 }
1128
1129
1130 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1131   // Implicitly locked.
1132   return NullPtrConstants->getOrCreate(Ty, 0);
1133 }
1134
1135 // destroyConstant - Remove the constant from the constant table...
1136 //
1137 void ConstantPointerNull::destroyConstant() {
1138   // Implicitly locked.
1139   NullPtrConstants->remove(this);
1140   destroyConstantImpl();
1141 }
1142
1143
1144 //---- UndefValue::get() implementation...
1145 //
1146
1147 namespace llvm {
1148   // UndefValue does not take extra "value" argument...
1149   template<class ValType>
1150   struct ConstantCreator<UndefValue, Type, ValType> {
1151     static UndefValue *create(const Type *Ty, const ValType &V) {
1152       return new UndefValue(Ty);
1153     }
1154   };
1155
1156   template<>
1157   struct ConvertConstantType<UndefValue, Type> {
1158     static void convert(UndefValue *OldC, const Type *NewTy) {
1159       // Make everyone now use a constant of the new type.
1160       Constant *New = UndefValue::get(NewTy);
1161       assert(New != OldC && "Didn't replace constant??");
1162       OldC->uncheckedReplaceAllUsesWith(New);
1163       OldC->destroyConstant();     // This constant is now dead, destroy it.
1164     }
1165   };
1166 }
1167
1168 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1169
1170 static char getValType(UndefValue *) {
1171   return 0;
1172 }
1173
1174
1175 UndefValue *UndefValue::get(const Type *Ty) {
1176   // Implicitly locked.
1177   return UndefValueConstants->getOrCreate(Ty, 0);
1178 }
1179
1180 // destroyConstant - Remove the constant from the constant table.
1181 //
1182 void UndefValue::destroyConstant() {
1183   // Implicitly locked.
1184   UndefValueConstants->remove(this);
1185   destroyConstantImpl();
1186 }
1187
1188 //---- MDNode::get() implementation
1189 //
1190
1191 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1192   : MetadataBase(Type::MetadataTy, Value::MDNodeVal) {
1193   for (unsigned i = 0; i != NumVals; ++i)
1194     Node.push_back(WeakVH(Vals[i]));
1195 }
1196
1197 void MDNode::Profile(FoldingSetNodeID &ID) const {
1198   for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1199     ID.AddPointer(*I);
1200 }
1201
1202 //---- ConstantExpr::get() implementations...
1203 //
1204
1205 namespace {
1206
1207 struct ExprMapKeyType {
1208   typedef SmallVector<unsigned, 4> IndexList;
1209
1210   ExprMapKeyType(unsigned opc,
1211       const std::vector<Constant*> &ops,
1212       unsigned short pred = 0,
1213       const IndexList &inds = IndexList())
1214         : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1215   uint16_t opcode;
1216   uint16_t predicate;
1217   std::vector<Constant*> operands;
1218   IndexList indices;
1219   bool operator==(const ExprMapKeyType& that) const {
1220     return this->opcode == that.opcode &&
1221            this->predicate == that.predicate &&
1222            this->operands == that.operands &&
1223            this->indices == that.indices;
1224   }
1225   bool operator<(const ExprMapKeyType & that) const {
1226     return this->opcode < that.opcode ||
1227       (this->opcode == that.opcode && this->predicate < that.predicate) ||
1228       (this->opcode == that.opcode && this->predicate == that.predicate &&
1229        this->operands < that.operands) ||
1230       (this->opcode == that.opcode && this->predicate == that.predicate &&
1231        this->operands == that.operands && this->indices < that.indices);
1232   }
1233
1234   bool operator!=(const ExprMapKeyType& that) const {
1235     return !(*this == that);
1236   }
1237 };
1238
1239 }
1240
1241 namespace llvm {
1242   template<>
1243   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1244     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1245         unsigned short pred = 0) {
1246       if (Instruction::isCast(V.opcode))
1247         return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1248       if ((V.opcode >= Instruction::BinaryOpsBegin &&
1249            V.opcode < Instruction::BinaryOpsEnd))
1250         return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1251       if (V.opcode == Instruction::Select)
1252         return new SelectConstantExpr(V.operands[0], V.operands[1], 
1253                                       V.operands[2]);
1254       if (V.opcode == Instruction::ExtractElement)
1255         return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1256       if (V.opcode == Instruction::InsertElement)
1257         return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1258                                              V.operands[2]);
1259       if (V.opcode == Instruction::ShuffleVector)
1260         return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1261                                              V.operands[2]);
1262       if (V.opcode == Instruction::InsertValue)
1263         return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1264                                            V.indices, Ty);
1265       if (V.opcode == Instruction::ExtractValue)
1266         return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1267       if (V.opcode == Instruction::GetElementPtr) {
1268         std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1269         return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1270       }
1271
1272       // The compare instructions are weird. We have to encode the predicate
1273       // value and it is combined with the instruction opcode by multiplying
1274       // the opcode by one hundred. We must decode this to get the predicate.
1275       if (V.opcode == Instruction::ICmp)
1276         return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate, 
1277                                        V.operands[0], V.operands[1]);
1278       if (V.opcode == Instruction::FCmp) 
1279         return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate, 
1280                                        V.operands[0], V.operands[1]);
1281       llvm_unreachable("Invalid ConstantExpr!");
1282       return 0;
1283     }
1284   };
1285
1286   template<>
1287   struct ConvertConstantType<ConstantExpr, Type> {
1288     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1289       Constant *New;
1290       switch (OldC->getOpcode()) {
1291       case Instruction::Trunc:
1292       case Instruction::ZExt:
1293       case Instruction::SExt:
1294       case Instruction::FPTrunc:
1295       case Instruction::FPExt:
1296       case Instruction::UIToFP:
1297       case Instruction::SIToFP:
1298       case Instruction::FPToUI:
1299       case Instruction::FPToSI:
1300       case Instruction::PtrToInt:
1301       case Instruction::IntToPtr:
1302       case Instruction::BitCast:
1303         New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0), 
1304                                     NewTy);
1305         break;
1306       case Instruction::Select:
1307         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1308                                         OldC->getOperand(1),
1309                                         OldC->getOperand(2));
1310         break;
1311       default:
1312         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1313                OldC->getOpcode() <  Instruction::BinaryOpsEnd);
1314         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1315                                   OldC->getOperand(1));
1316         break;
1317       case Instruction::GetElementPtr:
1318         // Make everyone now use a constant of the new type...
1319         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1320         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1321                                                &Idx[0], Idx.size());
1322         break;
1323       }
1324
1325       assert(New != OldC && "Didn't replace constant??");
1326       OldC->uncheckedReplaceAllUsesWith(New);
1327       OldC->destroyConstant();    // This constant is now dead, destroy it.
1328     }
1329   };
1330 } // end namespace llvm
1331
1332
1333 static ExprMapKeyType getValType(ConstantExpr *CE) {
1334   std::vector<Constant*> Operands;
1335   Operands.reserve(CE->getNumOperands());
1336   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1337     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1338   return ExprMapKeyType(CE->getOpcode(), Operands, 
1339       CE->isCompare() ? CE->getPredicate() : 0,
1340       CE->hasIndices() ?
1341         CE->getIndices() : SmallVector<unsigned, 4>());
1342 }
1343
1344 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1345                               ConstantExpr> > ExprConstants;
1346
1347 /// This is a utility function to handle folding of casts and lookup of the
1348 /// cast in the ExprConstants map. It is used by the various get* methods below.
1349 static inline Constant *getFoldedCast(
1350   Instruction::CastOps opc, Constant *C, const Type *Ty) {
1351   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1352   // Fold a few common cases
1353   if (Constant *FC = 
1354                     ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1355     return FC;
1356
1357   // Look up the constant in the table first to ensure uniqueness
1358   std::vector<Constant*> argVec(1, C);
1359   ExprMapKeyType Key(opc, argVec);
1360   
1361   // Implicitly locked.
1362   return ExprConstants->getOrCreate(Ty, Key);
1363 }
1364  
1365 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1366   Instruction::CastOps opc = Instruction::CastOps(oc);
1367   assert(Instruction::isCast(opc) && "opcode out of range");
1368   assert(C && Ty && "Null arguments to getCast");
1369   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1370
1371   switch (opc) {
1372     default:
1373       llvm_unreachable("Invalid cast opcode");
1374       break;
1375     case Instruction::Trunc:    return getTrunc(C, Ty);
1376     case Instruction::ZExt:     return getZExt(C, Ty);
1377     case Instruction::SExt:     return getSExt(C, Ty);
1378     case Instruction::FPTrunc:  return getFPTrunc(C, Ty);
1379     case Instruction::FPExt:    return getFPExtend(C, Ty);
1380     case Instruction::UIToFP:   return getUIToFP(C, Ty);
1381     case Instruction::SIToFP:   return getSIToFP(C, Ty);
1382     case Instruction::FPToUI:   return getFPToUI(C, Ty);
1383     case Instruction::FPToSI:   return getFPToSI(C, Ty);
1384     case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1385     case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1386     case Instruction::BitCast:  return getBitCast(C, Ty);
1387   }
1388   return 0;
1389
1390
1391 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1392   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1393     return getCast(Instruction::BitCast, C, Ty);
1394   return getCast(Instruction::ZExt, C, Ty);
1395 }
1396
1397 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1398   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1399     return getCast(Instruction::BitCast, C, Ty);
1400   return getCast(Instruction::SExt, C, Ty);
1401 }
1402
1403 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1404   if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1405     return getCast(Instruction::BitCast, C, Ty);
1406   return getCast(Instruction::Trunc, C, Ty);
1407 }
1408
1409 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1410   assert(isa<PointerType>(S->getType()) && "Invalid cast");
1411   assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1412
1413   if (Ty->isInteger())
1414     return getCast(Instruction::PtrToInt, S, Ty);
1415   return getCast(Instruction::BitCast, S, Ty);
1416 }
1417
1418 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty, 
1419                                        bool isSigned) {
1420   assert(C->getType()->isIntOrIntVector() &&
1421          Ty->isIntOrIntVector() && "Invalid cast");
1422   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1423   unsigned DstBits = Ty->getScalarSizeInBits();
1424   Instruction::CastOps opcode =
1425     (SrcBits == DstBits ? Instruction::BitCast :
1426      (SrcBits > DstBits ? Instruction::Trunc :
1427       (isSigned ? Instruction::SExt : Instruction::ZExt)));
1428   return getCast(opcode, C, Ty);
1429 }
1430
1431 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1432   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1433          "Invalid cast");
1434   unsigned SrcBits = C->getType()->getScalarSizeInBits();
1435   unsigned DstBits = Ty->getScalarSizeInBits();
1436   if (SrcBits == DstBits)
1437     return C; // Avoid a useless cast
1438   Instruction::CastOps opcode =
1439      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1440   return getCast(opcode, C, Ty);
1441 }
1442
1443 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1444 #ifndef NDEBUG
1445   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1446   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1447 #endif
1448   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1449   assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1450   assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1451   assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1452          "SrcTy must be larger than DestTy for Trunc!");
1453
1454   return getFoldedCast(Instruction::Trunc, C, Ty);
1455 }
1456
1457 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1458 #ifndef NDEBUG
1459   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1460   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1461 #endif
1462   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1463   assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1464   assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1465   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1466          "SrcTy must be smaller than DestTy for SExt!");
1467
1468   return getFoldedCast(Instruction::SExt, C, Ty);
1469 }
1470
1471 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1472 #ifndef NDEBUG
1473   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1474   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1475 #endif
1476   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1477   assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1478   assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1479   assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1480          "SrcTy must be smaller than DestTy for ZExt!");
1481
1482   return getFoldedCast(Instruction::ZExt, C, Ty);
1483 }
1484
1485 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1486 #ifndef NDEBUG
1487   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1488   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1489 #endif
1490   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1491   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1492          C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1493          "This is an illegal floating point truncation!");
1494   return getFoldedCast(Instruction::FPTrunc, C, Ty);
1495 }
1496
1497 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1498 #ifndef NDEBUG
1499   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1500   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1501 #endif
1502   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1503   assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1504          C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1505          "This is an illegal floating point extension!");
1506   return getFoldedCast(Instruction::FPExt, C, Ty);
1507 }
1508
1509 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1510 #ifndef NDEBUG
1511   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1512   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1513 #endif
1514   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1515   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1516          "This is an illegal uint to floating point cast!");
1517   return getFoldedCast(Instruction::UIToFP, C, Ty);
1518 }
1519
1520 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1521 #ifndef NDEBUG
1522   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1523   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1524 #endif
1525   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1526   assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1527          "This is an illegal sint to floating point cast!");
1528   return getFoldedCast(Instruction::SIToFP, C, Ty);
1529 }
1530
1531 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1532 #ifndef NDEBUG
1533   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1534   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1535 #endif
1536   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1537   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1538          "This is an illegal floating point to uint cast!");
1539   return getFoldedCast(Instruction::FPToUI, C, Ty);
1540 }
1541
1542 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1543 #ifndef NDEBUG
1544   bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1545   bool toVec = Ty->getTypeID() == Type::VectorTyID;
1546 #endif
1547   assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1548   assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1549          "This is an illegal floating point to sint cast!");
1550   return getFoldedCast(Instruction::FPToSI, C, Ty);
1551 }
1552
1553 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1554   assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1555   assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1556   return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1557 }
1558
1559 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1560   assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1561   assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1562   return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1563 }
1564
1565 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1566   // BitCast implies a no-op cast of type only. No bits change.  However, you 
1567   // can't cast pointers to anything but pointers.
1568 #ifndef NDEBUG
1569   const Type *SrcTy = C->getType();
1570   assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1571          "BitCast cannot cast pointer to non-pointer and vice versa");
1572
1573   // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1574   // or nonptr->ptr). For all the other types, the cast is okay if source and 
1575   // destination bit widths are identical.
1576   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1577   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1578 #endif
1579   assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1580   
1581   // It is common to ask for a bitcast of a value to its own type, handle this
1582   // speedily.
1583   if (C->getType() == DstTy) return C;
1584   
1585   return getFoldedCast(Instruction::BitCast, C, DstTy);
1586 }
1587
1588 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1589                               Constant *C1, Constant *C2) {
1590   // Check the operands for consistency first
1591   assert(Opcode >= Instruction::BinaryOpsBegin &&
1592          Opcode <  Instruction::BinaryOpsEnd   &&
1593          "Invalid opcode in binary constant expression");
1594   assert(C1->getType() == C2->getType() &&
1595          "Operand types in binary constant expression should match");
1596
1597   if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1598     if (Constant *FC = ConstantFoldBinaryInstruction(
1599                                             getGlobalContext(), Opcode, C1, C2))
1600       return FC;          // Fold a few common cases...
1601
1602   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1603   ExprMapKeyType Key(Opcode, argVec);
1604   
1605   // Implicitly locked.
1606   return ExprConstants->getOrCreate(ReqTy, Key);
1607 }
1608
1609 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1610                                      Constant *C1, Constant *C2) {
1611   switch (predicate) {
1612     default: llvm_unreachable("Invalid CmpInst predicate");
1613     case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1614     case CmpInst::FCMP_OGE:   case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1615     case CmpInst::FCMP_ONE:   case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1616     case CmpInst::FCMP_UEQ:   case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1617     case CmpInst::FCMP_ULT:   case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1618     case CmpInst::FCMP_TRUE:
1619       return getFCmp(predicate, C1, C2);
1620
1621     case CmpInst::ICMP_EQ:  case CmpInst::ICMP_NE:  case CmpInst::ICMP_UGT:
1622     case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1623     case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1624     case CmpInst::ICMP_SLE:
1625       return getICmp(predicate, C1, C2);
1626   }
1627 }
1628
1629 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1630   // API compatibility: Adjust integer opcodes to floating-point opcodes.
1631   if (C1->getType()->isFPOrFPVector()) {
1632     if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1633     else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1634     else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1635   }
1636 #ifndef NDEBUG
1637   switch (Opcode) {
1638   case Instruction::Add:
1639   case Instruction::Sub:
1640   case Instruction::Mul:
1641     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1642     assert(C1->getType()->isIntOrIntVector() &&
1643            "Tried to create an integer operation on a non-integer type!");
1644     break;
1645   case Instruction::FAdd:
1646   case Instruction::FSub:
1647   case Instruction::FMul:
1648     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1649     assert(C1->getType()->isFPOrFPVector() &&
1650            "Tried to create a floating-point operation on a "
1651            "non-floating-point type!");
1652     break;
1653   case Instruction::UDiv: 
1654   case Instruction::SDiv: 
1655     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1656     assert(C1->getType()->isIntOrIntVector() &&
1657            "Tried to create an arithmetic operation on a non-arithmetic type!");
1658     break;
1659   case Instruction::FDiv:
1660     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1661     assert(C1->getType()->isFPOrFPVector() &&
1662            "Tried to create an arithmetic operation on a non-arithmetic type!");
1663     break;
1664   case Instruction::URem: 
1665   case Instruction::SRem: 
1666     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1667     assert(C1->getType()->isIntOrIntVector() &&
1668            "Tried to create an arithmetic operation on a non-arithmetic type!");
1669     break;
1670   case Instruction::FRem:
1671     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1672     assert(C1->getType()->isFPOrFPVector() &&
1673            "Tried to create an arithmetic operation on a non-arithmetic type!");
1674     break;
1675   case Instruction::And:
1676   case Instruction::Or:
1677   case Instruction::Xor:
1678     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1679     assert(C1->getType()->isIntOrIntVector() &&
1680            "Tried to create a logical operation on a non-integral type!");
1681     break;
1682   case Instruction::Shl:
1683   case Instruction::LShr:
1684   case Instruction::AShr:
1685     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1686     assert(C1->getType()->isIntOrIntVector() &&
1687            "Tried to create a shift operation on a non-integer type!");
1688     break;
1689   default:
1690     break;
1691   }
1692 #endif
1693
1694   return getTy(C1->getType(), Opcode, C1, C2);
1695 }
1696
1697 Constant *ConstantExpr::getCompare(unsigned short pred, 
1698                             Constant *C1, Constant *C2) {
1699   assert(C1->getType() == C2->getType() && "Op types should be identical!");
1700   return getCompareTy(pred, C1, C2);
1701 }
1702
1703 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1704                                     Constant *V1, Constant *V2) {
1705   assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1706
1707   if (ReqTy == V1->getType())
1708     if (Constant *SC = ConstantFoldSelectInstruction(
1709                                                 getGlobalContext(), C, V1, V2))
1710       return SC;        // Fold common cases
1711
1712   std::vector<Constant*> argVec(3, C);
1713   argVec[1] = V1;
1714   argVec[2] = V2;
1715   ExprMapKeyType Key(Instruction::Select, argVec);
1716   
1717   // Implicitly locked.
1718   return ExprConstants->getOrCreate(ReqTy, Key);
1719 }
1720
1721 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1722                                            Value* const *Idxs,
1723                                            unsigned NumIdx) {
1724   assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1725                                            Idxs+NumIdx) ==
1726          cast<PointerType>(ReqTy)->getElementType() &&
1727          "GEP indices invalid!");
1728
1729   if (Constant *FC = ConstantFoldGetElementPtr(
1730                                getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1731     return FC;          // Fold a few common cases...
1732
1733   assert(isa<PointerType>(C->getType()) &&
1734          "Non-pointer type for constant GetElementPtr expression");
1735   // Look up the constant in the table first to ensure uniqueness
1736   std::vector<Constant*> ArgVec;
1737   ArgVec.reserve(NumIdx+1);
1738   ArgVec.push_back(C);
1739   for (unsigned i = 0; i != NumIdx; ++i)
1740     ArgVec.push_back(cast<Constant>(Idxs[i]));
1741   const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1742
1743   // Implicitly locked.
1744   return ExprConstants->getOrCreate(ReqTy, Key);
1745 }
1746
1747 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1748                                          unsigned NumIdx) {
1749   // Get the result type of the getelementptr!
1750   const Type *Ty = 
1751     GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1752   assert(Ty && "GEP indices invalid!");
1753   unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1754   return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1755 }
1756
1757 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1758                                          unsigned NumIdx) {
1759   return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1760 }
1761
1762
1763 Constant *
1764 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1765   assert(LHS->getType() == RHS->getType());
1766   assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE && 
1767          pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1768
1769   if (Constant *FC = ConstantFoldCompareInstruction(
1770                                              getGlobalContext(),pred, LHS, RHS))
1771     return FC;          // Fold a few common cases...
1772
1773   // Look up the constant in the table first to ensure uniqueness
1774   std::vector<Constant*> ArgVec;
1775   ArgVec.push_back(LHS);
1776   ArgVec.push_back(RHS);
1777   // Get the key type with both the opcode and predicate
1778   const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1779
1780   // Implicitly locked.
1781   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1782 }
1783
1784 Constant *
1785 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1786   assert(LHS->getType() == RHS->getType());
1787   assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1788
1789   if (Constant *FC = ConstantFoldCompareInstruction(
1790                                             getGlobalContext(), pred, LHS, RHS))
1791     return FC;          // Fold a few common cases...
1792
1793   // Look up the constant in the table first to ensure uniqueness
1794   std::vector<Constant*> ArgVec;
1795   ArgVec.push_back(LHS);
1796   ArgVec.push_back(RHS);
1797   // Get the key type with both the opcode and predicate
1798   const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1799   
1800   // Implicitly locked.
1801   return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1802 }
1803
1804 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1805                                             Constant *Idx) {
1806   if (Constant *FC = ConstantFoldExtractElementInstruction(
1807                                                   getGlobalContext(), Val, Idx))
1808     return FC;          // Fold a few common cases...
1809   // Look up the constant in the table first to ensure uniqueness
1810   std::vector<Constant*> ArgVec(1, Val);
1811   ArgVec.push_back(Idx);
1812   const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1813   
1814   // Implicitly locked.
1815   return ExprConstants->getOrCreate(ReqTy, Key);
1816 }
1817
1818 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1819   assert(isa<VectorType>(Val->getType()) &&
1820          "Tried to create extractelement operation on non-vector type!");
1821   assert(Idx->getType() == Type::Int32Ty &&
1822          "Extractelement index must be i32 type!");
1823   return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1824                              Val, Idx);
1825 }
1826
1827 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1828                                            Constant *Elt, Constant *Idx) {
1829   if (Constant *FC = ConstantFoldInsertElementInstruction(
1830                                             getGlobalContext(), Val, Elt, Idx))
1831     return FC;          // Fold a few common cases...
1832   // Look up the constant in the table first to ensure uniqueness
1833   std::vector<Constant*> ArgVec(1, Val);
1834   ArgVec.push_back(Elt);
1835   ArgVec.push_back(Idx);
1836   const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1837   
1838   // Implicitly locked.
1839   return ExprConstants->getOrCreate(ReqTy, Key);
1840 }
1841
1842 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt, 
1843                                          Constant *Idx) {
1844   assert(isa<VectorType>(Val->getType()) &&
1845          "Tried to create insertelement operation on non-vector type!");
1846   assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1847          && "Insertelement types must match!");
1848   assert(Idx->getType() == Type::Int32Ty &&
1849          "Insertelement index must be i32 type!");
1850   return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1851 }
1852
1853 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1854                                            Constant *V2, Constant *Mask) {
1855   if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1856                                               getGlobalContext(), V1, V2, Mask))
1857     return FC;          // Fold a few common cases...
1858   // Look up the constant in the table first to ensure uniqueness
1859   std::vector<Constant*> ArgVec(1, V1);
1860   ArgVec.push_back(V2);
1861   ArgVec.push_back(Mask);
1862   const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1863   
1864   // Implicitly locked.
1865   return ExprConstants->getOrCreate(ReqTy, Key);
1866 }
1867
1868 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2, 
1869                                          Constant *Mask) {
1870   assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1871          "Invalid shuffle vector constant expr operands!");
1872
1873   unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1874   const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1875   const Type *ShufTy = VectorType::get(EltTy, NElts);
1876   return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1877 }
1878
1879 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1880                                          Constant *Val,
1881                                         const unsigned *Idxs, unsigned NumIdx) {
1882   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1883                                           Idxs+NumIdx) == Val->getType() &&
1884          "insertvalue indices invalid!");
1885   assert(Agg->getType() == ReqTy &&
1886          "insertvalue type invalid!");
1887   assert(Agg->getType()->isFirstClassType() &&
1888          "Non-first-class type for constant InsertValue expression");
1889   Constant *FC = ConstantFoldInsertValueInstruction(
1890                                     getGlobalContext(), Agg, Val, Idxs, NumIdx);
1891   assert(FC && "InsertValue constant expr couldn't be folded!");
1892   return FC;
1893 }
1894
1895 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1896                                      const unsigned *IdxList, unsigned NumIdx) {
1897   assert(Agg->getType()->isFirstClassType() &&
1898          "Tried to create insertelement operation on non-first-class type!");
1899
1900   const Type *ReqTy = Agg->getType();
1901 #ifndef NDEBUG
1902   const Type *ValTy =
1903     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1904 #endif
1905   assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1906   return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1907 }
1908
1909 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1910                                         const unsigned *Idxs, unsigned NumIdx) {
1911   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1912                                           Idxs+NumIdx) == ReqTy &&
1913          "extractvalue indices invalid!");
1914   assert(Agg->getType()->isFirstClassType() &&
1915          "Non-first-class type for constant extractvalue expression");
1916   Constant *FC = ConstantFoldExtractValueInstruction(
1917                                          getGlobalContext(), Agg, Idxs, NumIdx);
1918   assert(FC && "ExtractValue constant expr couldn't be folded!");
1919   return FC;
1920 }
1921
1922 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1923                                      const unsigned *IdxList, unsigned NumIdx) {
1924   assert(Agg->getType()->isFirstClassType() &&
1925          "Tried to create extractelement operation on non-first-class type!");
1926
1927   const Type *ReqTy =
1928     ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1929   assert(ReqTy && "extractvalue indices invalid!");
1930   return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1931 }
1932
1933 // destroyConstant - Remove the constant from the constant table...
1934 //
1935 void ConstantExpr::destroyConstant() {
1936   // Implicitly locked.
1937   ExprConstants->remove(this);
1938   destroyConstantImpl();
1939 }
1940
1941 const char *ConstantExpr::getOpcodeName() const {
1942   return Instruction::getOpcodeName(getOpcode());
1943 }
1944
1945 //===----------------------------------------------------------------------===//
1946 //                replaceUsesOfWithOnConstant implementations
1947
1948 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1949 /// 'From' to be uses of 'To'.  This must update the uniquing data structures
1950 /// etc.
1951 ///
1952 /// Note that we intentionally replace all uses of From with To here.  Consider
1953 /// a large array that uses 'From' 1000 times.  By handling this case all here,
1954 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1955 /// single invocation handles all 1000 uses.  Handling them one at a time would
1956 /// work, but would be really slow because it would have to unique each updated
1957 /// array instance.
1958
1959 static std::vector<Constant*> getValType(ConstantArray *CA) {
1960   std::vector<Constant*> Elements;
1961   Elements.reserve(CA->getNumOperands());
1962   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1963     Elements.push_back(cast<Constant>(CA->getOperand(i)));
1964   return Elements;
1965 }
1966
1967
1968 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1969                                                 Use *U) {
1970   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1971   Constant *ToC = cast<Constant>(To);
1972
1973   LLVMContext &Context = getType()->getContext();
1974   LLVMContextImpl *pImpl = Context.pImpl;
1975
1976   std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
1977   Lookup.first.first = getType();
1978   Lookup.second = this;
1979
1980   std::vector<Constant*> &Values = Lookup.first.second;
1981   Values.reserve(getNumOperands());  // Build replacement array.
1982
1983   // Fill values with the modified operands of the constant array.  Also, 
1984   // compute whether this turns into an all-zeros array.
1985   bool isAllZeros = false;
1986   unsigned NumUpdated = 0;
1987   if (!ToC->isNullValue()) {
1988     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1989       Constant *Val = cast<Constant>(O->get());
1990       if (Val == From) {
1991         Val = ToC;
1992         ++NumUpdated;
1993       }
1994       Values.push_back(Val);
1995     }
1996   } else {
1997     isAllZeros = true;
1998     for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1999       Constant *Val = cast<Constant>(O->get());
2000       if (Val == From) {
2001         Val = ToC;
2002         ++NumUpdated;
2003       }
2004       Values.push_back(Val);
2005       if (isAllZeros) isAllZeros = Val->isNullValue();
2006     }
2007   }
2008   
2009   Constant *Replacement = 0;
2010   if (isAllZeros) {
2011     Replacement = Context.getConstantAggregateZero(getType());
2012   } else {
2013     // Check to see if we have this array type already.
2014     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
2015     bool Exists;
2016     LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2017       pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
2018     
2019     if (Exists) {
2020       Replacement = I->second;
2021     } else {
2022       // Okay, the new shape doesn't exist in the system yet.  Instead of
2023       // creating a new constant array, inserting it, replaceallusesof'ing the
2024       // old with the new, then deleting the old... just update the current one
2025       // in place!
2026       pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
2027       
2028       // Update to the new value.  Optimize for the case when we have a single
2029       // operand that we're changing, but handle bulk updates efficiently.
2030       if (NumUpdated == 1) {
2031         unsigned OperandToUpdate = U - OperandList;
2032         assert(getOperand(OperandToUpdate) == From &&
2033                "ReplaceAllUsesWith broken!");
2034         setOperand(OperandToUpdate, ToC);
2035       } else {
2036         for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2037           if (getOperand(i) == From)
2038             setOperand(i, ToC);
2039       }
2040       return;
2041     }
2042   }
2043  
2044   // Otherwise, I do need to replace this with an existing value.
2045   assert(Replacement != this && "I didn't contain From!");
2046   
2047   // Everyone using this now uses the replacement.
2048   uncheckedReplaceAllUsesWith(Replacement);
2049   
2050   // Delete the old constant!
2051   destroyConstant();
2052 }
2053
2054 static std::vector<Constant*> getValType(ConstantStruct *CS) {
2055   std::vector<Constant*> Elements;
2056   Elements.reserve(CS->getNumOperands());
2057   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
2058     Elements.push_back(cast<Constant>(CS->getOperand(i)));
2059   return Elements;
2060 }
2061
2062 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2063                                                  Use *U) {
2064   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2065   Constant *ToC = cast<Constant>(To);
2066
2067   unsigned OperandToUpdate = U-OperandList;
2068   assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2069
2070   std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
2071   Lookup.first.first = getType();
2072   Lookup.second = this;
2073   std::vector<Constant*> &Values = Lookup.first.second;
2074   Values.reserve(getNumOperands());  // Build replacement struct.
2075   
2076   
2077   // Fill values with the modified operands of the constant struct.  Also, 
2078   // compute whether this turns into an all-zeros struct.
2079   bool isAllZeros = false;
2080   if (!ToC->isNullValue()) {
2081     for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2082       Values.push_back(cast<Constant>(O->get()));
2083   } else {
2084     isAllZeros = true;
2085     for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2086       Constant *Val = cast<Constant>(O->get());
2087       Values.push_back(Val);
2088       if (isAllZeros) isAllZeros = Val->isNullValue();
2089     }
2090   }
2091   Values[OperandToUpdate] = ToC;
2092   
2093   LLVMContext &Context = getType()->getContext();
2094   LLVMContextImpl *pImpl = Context.pImpl;
2095   
2096   Constant *Replacement = 0;
2097   if (isAllZeros) {
2098     Replacement = Context.getConstantAggregateZero(getType());
2099   } else {
2100     // Check to see if we have this array type already.
2101     sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
2102     bool Exists;
2103     LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2104       pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2105     
2106     if (Exists) {
2107       Replacement = I->second;
2108     } else {
2109       // Okay, the new shape doesn't exist in the system yet.  Instead of
2110       // creating a new constant struct, inserting it, replaceallusesof'ing the
2111       // old with the new, then deleting the old... just update the current one
2112       // in place!
2113       pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2114       
2115       // Update to the new value.
2116       setOperand(OperandToUpdate, ToC);
2117       return;
2118     }
2119   }
2120   
2121   assert(Replacement != this && "I didn't contain From!");
2122   
2123   // Everyone using this now uses the replacement.
2124   uncheckedReplaceAllUsesWith(Replacement);
2125   
2126   // Delete the old constant!
2127   destroyConstant();
2128 }
2129
2130 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2131                                                  Use *U) {
2132   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2133   
2134   std::vector<Constant*> Values;
2135   Values.reserve(getNumOperands());  // Build replacement array...
2136   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2137     Constant *Val = getOperand(i);
2138     if (Val == From) Val = cast<Constant>(To);
2139     Values.push_back(Val);
2140   }
2141   
2142   Constant *Replacement =
2143     getType()->getContext().getConstantVector(getType(), Values);
2144   assert(Replacement != this && "I didn't contain From!");
2145   
2146   // Everyone using this now uses the replacement.
2147   uncheckedReplaceAllUsesWith(Replacement);
2148   
2149   // Delete the old constant!
2150   destroyConstant();
2151 }
2152
2153 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2154                                                Use *U) {
2155   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2156   Constant *To = cast<Constant>(ToV);
2157   
2158   Constant *Replacement = 0;
2159   if (getOpcode() == Instruction::GetElementPtr) {
2160     SmallVector<Constant*, 8> Indices;
2161     Constant *Pointer = getOperand(0);
2162     Indices.reserve(getNumOperands()-1);
2163     if (Pointer == From) Pointer = To;
2164     
2165     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2166       Constant *Val = getOperand(i);
2167       if (Val == From) Val = To;
2168       Indices.push_back(Val);
2169     }
2170     Replacement = ConstantExpr::getGetElementPtr(Pointer,
2171                                                  &Indices[0], Indices.size());
2172   } else if (getOpcode() == Instruction::ExtractValue) {
2173     Constant *Agg = getOperand(0);
2174     if (Agg == From) Agg = To;
2175     
2176     const SmallVector<unsigned, 4> &Indices = getIndices();
2177     Replacement = ConstantExpr::getExtractValue(Agg,
2178                                                 &Indices[0], Indices.size());
2179   } else if (getOpcode() == Instruction::InsertValue) {
2180     Constant *Agg = getOperand(0);
2181     Constant *Val = getOperand(1);
2182     if (Agg == From) Agg = To;
2183     if (Val == From) Val = To;
2184     
2185     const SmallVector<unsigned, 4> &Indices = getIndices();
2186     Replacement = ConstantExpr::getInsertValue(Agg, Val,
2187                                                &Indices[0], Indices.size());
2188   } else if (isCast()) {
2189     assert(getOperand(0) == From && "Cast only has one use!");
2190     Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2191   } else if (getOpcode() == Instruction::Select) {
2192     Constant *C1 = getOperand(0);
2193     Constant *C2 = getOperand(1);
2194     Constant *C3 = getOperand(2);
2195     if (C1 == From) C1 = To;
2196     if (C2 == From) C2 = To;
2197     if (C3 == From) C3 = To;
2198     Replacement = ConstantExpr::getSelect(C1, C2, C3);
2199   } else if (getOpcode() == Instruction::ExtractElement) {
2200     Constant *C1 = getOperand(0);
2201     Constant *C2 = getOperand(1);
2202     if (C1 == From) C1 = To;
2203     if (C2 == From) C2 = To;
2204     Replacement = ConstantExpr::getExtractElement(C1, C2);
2205   } else if (getOpcode() == Instruction::InsertElement) {
2206     Constant *C1 = getOperand(0);
2207     Constant *C2 = getOperand(1);
2208     Constant *C3 = getOperand(1);
2209     if (C1 == From) C1 = To;
2210     if (C2 == From) C2 = To;
2211     if (C3 == From) C3 = To;
2212     Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2213   } else if (getOpcode() == Instruction::ShuffleVector) {
2214     Constant *C1 = getOperand(0);
2215     Constant *C2 = getOperand(1);
2216     Constant *C3 = getOperand(2);
2217     if (C1 == From) C1 = To;
2218     if (C2 == From) C2 = To;
2219     if (C3 == From) C3 = To;
2220     Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2221   } else if (isCompare()) {
2222     Constant *C1 = getOperand(0);
2223     Constant *C2 = getOperand(1);
2224     if (C1 == From) C1 = To;
2225     if (C2 == From) C2 = To;
2226     if (getOpcode() == Instruction::ICmp)
2227       Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2228     else {
2229       assert(getOpcode() == Instruction::FCmp);
2230       Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2231     }
2232   } else if (getNumOperands() == 2) {
2233     Constant *C1 = getOperand(0);
2234     Constant *C2 = getOperand(1);
2235     if (C1 == From) C1 = To;
2236     if (C2 == From) C2 = To;
2237     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2238   } else {
2239     llvm_unreachable("Unknown ConstantExpr type!");
2240     return;
2241   }
2242   
2243   assert(Replacement != this && "I didn't contain From!");
2244   
2245   // Everyone using this now uses the replacement.
2246   uncheckedReplaceAllUsesWith(Replacement);
2247   
2248   // Delete the old constant!
2249   destroyConstant();
2250 }
2251
2252 void MDNode::replaceElement(Value *From, Value *To) {
2253   SmallVector<Value*, 4> Values;
2254   Values.reserve(getNumElements());  // Build replacement array...
2255   for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2256     Value *Val = getElement(i);
2257     if (Val == From) Val = To;
2258     Values.push_back(Val);
2259   }
2260
2261   MDNode *Replacement =
2262     getType()->getContext().getMDNode(&Values[0], Values.size());
2263   assert(Replacement != this && "I didn't contain From!");
2264
2265   uncheckedReplaceAllUsesWith(Replacement);
2266 }