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