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