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