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