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