Fix some comments.
[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 <algorithm>
23 #include <iostream>
24 using namespace llvm;
25
26 ConstantBool *ConstantBool::True  = new ConstantBool(true);
27 ConstantBool *ConstantBool::False = new ConstantBool(false);
28
29
30 //===----------------------------------------------------------------------===//
31 //                              Constant Class
32 //===----------------------------------------------------------------------===//
33
34 // Specialize setName to take care of symbol table majik
35 void Constant::setName(const std::string &Name, SymbolTable *ST) {
36   assert(ST && "Type::setName - Must provide symbol table argument!");
37
38   if (Name.size()) ST->insert(Name, this);
39 }
40
41 void Constant::destroyConstantImpl() {
42   // When a Constant is destroyed, there may be lingering
43   // references to the constant by other constants in the constant pool.  These
44   // constants are implicitly dependent on the module that is being deleted,
45   // but they don't know that.  Because we only find out when the CPV is
46   // deleted, we must now notify all of our users (that should only be
47   // Constants) that they are, in fact, invalid now and should be deleted.
48   //
49   while (!use_empty()) {
50     Value *V = use_back();
51 #ifndef NDEBUG      // Only in -g mode...
52     if (!isa<Constant>(V))
53       std::cerr << "While deleting: " << *this
54                 << "\n\nUse still stuck around after Def is destroyed: "
55                 << *V << "\n\n";
56 #endif
57     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
58     Constant *CV = cast<Constant>(V);
59     CV->destroyConstant();
60
61     // The constant should remove itself from our use list...
62     assert((use_empty() || use_back() != V) && "Constant not removed!");
63   }
64
65   // Value has no outstanding references it is safe to delete it now...
66   delete this;
67 }
68
69 // Static constructor to create a '0' constant of arbitrary type...
70 Constant *Constant::getNullValue(const Type *Ty) {
71   switch (Ty->getTypeID()) {
72   case Type::BoolTyID: {
73     static Constant *NullBool = ConstantBool::get(false);
74     return NullBool;
75   }
76   case Type::SByteTyID: {
77     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
78     return NullSByte;
79   }
80   case Type::UByteTyID: {
81     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
82     return NullUByte;
83   }
84   case Type::ShortTyID: {
85     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
86     return NullShort;
87   }
88   case Type::UShortTyID: {
89     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
90     return NullUShort;
91   }
92   case Type::IntTyID: {
93     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
94     return NullInt;
95   }
96   case Type::UIntTyID: {
97     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
98     return NullUInt;
99   }
100   case Type::LongTyID: {
101     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
102     return NullLong;
103   }
104   case Type::ULongTyID: {
105     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
106     return NullULong;
107   }
108
109   case Type::FloatTyID: {
110     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
111     return NullFloat;
112   }
113   case Type::DoubleTyID: {
114     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
115     return NullDouble;
116   }
117
118   case Type::PointerTyID: 
119     return ConstantPointerNull::get(cast<PointerType>(Ty));
120
121   case Type::StructTyID:
122   case Type::ArrayTyID:
123   case Type::PackedTyID:
124     return ConstantAggregateZero::get(Ty);
125   default:
126     // Function, Label, or Opaque type?
127     assert(!"Cannot create a null constant of that type!");
128     return 0;
129   }
130 }
131
132 // Static constructor to create the maximum constant of an integral type...
133 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
134   switch (Ty->getTypeID()) {
135   case Type::BoolTyID:   return ConstantBool::True;
136   case Type::SByteTyID:
137   case Type::ShortTyID:
138   case Type::IntTyID:
139   case Type::LongTyID: {
140     // Calculate 011111111111111... 
141     unsigned TypeBits = Ty->getPrimitiveSize()*8;
142     int64_t Val = INT64_MAX;             // All ones
143     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
144     return ConstantSInt::get(Ty, Val);
145   }
146
147   case Type::UByteTyID:
148   case Type::UShortTyID:
149   case Type::UIntTyID:
150   case Type::ULongTyID:  return getAllOnesValue(Ty);
151
152   default: return 0;
153   }
154 }
155
156 // Static constructor to create the minimum constant for an integral type...
157 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
158   switch (Ty->getTypeID()) {
159   case Type::BoolTyID:   return ConstantBool::False;
160   case Type::SByteTyID:
161   case Type::ShortTyID:
162   case Type::IntTyID:
163   case Type::LongTyID: {
164      // Calculate 1111111111000000000000 
165      unsigned TypeBits = Ty->getPrimitiveSize()*8;
166      int64_t Val = -1;                    // All ones
167      Val <<= TypeBits-1;                  // Shift over to the right spot
168      return ConstantSInt::get(Ty, Val);
169   }
170
171   case Type::UByteTyID:
172   case Type::UShortTyID:
173   case Type::UIntTyID:
174   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
175
176   default: return 0;
177   }
178 }
179
180 // Static constructor to create an integral constant with all bits set
181 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
182   switch (Ty->getTypeID()) {
183   case Type::BoolTyID:   return ConstantBool::True;
184   case Type::SByteTyID:
185   case Type::ShortTyID:
186   case Type::IntTyID:
187   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
188
189   case Type::UByteTyID:
190   case Type::UShortTyID:
191   case Type::UIntTyID:
192   case Type::ULongTyID: {
193     // Calculate ~0 of the right type...
194     unsigned TypeBits = Ty->getPrimitiveSize()*8;
195     uint64_t Val = ~0ULL;                // All ones
196     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
197     return ConstantUInt::get(Ty, Val);
198   }
199   default: return 0;
200   }
201 }
202
203 bool ConstantUInt::isAllOnesValue() const {
204   unsigned TypeBits = getType()->getPrimitiveSize()*8;
205   uint64_t Val = ~0ULL;                // All ones
206   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
207   return getValue() == Val;
208 }
209
210
211 //===----------------------------------------------------------------------===//
212 //                            ConstantXXX Classes
213 //===----------------------------------------------------------------------===//
214
215 //===----------------------------------------------------------------------===//
216 //                             Normal Constructors
217
218 ConstantIntegral::ConstantIntegral(const Type *Ty, uint64_t V)
219   : Constant(Ty) {
220     Val.Unsigned = V;
221 }
222
223 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy, V) {
224 }
225
226 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty, V) {
227 }
228
229 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
230   assert(Ty->isInteger() && Ty->isSigned() &&
231          "Illegal type for unsigned integer constant!");
232   assert(isValueValidForType(Ty, V) && "Value too large for type!");
233 }
234
235 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
236   assert(Ty->isInteger() && Ty->isUnsigned() &&
237          "Illegal type for unsigned integer constant!");
238   assert(isValueValidForType(Ty, V) && "Value too large for type!");
239 }
240
241 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
242   assert(isValueValidForType(Ty, V) && "Value too large for type!");
243   Val = V;
244 }
245
246 ConstantArray::ConstantArray(const ArrayType *T,
247                              const std::vector<Constant*> &V) : Constant(T) {
248   assert(V.size() == T->getNumElements() &&
249          "Invalid initializer vector for constant array");
250   Operands.reserve(V.size());
251   for (unsigned i = 0, e = V.size(); i != e; ++i) {
252     assert((V[i]->getType() == T->getElementType() ||
253             (T->isAbstract() &&
254              V[i]->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
255            "Initializer for array element doesn't match array element type!");
256     Operands.push_back(Use(V[i], this));
257   }
258 }
259
260 ConstantStruct::ConstantStruct(const StructType *T,
261                                const std::vector<Constant*> &V) : Constant(T) {
262   assert(V.size() == T->getNumElements() &&
263          "Invalid initializer vector for constant structure");
264   Operands.reserve(V.size());
265   for (unsigned i = 0, e = V.size(); i != e; ++i) {
266     assert((V[i]->getType() == T->getElementType(i) ||
267             ((T->getElementType(i)->isAbstract() ||
268               V[i]->getType()->isAbstract()) &&
269              T->getElementType(i)->getTypeID() == V[i]->getType()->getTypeID())) &&
270            "Initializer for struct element doesn't match struct element type!");
271     Operands.push_back(Use(V[i], this));
272   }
273 }
274
275 ConstantPacked::ConstantPacked(const PackedType *T,
276                                const std::vector<Constant*> &V) : Constant(T) {
277   Operands.reserve(V.size());
278   for (unsigned i = 0, e = V.size(); i != e; ++i) {
279     assert((V[i]->getType() == T->getElementType() ||
280             (T->isAbstract() &&
281              V[i]->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
282            "Initializer for packed element doesn't match packed element type!");
283     Operands.push_back(Use(V[i], this));
284   }
285 }
286
287 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
288   : Constant(Ty, ConstantExprVal), iType(Opcode) {
289   Operands.reserve(1);
290   Operands.push_back(Use(C, this));
291 }
292
293 // Select instruction creation ctor
294 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
295   : Constant(V1->getType(), ConstantExprVal), iType(Instruction::Select) {
296   Operands.reserve(3);
297   Operands.push_back(Use(C, this));
298   Operands.push_back(Use(V1, this));
299   Operands.push_back(Use(V2, this));
300 }
301
302
303 static bool isSetCC(unsigned Opcode) {
304   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
305          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
306          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
307 }
308
309 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
310   : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType(), ConstantExprVal),
311     iType(Opcode) {
312   Operands.reserve(2);
313   Operands.push_back(Use(C1, this));
314   Operands.push_back(Use(C2, this));
315 }
316
317 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
318                            const Type *DestTy)
319   : Constant(DestTy, ConstantExprVal), iType(Instruction::GetElementPtr) {
320   Operands.reserve(1+IdxList.size());
321   Operands.push_back(Use(C, this));
322   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
323     Operands.push_back(Use(IdxList[i], this));
324 }
325
326 /// ConstantExpr::get* - Return some common constants without having to
327 /// specify the full Instruction::OPCODE identifier.
328 ///
329 Constant *ConstantExpr::getNeg(Constant *C) {
330   if (!C->getType()->isFloatingPoint())
331     return get(Instruction::Sub, getNullValue(C->getType()), C);
332   else
333     return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
334 }
335 Constant *ConstantExpr::getNot(Constant *C) {
336   assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
337   return get(Instruction::Xor, C,
338              ConstantIntegral::getAllOnesValue(C->getType()));
339 }
340 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
341   return get(Instruction::Add, C1, C2);
342 }
343 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
344   return get(Instruction::Sub, C1, C2);
345 }
346 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
347   return get(Instruction::Mul, C1, C2);
348 }
349 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
350   return get(Instruction::Div, C1, C2);
351 }
352 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
353   return get(Instruction::Rem, C1, C2);
354 }
355 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
356   return get(Instruction::And, C1, C2);
357 }
358 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
359   return get(Instruction::Or, C1, C2);
360 }
361 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
362   return get(Instruction::Xor, C1, C2);
363 }
364 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
365   return get(Instruction::SetEQ, C1, C2);
366 }
367 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
368   return get(Instruction::SetNE, C1, C2);
369 }
370 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
371   return get(Instruction::SetLT, C1, C2);
372 }
373 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
374   return get(Instruction::SetGT, C1, C2);
375 }
376 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
377   return get(Instruction::SetLE, C1, C2);
378 }
379 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
380   return get(Instruction::SetGE, C1, C2);
381 }
382 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
383   return get(Instruction::Shl, C1, C2);
384 }
385 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
386   return get(Instruction::Shr, C1, C2);
387 }
388
389 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
390   if (C1->getType()->isUnsigned()) return getShr(C1, C2);
391   return getCast(getShr(getCast(C1,
392                     C1->getType()->getUnsignedVersion()), C2), C1->getType());
393 }
394
395 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
396   if (C1->getType()->isSigned()) return getShr(C1, C2);
397   return getCast(getShr(getCast(C1,
398                         C1->getType()->getSignedVersion()), C2), C1->getType());
399 }
400
401
402 //===----------------------------------------------------------------------===//
403 //                      isValueValidForType implementations
404
405 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
406   switch (Ty->getTypeID()) {
407   default:
408     return false;         // These can't be represented as integers!!!
409     // Signed types...
410   case Type::SByteTyID:
411     return (Val <= INT8_MAX && Val >= INT8_MIN);
412   case Type::ShortTyID:
413     return (Val <= INT16_MAX && Val >= INT16_MIN);
414   case Type::IntTyID:
415     return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
416   case Type::LongTyID:
417     return true;          // This is the largest type...
418   }
419 }
420
421 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
422   switch (Ty->getTypeID()) {
423   default:
424     return false;         // These can't be represented as integers!!!
425
426     // Unsigned types...
427   case Type::UByteTyID:
428     return (Val <= UINT8_MAX);
429   case Type::UShortTyID:
430     return (Val <= UINT16_MAX);
431   case Type::UIntTyID:
432     return (Val <= UINT32_MAX);
433   case Type::ULongTyID:
434     return true;          // This is the largest type...
435   }
436 }
437
438 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
439   switch (Ty->getTypeID()) {
440   default:
441     return false;         // These can't be represented as floating point!
442
443   case Type::FloatTyID:
444     // Since we're passed a double but the ConstantFP is of type float, make
445     // sure that the double value is in the range of a float
446     return isinf(Val) || isnan(Val) || (Val >= -HUGE_VALF && Val <= HUGE_VALF);
447     
448   case Type::DoubleTyID:
449     return true;          // This is the largest type...
450   }
451 };
452
453 //===----------------------------------------------------------------------===//
454 //                replaceUsesOfWithOnConstant implementations
455
456 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
457                                                 bool DisableChecking) {
458   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
459
460   std::vector<Constant*> Values;
461   Values.reserve(getNumOperands());  // Build replacement array...
462   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
463     Constant *Val = getOperand(i);
464     if (Val == From) Val = cast<Constant>(To);
465     Values.push_back(Val);
466   }
467   
468   Constant *Replacement = ConstantArray::get(getType(), Values);
469   assert(Replacement != this && "I didn't contain From!");
470
471   // Everyone using this now uses the replacement...
472   if (DisableChecking)
473     uncheckedReplaceAllUsesWith(Replacement);
474   else
475     replaceAllUsesWith(Replacement);
476   
477   // Delete the old constant!
478   destroyConstant();  
479 }
480
481 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
482                                                  bool DisableChecking) {
483   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
484
485   std::vector<Constant*> Values;
486   Values.reserve(getNumOperands());  // Build replacement array...
487   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
488     Constant *Val = getOperand(i);
489     if (Val == From) Val = cast<Constant>(To);
490     Values.push_back(Val);
491   }
492   
493   Constant *Replacement = ConstantStruct::get(getType(), Values);
494   assert(Replacement != this && "I didn't contain From!");
495
496   // Everyone using this now uses the replacement...
497   if (DisableChecking)
498     uncheckedReplaceAllUsesWith(Replacement);
499   else
500     replaceAllUsesWith(Replacement);
501   
502   // Delete the old constant!
503   destroyConstant();
504 }
505
506 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
507                                                  bool DisableChecking) {
508   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
509
510   std::vector<Constant*> Values;
511   Values.reserve(getNumOperands());  // Build replacement array...
512   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
513     Constant *Val = getOperand(i);
514     if (Val == From) Val = cast<Constant>(To);
515     Values.push_back(Val);
516   }
517   
518   Constant *Replacement = ConstantPacked::get(getType(), Values);
519   assert(Replacement != this && "I didn't contain From!");
520
521   // Everyone using this now uses the replacement...
522   if (DisableChecking)
523     uncheckedReplaceAllUsesWith(Replacement);
524   else
525     replaceAllUsesWith(Replacement);
526   
527   // Delete the old constant!
528   destroyConstant();  
529 }
530
531 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
532                                                bool DisableChecking) {
533   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
534   Constant *To = cast<Constant>(ToV);
535
536   Constant *Replacement = 0;
537   if (getOpcode() == Instruction::GetElementPtr) {
538     std::vector<Constant*> Indices;
539     Constant *Pointer = getOperand(0);
540     Indices.reserve(getNumOperands()-1);
541     if (Pointer == From) Pointer = To;
542     
543     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
544       Constant *Val = getOperand(i);
545       if (Val == From) Val = To;
546       Indices.push_back(Val);
547     }
548     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
549   } else if (getOpcode() == Instruction::Cast) {
550     assert(getOperand(0) == From && "Cast only has one use!");
551     Replacement = ConstantExpr::getCast(To, getType());
552   } else if (getOpcode() == Instruction::Select) {
553     Constant *C1 = getOperand(0);
554     Constant *C2 = getOperand(1);
555     Constant *C3 = getOperand(2);
556     if (C1 == From) C1 = To;
557     if (C2 == From) C2 = To;
558     if (C3 == From) C3 = To;
559     Replacement = ConstantExpr::getSelect(C1, C2, C3);
560   } else if (getNumOperands() == 2) {
561     Constant *C1 = getOperand(0);
562     Constant *C2 = getOperand(1);
563     if (C1 == From) C1 = To;
564     if (C2 == From) C2 = To;
565     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
566   } else {
567     assert(0 && "Unknown ConstantExpr type!");
568     return;
569   }
570   
571   assert(Replacement != this && "I didn't contain From!");
572
573   // Everyone using this now uses the replacement...
574   if (DisableChecking)
575     uncheckedReplaceAllUsesWith(Replacement);
576   else
577     replaceAllUsesWith(Replacement);
578   
579   // Delete the old constant!
580   destroyConstant();
581 }
582
583 //===----------------------------------------------------------------------===//
584 //                      Factory Function Implementation
585
586 // ConstantCreator - A class that is used to create constants by
587 // ValueMap*.  This class should be partially specialized if there is
588 // something strange that needs to be done to interface to the ctor for the
589 // constant.
590 //
591 namespace llvm {
592   template<class ConstantClass, class TypeClass, class ValType>
593   struct ConstantCreator {
594     static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
595       return new ConstantClass(Ty, V);
596     }
597   };
598   
599   template<class ConstantClass, class TypeClass>
600   struct ConvertConstantType {
601     static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
602       assert(0 && "This type cannot be converted!\n");
603       abort();
604     }
605   };
606 }
607
608 namespace {
609   template<class ValType, class TypeClass, class ConstantClass>
610   class ValueMap : public AbstractTypeUser {
611     typedef std::pair<const TypeClass*, ValType> MapKey;
612     typedef std::map<MapKey, ConstantClass *> MapTy;
613     typedef typename MapTy::iterator MapIterator;
614     MapTy Map;
615
616     typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
617     AbstractTypeMapTy AbstractTypeMap;
618
619     friend void Constant::clearAllValueMaps();
620   private:
621     void clear(std::vector<Constant *> &Constants) {
622       for(MapIterator I = Map.begin(); I != Map.end(); ++I)
623         Constants.push_back(I->second);
624       Map.clear();
625       AbstractTypeMap.clear();
626     }
627
628   public:
629     // getOrCreate - Return the specified constant from the map, creating it if
630     // necessary.
631     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
632       MapKey Lookup(Ty, V);
633       MapIterator I = Map.lower_bound(Lookup);
634       if (I != Map.end() && I->first == Lookup)
635         return I->second;  // Is it in the map?
636
637       // If no preexisting value, create one now...
638       ConstantClass *Result =
639         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
640
641
642       /// FIXME: why does this assert fail when loading 176.gcc?
643       //assert(Result->getType() == Ty && "Type specified is not correct!");
644       I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
645
646       // If the type of the constant is abstract, make sure that an entry exists
647       // for it in the AbstractTypeMap.
648       if (Ty->isAbstract()) {
649         typename AbstractTypeMapTy::iterator TI =
650           AbstractTypeMap.lower_bound(Ty);
651
652         if (TI == AbstractTypeMap.end() || TI->first != Ty) {
653           // Add ourselves to the ATU list of the type.
654           cast<DerivedType>(Ty)->addAbstractTypeUser(this);
655
656           AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
657         }
658       }
659       return Result;
660     }
661     
662     void remove(ConstantClass *CP) {
663       MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
664                                       getValType(CP)));
665       if (I == Map.end() || I->second != CP) {
666         // FIXME: This should not use a linear scan.  If this gets to be a
667         // performance problem, someone should look at this.
668         for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
669           /* empty */;
670       }
671
672       assert(I != Map.end() && "Constant not found in constant table!");
673       assert(I->second == CP && "Didn't find correct element?");
674
675       // Now that we found the entry, make sure this isn't the entry that
676       // the AbstractTypeMap points to.
677       const TypeClass *Ty = I->first.first;
678       if (Ty->isAbstract()) {
679         assert(AbstractTypeMap.count(Ty) &&
680                "Abstract type not in AbstractTypeMap?");
681         MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
682         if (ATMEntryIt == I) {
683           // Yes, we are removing the representative entry for this type.
684           // See if there are any other entries of the same type.
685           MapIterator TmpIt = ATMEntryIt;
686           
687           // First check the entry before this one...
688           if (TmpIt != Map.begin()) {
689             --TmpIt;
690             if (TmpIt->first.first != Ty) // Not the same type, move back...
691               ++TmpIt;
692           }
693           
694           // If we didn't find the same type, try to move forward...
695           if (TmpIt == ATMEntryIt) {
696             ++TmpIt;
697             if (TmpIt == Map.end() || TmpIt->first.first != Ty)
698               --TmpIt;   // No entry afterwards with the same type
699           }
700
701           // If there is another entry in the map of the same abstract type,
702           // update the AbstractTypeMap entry now.
703           if (TmpIt != ATMEntryIt) {
704             ATMEntryIt = TmpIt;
705           } else {
706             // Otherwise, we are removing the last instance of this type
707             // from the table.  Remove from the ATM, and from user list.
708             cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
709             AbstractTypeMap.erase(Ty);
710           }
711         }
712       }
713       
714       Map.erase(I);
715     }
716
717     void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
718       typename AbstractTypeMapTy::iterator I = 
719         AbstractTypeMap.find(cast<TypeClass>(OldTy));
720
721       assert(I != AbstractTypeMap.end() &&
722              "Abstract type not in AbstractTypeMap?");
723
724       // Convert a constant at a time until the last one is gone.  The last one
725       // leaving will remove() itself, causing the AbstractTypeMapEntry to be
726       // eliminated eventually.
727       do {
728         ConvertConstantType<ConstantClass,
729                             TypeClass>::convert(I->second->second,
730                                                 cast<TypeClass>(NewTy));
731
732         I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
733       } while (I != AbstractTypeMap.end());
734     }
735
736     // If the type became concrete without being refined to any other existing
737     // type, we just remove ourselves from the ATU list.
738     void typeBecameConcrete(const DerivedType *AbsTy) {
739       AbsTy->removeAbstractTypeUser(this);
740     }
741
742     void dump() const {
743       std::cerr << "Constant.cpp: ValueMap\n";
744     }
745   };
746 }
747
748 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
749 //
750 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
751 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
752
753 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
754   return SIntConstants.getOrCreate(Ty, V);
755 }
756
757 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
758   return UIntConstants.getOrCreate(Ty, V);
759 }
760
761 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
762   assert(V <= 127 && "Can only be used with very small positive constants!");
763   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
764   return ConstantUInt::get(Ty, V);
765 }
766
767 //---- ConstantFP::get() implementation...
768 //
769 namespace llvm {
770   template<>
771   struct ConstantCreator<ConstantFP, Type, uint64_t> {
772     static ConstantFP *create(const Type *Ty, uint64_t V) {
773       assert(Ty == Type::DoubleTy);
774       union {
775         double F;
776         uint64_t I;
777       } T;
778       T.I = V;
779       return new ConstantFP(Ty, T.F);
780     }
781   };
782   template<>
783   struct ConstantCreator<ConstantFP, Type, uint32_t> {
784     static ConstantFP *create(const Type *Ty, uint32_t V) {
785       assert(Ty == Type::FloatTy);
786       union {
787         float F;
788         uint32_t I;
789       } T;
790       T.I = V;
791       return new ConstantFP(Ty, T.F);
792     }
793   };
794 }
795
796 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
797 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
798
799 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
800   if (Ty == Type::FloatTy) {
801     // Force the value through memory to normalize it.
802     union {
803       float F;
804       uint32_t I;
805     } T;
806     T.F = (float)V;
807     return FloatConstants.getOrCreate(Ty, T.I);
808   } else {
809     assert(Ty == Type::DoubleTy);
810     union {
811       double F;
812       uint64_t I;
813     } T;
814     T.F = V;
815     return DoubleConstants.getOrCreate(Ty, T.I);
816   }
817 }
818
819 //---- ConstantAggregateZero::get() implementation...
820 //
821 namespace llvm {
822   // ConstantAggregateZero does not take extra "value" argument...
823   template<class ValType>
824   struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
825     static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
826       return new ConstantAggregateZero(Ty);
827     }
828   };
829
830   template<>
831   struct ConvertConstantType<ConstantAggregateZero, Type> {
832     static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
833       // Make everyone now use a constant of the new type...
834       Constant *New = ConstantAggregateZero::get(NewTy);
835       assert(New != OldC && "Didn't replace constant??");
836       OldC->uncheckedReplaceAllUsesWith(New);
837       OldC->destroyConstant();     // This constant is now dead, destroy it.
838     }
839   };
840 }
841
842 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
843
844 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
845
846 Constant *ConstantAggregateZero::get(const Type *Ty) {
847   return AggZeroConstants.getOrCreate(Ty, 0);
848 }
849
850 // destroyConstant - Remove the constant from the constant table...
851 //
852 void ConstantAggregateZero::destroyConstant() {
853   AggZeroConstants.remove(this);
854   destroyConstantImpl();
855 }
856
857 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
858                                                         bool DisableChecking) {
859   assert(0 && "No uses!");
860   abort();
861 }
862
863
864
865 //---- ConstantArray::get() implementation...
866 //
867 namespace llvm {
868   template<>
869   struct ConvertConstantType<ConstantArray, ArrayType> {
870     static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
871       // Make everyone now use a constant of the new type...
872       std::vector<Constant*> C;
873       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
874         C.push_back(cast<Constant>(OldC->getOperand(i)));
875       Constant *New = ConstantArray::get(NewTy, C);
876       assert(New != OldC && "Didn't replace constant??");
877       OldC->uncheckedReplaceAllUsesWith(New);
878       OldC->destroyConstant();    // This constant is now dead, destroy it.
879     }
880   };
881 }
882
883 static std::vector<Constant*> getValType(ConstantArray *CA) {
884   std::vector<Constant*> Elements;
885   Elements.reserve(CA->getNumOperands());
886   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
887     Elements.push_back(cast<Constant>(CA->getOperand(i)));
888   return Elements;
889 }
890
891 static ValueMap<std::vector<Constant*>, ArrayType,
892                 ConstantArray> ArrayConstants;
893
894 Constant *ConstantArray::get(const ArrayType *Ty,
895                              const std::vector<Constant*> &V) {
896   // If this is an all-zero array, return a ConstantAggregateZero object
897   if (!V.empty()) {
898     Constant *C = V[0];
899     if (!C->isNullValue())
900       return ArrayConstants.getOrCreate(Ty, V);
901     for (unsigned i = 1, e = V.size(); i != e; ++i)
902       if (V[i] != C)
903         return ArrayConstants.getOrCreate(Ty, V);
904   }
905   return ConstantAggregateZero::get(Ty);
906 }
907
908 // destroyConstant - Remove the constant from the constant table...
909 //
910 void ConstantArray::destroyConstant() {
911   ArrayConstants.remove(this);
912   destroyConstantImpl();
913 }
914
915 // ConstantArray::get(const string&) - Return an array that is initialized to
916 // contain the specified string.  A null terminator is added to the specified
917 // string so that it may be used in a natural way...
918 //
919 Constant *ConstantArray::get(const std::string &Str) {
920   std::vector<Constant*> ElementVals;
921
922   for (unsigned i = 0; i < Str.length(); ++i)
923     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
924
925   // Add a null terminator to the string...
926   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
927
928   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
929   return ConstantArray::get(ATy, ElementVals);
930 }
931
932 /// isString - This method returns true if the array is an array of sbyte or
933 /// ubyte, and if the elements of the array are all ConstantInt's.
934 bool ConstantArray::isString() const {
935   // Check the element type for sbyte or ubyte...
936   if (getType()->getElementType() != Type::UByteTy &&
937       getType()->getElementType() != Type::SByteTy)
938     return false;
939   // Check the elements to make sure they are all integers, not constant
940   // expressions.
941   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
942     if (!isa<ConstantInt>(getOperand(i)))
943       return false;
944   return true;
945 }
946
947 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
948 // then this method converts the array to an std::string and returns it.
949 // Otherwise, it asserts out.
950 //
951 std::string ConstantArray::getAsString() const {
952   assert(isString() && "Not a string!");
953   std::string Result;
954   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
955     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
956   return Result;
957 }
958
959
960 //---- ConstantStruct::get() implementation...
961 //
962
963 namespace llvm {
964   template<>
965   struct ConvertConstantType<ConstantStruct, StructType> {
966     static void convert(ConstantStruct *OldC, const StructType *NewTy) {
967       // Make everyone now use a constant of the new type...
968       std::vector<Constant*> C;
969       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
970         C.push_back(cast<Constant>(OldC->getOperand(i)));
971       Constant *New = ConstantStruct::get(NewTy, C);
972       assert(New != OldC && "Didn't replace constant??");
973       
974       OldC->uncheckedReplaceAllUsesWith(New);
975       OldC->destroyConstant();    // This constant is now dead, destroy it.
976     }
977   };
978 }
979
980 static ValueMap<std::vector<Constant*>, StructType, 
981                 ConstantStruct> StructConstants;
982
983 static std::vector<Constant*> getValType(ConstantStruct *CS) {
984   std::vector<Constant*> Elements;
985   Elements.reserve(CS->getNumOperands());
986   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
987     Elements.push_back(cast<Constant>(CS->getOperand(i)));
988   return Elements;
989 }
990
991 Constant *ConstantStruct::get(const StructType *Ty,
992                               const std::vector<Constant*> &V) {
993   // Create a ConstantAggregateZero value if all elements are zeros...
994   for (unsigned i = 0, e = V.size(); i != e; ++i)
995     if (!V[i]->isNullValue())
996       return StructConstants.getOrCreate(Ty, V);
997
998   return ConstantAggregateZero::get(Ty);
999 }
1000
1001 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1002   std::vector<const Type*> StructEls;
1003   StructEls.reserve(V.size());
1004   for (unsigned i = 0, e = V.size(); i != e; ++i)
1005     StructEls.push_back(V[i]->getType());
1006   return get(StructType::get(StructEls), V);
1007 }
1008
1009 // destroyConstant - Remove the constant from the constant table...
1010 //
1011 void ConstantStruct::destroyConstant() {
1012   StructConstants.remove(this);
1013   destroyConstantImpl();
1014 }
1015
1016 //---- ConstantPacked::get() implementation...
1017 //
1018 namespace llvm {
1019   template<>
1020   struct ConvertConstantType<ConstantPacked, PackedType> {
1021     static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1022       // Make everyone now use a constant of the new type...
1023       std::vector<Constant*> C;
1024       for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1025         C.push_back(cast<Constant>(OldC->getOperand(i)));
1026       Constant *New = ConstantPacked::get(NewTy, C);
1027       assert(New != OldC && "Didn't replace constant??");
1028       OldC->uncheckedReplaceAllUsesWith(New);
1029       OldC->destroyConstant();    // This constant is now dead, destroy it.
1030     }
1031   };
1032 }
1033
1034 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1035   std::vector<Constant*> Elements;
1036   Elements.reserve(CP->getNumOperands());
1037   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1038     Elements.push_back(CP->getOperand(i));
1039   return Elements;
1040 }
1041
1042 static ValueMap<std::vector<Constant*>, PackedType,
1043                 ConstantPacked> PackedConstants;
1044
1045 Constant *ConstantPacked::get(const PackedType *Ty,
1046                               const std::vector<Constant*> &V) {
1047   // If this is an all-zero packed, return a ConstantAggregateZero object
1048   if (!V.empty()) {
1049     Constant *C = V[0];
1050     if (!C->isNullValue())
1051       return PackedConstants.getOrCreate(Ty, V);
1052     for (unsigned i = 1, e = V.size(); i != e; ++i)
1053       if (V[i] != C)
1054         return PackedConstants.getOrCreate(Ty, V);
1055   }
1056   return ConstantAggregateZero::get(Ty);
1057 }
1058
1059 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1060   assert(!V.empty() && "Cannot infer type if V is empty");
1061   return get(PackedType::get(V.front()->getType(),V.size()), V);
1062 }
1063
1064 // destroyConstant - Remove the constant from the constant table...
1065 //
1066 void ConstantPacked::destroyConstant() {
1067   PackedConstants.remove(this);
1068   destroyConstantImpl();
1069 }
1070
1071 //---- ConstantPointerNull::get() implementation...
1072 //
1073
1074 namespace llvm {
1075   // ConstantPointerNull does not take extra "value" argument...
1076   template<class ValType>
1077   struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1078     static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1079       return new ConstantPointerNull(Ty);
1080     }
1081   };
1082
1083   template<>
1084   struct ConvertConstantType<ConstantPointerNull, PointerType> {
1085     static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1086       // Make everyone now use a constant of the new type...
1087       Constant *New = ConstantPointerNull::get(NewTy);
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 ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1096
1097 static char getValType(ConstantPointerNull *) {
1098   return 0;
1099 }
1100
1101
1102 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1103   return NullPtrConstants.getOrCreate(Ty, 0);
1104 }
1105
1106 // destroyConstant - Remove the constant from the constant table...
1107 //
1108 void ConstantPointerNull::destroyConstant() {
1109   NullPtrConstants.remove(this);
1110   destroyConstantImpl();
1111 }
1112
1113
1114 //---- UndefValue::get() implementation...
1115 //
1116
1117 namespace llvm {
1118   // UndefValue does not take extra "value" argument...
1119   template<class ValType>
1120   struct ConstantCreator<UndefValue, Type, ValType> {
1121     static UndefValue *create(const Type *Ty, const ValType &V) {
1122       return new UndefValue(Ty);
1123     }
1124   };
1125
1126   template<>
1127   struct ConvertConstantType<UndefValue, Type> {
1128     static void convert(UndefValue *OldC, const Type *NewTy) {
1129       // Make everyone now use a constant of the new type.
1130       Constant *New = UndefValue::get(NewTy);
1131       assert(New != OldC && "Didn't replace constant??");
1132       OldC->uncheckedReplaceAllUsesWith(New);
1133       OldC->destroyConstant();     // This constant is now dead, destroy it.
1134     }
1135   };
1136 }
1137
1138 static ValueMap<char, Type, UndefValue> UndefValueConstants;
1139
1140 static char getValType(UndefValue *) {
1141   return 0;
1142 }
1143
1144
1145 UndefValue *UndefValue::get(const Type *Ty) {
1146   return UndefValueConstants.getOrCreate(Ty, 0);
1147 }
1148
1149 // destroyConstant - Remove the constant from the constant table.
1150 //
1151 void UndefValue::destroyConstant() {
1152   UndefValueConstants.remove(this);
1153   destroyConstantImpl();
1154 }
1155
1156
1157
1158
1159 //---- ConstantExpr::get() implementations...
1160 //
1161 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1162
1163 namespace llvm {
1164   template<>
1165   struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1166     static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1167       if (V.first == Instruction::Cast)
1168         return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
1169       if ((V.first >= Instruction::BinaryOpsBegin &&
1170            V.first < Instruction::BinaryOpsEnd) ||
1171           V.first == Instruction::Shl || V.first == Instruction::Shr)
1172         return new ConstantExpr(V.first, V.second[0], V.second[1]);
1173       if (V.first == Instruction::Select)
1174         return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
1175       
1176       assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1177       
1178       std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1179       return new ConstantExpr(V.second[0], IdxList, Ty);
1180     }
1181   };
1182
1183   template<>
1184   struct ConvertConstantType<ConstantExpr, Type> {
1185     static void convert(ConstantExpr *OldC, const Type *NewTy) {
1186       Constant *New;
1187       switch (OldC->getOpcode()) {
1188       case Instruction::Cast:
1189         New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1190         break;
1191       case Instruction::Select:
1192         New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1193                                         OldC->getOperand(1),
1194                                         OldC->getOperand(2));
1195         break;
1196       case Instruction::Shl:
1197       case Instruction::Shr:
1198         New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1199                                      OldC->getOperand(0), OldC->getOperand(1));
1200         break;
1201       default:
1202         assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1203                OldC->getOpcode() < Instruction::BinaryOpsEnd);
1204         New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1205                                   OldC->getOperand(1));
1206         break;
1207       case Instruction::GetElementPtr:
1208         // Make everyone now use a constant of the new type... 
1209         std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1210         New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1211         break;
1212       }
1213       
1214       assert(New != OldC && "Didn't replace constant??");
1215       OldC->uncheckedReplaceAllUsesWith(New);
1216       OldC->destroyConstant();    // This constant is now dead, destroy it.
1217     }
1218   };
1219 } // end namespace llvm
1220
1221
1222 static ExprMapKeyType getValType(ConstantExpr *CE) {
1223   std::vector<Constant*> Operands;
1224   Operands.reserve(CE->getNumOperands());
1225   for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1226     Operands.push_back(cast<Constant>(CE->getOperand(i)));
1227   return ExprMapKeyType(CE->getOpcode(), Operands);
1228 }
1229
1230 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1231
1232 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1233   assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1234
1235   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1236     return FC;          // Fold a few common cases...
1237
1238   // Look up the constant in the table first to ensure uniqueness
1239   std::vector<Constant*> argVec(1, C);
1240   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1241   return ExprConstants.getOrCreate(Ty, Key);
1242 }
1243
1244 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1245   assert(C->getType()->isInteger() && Ty->isInteger() &&
1246          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1247          "This is an illegal sign extension!");
1248   C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1249   return ConstantExpr::getCast(C, Ty);
1250 }
1251
1252 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1253   assert(C->getType()->isInteger() && Ty->isInteger() &&
1254          C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1255          "This is an illegal zero extension!");
1256   C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1257   return ConstantExpr::getCast(C, Ty);
1258 }
1259
1260 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1261   // sizeof is implemented as: (unsigned) gep (Ty*)null, 1
1262   return getCast(
1263     getGetElementPtr(
1264       getNullValue(PointerType::get(Ty)),
1265       std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1266     Type::UIntTy);
1267 }
1268
1269 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1270                               Constant *C1, Constant *C2) {
1271   if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1272     return getShiftTy(ReqTy, Opcode, C1, C2);
1273   // Check the operands for consistency first
1274   assert((Opcode >= Instruction::BinaryOpsBegin &&
1275           Opcode < Instruction::BinaryOpsEnd) &&
1276          "Invalid opcode in binary constant expression");
1277   assert(C1->getType() == C2->getType() &&
1278          "Operand types in binary constant expression should match");
1279
1280   if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1281                                  ReqTy == Type::BoolTy))
1282     if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1283       return FC;          // Fold a few common cases...
1284
1285   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1286   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1287   return ExprConstants.getOrCreate(ReqTy, Key);
1288 }
1289
1290 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1291 #ifndef NDEBUG
1292   switch (Opcode) {
1293   case Instruction::Add: case Instruction::Sub:
1294   case Instruction::Mul: case Instruction::Div:
1295   case Instruction::Rem:
1296     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1297     assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) && 
1298            "Tried to create an arithmetic operation on a non-arithmetic type!");
1299     break;
1300   case Instruction::And:
1301   case Instruction::Or:
1302   case Instruction::Xor:
1303     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1304     assert(C1->getType()->isIntegral() &&
1305            "Tried to create an logical operation on a non-integral type!");
1306     break;
1307   case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1308   case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1309     assert(C1->getType() == C2->getType() && "Op types should be identical!");
1310     break;
1311   case Instruction::Shl:
1312   case Instruction::Shr:
1313     assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1314     assert(C1->getType()->isInteger() &&
1315            "Tried to create a shift operation on a non-integer type!");
1316     break;
1317   default:
1318     break;
1319   }
1320 #endif
1321
1322   if (Instruction::isRelational(Opcode))
1323     return getTy(Type::BoolTy, Opcode, C1, C2);
1324   else
1325     return getTy(C1->getType(), Opcode, C1, C2);
1326 }
1327
1328 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1329                                     Constant *V1, Constant *V2) {
1330   assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1331   assert(V1->getType() == V2->getType() && "Select value types must match!");
1332   assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1333
1334   if (ReqTy == V1->getType())
1335     if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1336       return SC;        // Fold common cases
1337
1338   std::vector<Constant*> argVec(3, C);
1339   argVec[1] = V1;
1340   argVec[2] = V2;
1341   ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1342   return ExprConstants.getOrCreate(ReqTy, Key);
1343 }
1344
1345 /// getShiftTy - Return a shift left or shift right constant expr
1346 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1347                                    Constant *C1, Constant *C2) {
1348   // Check the operands for consistency first
1349   assert((Opcode == Instruction::Shl ||
1350           Opcode == Instruction::Shr) &&
1351          "Invalid opcode in binary constant expression");
1352   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1353          "Invalid operand types for Shift constant expr!");
1354
1355   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1356     return FC;          // Fold a few common cases...
1357
1358   // Look up the constant in the table first to ensure uniqueness
1359   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1360   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1361   return ExprConstants.getOrCreate(ReqTy, Key);
1362 }
1363
1364
1365 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1366                                            const std::vector<Value*> &IdxList) {
1367   assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1368          "GEP indices invalid!");
1369
1370   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1371     return FC;          // Fold a few common cases...
1372
1373   assert(isa<PointerType>(C->getType()) &&
1374          "Non-pointer type for constant GetElementPtr expression");
1375   // Look up the constant in the table first to ensure uniqueness
1376   std::vector<Constant*> ArgVec;
1377   ArgVec.reserve(IdxList.size()+1);
1378   ArgVec.push_back(C);
1379   for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1380     ArgVec.push_back(cast<Constant>(IdxList[i]));
1381   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1382   return ExprConstants.getOrCreate(ReqTy, Key);
1383 }
1384
1385 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1386                                          const std::vector<Constant*> &IdxList){
1387   // Get the result type of the getelementptr!
1388   std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1389
1390   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1391                                                      true);
1392   assert(Ty && "GEP indices invalid!");
1393   return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1394 }
1395
1396 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1397                                          const std::vector<Value*> &IdxList) {
1398   // Get the result type of the getelementptr!
1399   const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1400                                                      true);
1401   assert(Ty && "GEP indices invalid!");
1402   return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1403 }
1404
1405
1406 // destroyConstant - Remove the constant from the constant table...
1407 //
1408 void ConstantExpr::destroyConstant() {
1409   ExprConstants.remove(this);
1410   destroyConstantImpl();
1411 }
1412
1413 const char *ConstantExpr::getOpcodeName() const {
1414   return Instruction::getOpcodeName(getOpcode());
1415 }
1416
1417 /// clearAllValueMaps - This method frees all internal memory used by the
1418 /// constant subsystem, which can be used in environments where this memory
1419 /// is otherwise reported as a leak.
1420 void Constant::clearAllValueMaps() {
1421   std::vector<Constant *> Constants;
1422
1423   DoubleConstants.clear(Constants);
1424   FloatConstants.clear(Constants);
1425   SIntConstants.clear(Constants);
1426   UIntConstants.clear(Constants);
1427   AggZeroConstants.clear(Constants);
1428   ArrayConstants.clear(Constants);
1429   StructConstants.clear(Constants);
1430   PackedConstants.clear(Constants);
1431   NullPtrConstants.clear(Constants);
1432   UndefValueConstants.clear(Constants);
1433   ExprConstants.clear(Constants);
1434
1435   for (std::vector<Constant *>::iterator I = Constants.begin(), 
1436        E = Constants.end(); I != E; ++I)
1437     (*I)->dropAllReferences();
1438   for (std::vector<Constant *>::iterator I = Constants.begin(),
1439        E = Constants.end(); I != E; ++I)
1440     (*I)->destroyConstantImpl();
1441   Constants.clear();
1442 }