Add support for reading and writing pointersize/endianness to and from bytecode
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes -----------------*- C++ -*--=//
2 //
3 // This file implements the Constant* classes...
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Constants.h"
8 #include "llvm/ConstantHandling.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/SymbolTable.h"
12 #include "llvm/Module.h"
13 #include "Support/StringExtras.h"
14 #include <algorithm>
15
16 using std::map;
17 using std::pair;
18 using std::make_pair;
19 using std::vector;
20
21 ConstantBool *ConstantBool::True  = new ConstantBool(true);
22 ConstantBool *ConstantBool::False = new ConstantBool(false);
23
24
25 //===----------------------------------------------------------------------===//
26 //                              Constant Class
27 //===----------------------------------------------------------------------===//
28
29 // Specialize setName to take care of symbol table majik
30 void Constant::setName(const std::string &Name, SymbolTable *ST) {
31   assert(ST && "Type::setName - Must provide symbol table argument!");
32
33   if (Name.size()) ST->insert(Name, this);
34 }
35
36 void Constant::destroyConstantImpl() {
37   // When a Constant is destroyed, there may be lingering
38   // references to the constant by other constants in the constant pool.  These
39   // constants are implicitly dependant on the module that is being deleted,
40   // but they don't know that.  Because we only find out when the CPV is
41   // deleted, we must now notify all of our users (that should only be
42   // Constants) that they are, in fact, invalid now and should be deleted.
43   //
44   while (!use_empty()) {
45     Value *V = use_back();
46 #ifndef NDEBUG      // Only in -g mode...
47     if (!isa<Constant>(V))
48       std::cerr << "While deleting: " << *this
49                 << "\n\nUse still stuck around after Def is destroyed: "
50                 << *V << "\n\n";
51 #endif
52     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
53     Constant *CPV = cast<Constant>(V);
54     CPV->destroyConstant();
55
56     // The constant should remove itself from our use list...
57     assert((use_empty() || use_back() != V) && "Constant not removed!");
58   }
59
60   // Value has no outstanding references it is safe to delete it now...
61   delete this;
62 }
63
64 // Static constructor to create a '0' constant of arbitrary type...
65 Constant *Constant::getNullValue(const Type *Ty) {
66   switch (Ty->getPrimitiveID()) {
67   case Type::BoolTyID:   return ConstantBool::get(false);
68   case Type::SByteTyID:
69   case Type::ShortTyID:
70   case Type::IntTyID:
71   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
72
73   case Type::UByteTyID:
74   case Type::UShortTyID:
75   case Type::UIntTyID:
76   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
77
78   case Type::FloatTyID:
79   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
80
81   case Type::PointerTyID: 
82     return ConstantPointerNull::get(cast<PointerType>(Ty));
83   case Type::StructTyID: {
84     const StructType *ST = cast<StructType>(Ty);
85
86     const StructType::ElementTypes &ETs = ST->getElementTypes();
87     std::vector<Constant*> Elements;
88     Elements.resize(ETs.size());
89     for (unsigned i = 0, e = ETs.size(); i != e; ++i)
90       Elements[i] = Constant::getNullValue(ETs[i]);
91     return ConstantStruct::get(ST, Elements);
92   }
93   case Type::ArrayTyID: {
94     const ArrayType *AT = cast<ArrayType>(Ty);
95     Constant *El = Constant::getNullValue(AT->getElementType());
96     unsigned NumElements = AT->getNumElements();
97     return ConstantArray::get(AT, std::vector<Constant*>(NumElements, El));
98   }
99   default:
100     // Function, Type, Label, or Opaque type?
101     assert(0 && "Cannot create a null constant of that type!");
102     return 0;
103   }
104 }
105
106 // Static constructor to create the maximum constant of an integral type...
107 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
108   switch (Ty->getPrimitiveID()) {
109   case Type::BoolTyID:   return ConstantBool::True;
110   case Type::SByteTyID:
111   case Type::ShortTyID:
112   case Type::IntTyID:
113   case Type::LongTyID: {
114     // Calculate 011111111111111... 
115     unsigned TypeBits = Ty->getPrimitiveSize()*8;
116     int64_t Val = INT64_MAX;             // All ones
117     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
118     return ConstantSInt::get(Ty, Val);
119   }
120
121   case Type::UByteTyID:
122   case Type::UShortTyID:
123   case Type::UIntTyID:
124   case Type::ULongTyID:  return getAllOnesValue(Ty);
125
126   default: return 0;
127   }
128 }
129
130 // Static constructor to create the minimum constant for an integral type...
131 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
132   switch (Ty->getPrimitiveID()) {
133   case Type::BoolTyID:   return ConstantBool::False;
134   case Type::SByteTyID:
135   case Type::ShortTyID:
136   case Type::IntTyID:
137   case Type::LongTyID: {
138      // Calculate 1111111111000000000000 
139      unsigned TypeBits = Ty->getPrimitiveSize()*8;
140      int64_t Val = -1;                    // All ones
141      Val <<= TypeBits-1;                  // Shift over to the right spot
142      return ConstantSInt::get(Ty, Val);
143   }
144
145   case Type::UByteTyID:
146   case Type::UShortTyID:
147   case Type::UIntTyID:
148   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
149
150   default: return 0;
151   }
152 }
153
154 // Static constructor to create an integral constant with all bits set
155 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
156   switch (Ty->getPrimitiveID()) {
157   case Type::BoolTyID:   return ConstantBool::True;
158   case Type::SByteTyID:
159   case Type::ShortTyID:
160   case Type::IntTyID:
161   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
162
163   case Type::UByteTyID:
164   case Type::UShortTyID:
165   case Type::UIntTyID:
166   case Type::ULongTyID: {
167     // Calculate ~0 of the right type...
168     unsigned TypeBits = Ty->getPrimitiveSize()*8;
169     uint64_t Val = ~0ULL;                // All ones
170     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
171     return ConstantUInt::get(Ty, Val);
172   }
173   default: return 0;
174   }
175 }
176
177 bool ConstantUInt::isAllOnesValue() const {
178   unsigned TypeBits = getType()->getPrimitiveSize()*8;
179   uint64_t Val = ~0ULL;                // All ones
180   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
181   return getValue() == Val;
182 }
183
184
185 //===----------------------------------------------------------------------===//
186 //                            ConstantXXX Classes
187 //===----------------------------------------------------------------------===//
188
189 //===----------------------------------------------------------------------===//
190 //                             Normal Constructors
191
192 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
193   Val = V;
194 }
195
196 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
197   Val.Unsigned = V;
198 }
199
200 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
201   assert(Ty->isInteger() && Ty->isSigned() &&
202          "Illegal type for unsigned integer constant!");
203   assert(isValueValidForType(Ty, V) && "Value too large for type!");
204 }
205
206 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
207   assert(Ty->isInteger() && Ty->isUnsigned() &&
208          "Illegal type for unsigned integer constant!");
209   assert(isValueValidForType(Ty, V) && "Value too large for type!");
210 }
211
212 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
213   assert(isValueValidForType(Ty, V) && "Value too large for type!");
214   Val = V;
215 }
216
217 ConstantArray::ConstantArray(const ArrayType *T,
218                              const std::vector<Constant*> &V) : Constant(T) {
219   Operands.reserve(V.size());
220   for (unsigned i = 0, e = V.size(); i != e; ++i) {
221     assert(V[i]->getType() == T->getElementType());
222     Operands.push_back(Use(V[i], this));
223   }
224 }
225
226 ConstantStruct::ConstantStruct(const StructType *T,
227                                const std::vector<Constant*> &V) : Constant(T) {
228   const StructType::ElementTypes &ETypes = T->getElementTypes();
229   assert(V.size() == ETypes.size() &&
230          "Invalid initializer vector for constant structure");
231   Operands.reserve(V.size());
232   for (unsigned i = 0, e = V.size(); i != e; ++i) {
233     assert(V[i]->getType() == ETypes[i]);
234     Operands.push_back(Use(V[i], this));
235   }
236 }
237
238 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
239   : ConstantPointer(GV->getType()) {
240   Operands.push_back(Use(GV, this));
241 }
242
243 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
244   : Constant(Ty), iType(Opcode) {
245   Operands.push_back(Use(C, this));
246 }
247
248 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
249   : Constant(C1->getType()), iType(Opcode) {
250   Operands.push_back(Use(C1, this));
251   Operands.push_back(Use(C2, this));
252 }
253
254 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
255                            const Type *DestTy)
256   : Constant(DestTy), iType(Instruction::GetElementPtr) {
257   Operands.reserve(1+IdxList.size());
258   Operands.push_back(Use(C, this));
259   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
260     Operands.push_back(Use(IdxList[i], this));
261 }
262
263
264
265 //===----------------------------------------------------------------------===//
266 //                           classof implementations
267
268 bool ConstantIntegral::classof(const Constant *CPV) {
269   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
270 }
271
272 bool ConstantInt::classof(const Constant *CPV) {
273   return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
274 }
275 bool ConstantSInt::classof(const Constant *CPV) {
276   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
277 }
278 bool ConstantUInt::classof(const Constant *CPV) {
279   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
280 }
281 bool ConstantFP::classof(const Constant *CPV) {
282   const Type *Ty = CPV->getType();
283   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
284           !isa<ConstantExpr>(CPV));
285 }
286 bool ConstantArray::classof(const Constant *CPV) {
287   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
288 }
289 bool ConstantStruct::classof(const Constant *CPV) {
290   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
291 }
292 bool ConstantPointer::classof(const Constant *CPV) {
293   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
294 }
295
296
297
298 //===----------------------------------------------------------------------===//
299 //                      isValueValidForType implementations
300
301 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
302   switch (Ty->getPrimitiveID()) {
303   default:
304     return false;         // These can't be represented as integers!!!
305
306     // Signed types...
307   case Type::SByteTyID:
308     return (Val <= INT8_MAX && Val >= INT8_MIN);
309   case Type::ShortTyID:
310     return (Val <= INT16_MAX && Val >= INT16_MIN);
311   case Type::IntTyID:
312     return (Val <= INT32_MAX && Val >= INT32_MIN);
313   case Type::LongTyID:
314     return true;          // This is the largest type...
315   }
316   assert(0 && "WTF?");
317   return false;
318 }
319
320 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
321   switch (Ty->getPrimitiveID()) {
322   default:
323     return false;         // These can't be represented as integers!!!
324
325     // Unsigned types...
326   case Type::UByteTyID:
327     return (Val <= UINT8_MAX);
328   case Type::UShortTyID:
329     return (Val <= UINT16_MAX);
330   case Type::UIntTyID:
331     return (Val <= UINT32_MAX);
332   case Type::ULongTyID:
333     return true;          // This is the largest type...
334   }
335   assert(0 && "WTF?");
336   return false;
337 }
338
339 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
340   switch (Ty->getPrimitiveID()) {
341   default:
342     return false;         // These can't be represented as floating point!
343
344     // TODO: Figure out how to test if a double can be cast to a float!
345   case Type::FloatTyID:
346     /*
347     return (Val <= UINT8_MAX);
348     */
349   case Type::DoubleTyID:
350     return true;          // This is the largest type...
351   }
352 };
353
354 //===----------------------------------------------------------------------===//
355 //                replaceUsesOfWithOnConstant implementations
356
357 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To) {
358   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
359
360   std::vector<Constant*> Values;
361   Values.reserve(getValues().size());  // Build replacement array...
362   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
363     Constant *Val = cast<Constant>(getValues()[i]);
364     if (Val == From) Val = cast<Constant>(To);
365     Values.push_back(Val);
366   }
367   
368   ConstantArray *Replacement = ConstantArray::get(getType(), Values);
369   assert(Replacement != this && "I didn't contain From!");
370
371   // Everyone using this now uses the replacement...
372   replaceAllUsesWith(Replacement);
373   
374   // Delete the old constant!
375   destroyConstant();  
376 }
377
378 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To) {
379   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
380
381   std::vector<Constant*> Values;
382   Values.reserve(getValues().size());
383   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
384     Constant *Val = cast<Constant>(getValues()[i]);
385     if (Val == From) Val = cast<Constant>(To);
386     Values.push_back(Val);
387   }
388   
389   ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
390   assert(Replacement != this && "I didn't contain From!");
391
392   // Everyone using this now uses the replacement...
393   replaceAllUsesWith(Replacement);
394   
395   // Delete the old constant!
396   destroyConstant();
397 }
398
399 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To) {
400   if (isa<GlobalValue>(To)) {
401     assert(From == getOperand(0) && "Doesn't contain from!");
402     ConstantPointerRef *Replacement =
403       ConstantPointerRef::get(cast<GlobalValue>(To));
404     
405     // Everyone using this now uses the replacement...
406     replaceAllUsesWith(Replacement);
407     
408     // Delete the old constant!
409     destroyConstant();
410   } else {
411     // Just replace ourselves with the To value specified.
412     replaceAllUsesWith(To);
413   
414     // Delete the old constant!
415     destroyConstant();
416   }
417 }
418
419 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *To) {
420   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
421
422   Constant *Replacement = 0;
423   if (getOpcode() == Instruction::GetElementPtr) {
424     std::vector<Constant*> Indices;
425     Constant *Pointer = cast<Constant>(getOperand(0));
426     Indices.reserve(getNumOperands()-1);
427     if (Pointer == From) Pointer = cast<Constant>(To);
428     
429     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
430       Constant *Val = cast<Constant>(getOperand(i));
431       if (Val == From) Val = cast<Constant>(To);
432       Indices.push_back(Val);
433     }
434     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
435   } else if (getOpcode() == Instruction::Cast) {
436     assert(getOperand(0) == From && "Cast only has one use!");
437     Replacement = ConstantExpr::getCast(cast<Constant>(To), getType());
438   } else if (getNumOperands() == 2) {
439     Constant *C1 = cast<Constant>(getOperand(0));
440     Constant *C2 = cast<Constant>(getOperand(1));
441     if (C1 == From) C1 = cast<Constant>(To);
442     if (C2 == From) C2 = cast<Constant>(To);
443     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
444   } else {
445     assert(0 && "Unknown ConstantExpr type!");
446     return;
447   }
448   
449   assert(Replacement != this && "I didn't contain From!");
450
451   // Everyone using this now uses the replacement...
452   replaceAllUsesWith(Replacement);
453   
454   // Delete the old constant!
455   destroyConstant();
456 }
457
458
459
460 //===----------------------------------------------------------------------===//
461 //                      Factory Function Implementation
462
463 template<class ValType, class ConstantClass>
464 struct ValueMap {
465   typedef pair<const Type*, ValType> ConstHashKey;
466   map<ConstHashKey, ConstantClass *> Map;
467
468   inline ConstantClass *get(const Type *Ty, ValType V) {
469     typename map<ConstHashKey,ConstantClass *>::iterator I =
470       Map.find(ConstHashKey(Ty, V));
471     return (I != Map.end()) ? I->second : 0;
472   }
473
474   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
475     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
476   }
477
478   inline void remove(ConstantClass *CP) {
479     for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
480                                                       E = Map.end(); I != E;++I)
481       if (I->second == CP) {
482         Map.erase(I);
483         return;
484       }
485   }
486 };
487
488 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
489 //
490 static ValueMap<uint64_t, ConstantInt> IntConstants;
491
492 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
493   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
494   if (!Result)   // If no preexisting value, create one now...
495     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
496   return Result;
497 }
498
499 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
500   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
501   if (!Result)   // If no preexisting value, create one now...
502     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
503   return Result;
504 }
505
506 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
507   assert(V <= 127 && "Can only be used with very small positive constants!");
508   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
509   return ConstantUInt::get(Ty, V);
510 }
511
512 //---- ConstantFP::get() implementation...
513 //
514 static ValueMap<double, ConstantFP> FPConstants;
515
516 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
517   ConstantFP *Result = FPConstants.get(Ty, V);
518   if (!Result)   // If no preexisting value, create one now...
519     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
520   return Result;
521 }
522
523 //---- ConstantArray::get() implementation...
524 //
525 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
526
527 ConstantArray *ConstantArray::get(const ArrayType *Ty,
528                                   const std::vector<Constant*> &V) {
529   ConstantArray *Result = ArrayConstants.get(Ty, V);
530   if (!Result)   // If no preexisting value, create one now...
531     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
532   return Result;
533 }
534
535 // ConstantArray::get(const string&) - Return an array that is initialized to
536 // contain the specified string.  A null terminator is added to the specified
537 // string so that it may be used in a natural way...
538 //
539 ConstantArray *ConstantArray::get(const std::string &Str) {
540   std::vector<Constant*> ElementVals;
541
542   for (unsigned i = 0; i < Str.length(); ++i)
543     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
544
545   // Add a null terminator to the string...
546   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
547
548   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
549   return ConstantArray::get(ATy, ElementVals);
550 }
551
552
553 // destroyConstant - Remove the constant from the constant table...
554 //
555 void ConstantArray::destroyConstant() {
556   ArrayConstants.remove(this);
557   destroyConstantImpl();
558 }
559
560 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
561 // then this method converts the array to an std::string and returns it.
562 // Otherwise, it asserts out.
563 //
564 std::string ConstantArray::getAsString() const {
565   std::string Result;
566   if (getType()->getElementType() == Type::SByteTy)
567     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
568       Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
569   else {
570     assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
571     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
572       Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
573   }
574   return Result;
575 }
576
577
578 //---- ConstantStruct::get() implementation...
579 //
580 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
581
582 ConstantStruct *ConstantStruct::get(const StructType *Ty,
583                                     const std::vector<Constant*> &V) {
584   ConstantStruct *Result = StructConstants.get(Ty, V);
585   if (!Result)   // If no preexisting value, create one now...
586     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
587   return Result;
588 }
589
590 // destroyConstant - Remove the constant from the constant table...
591 //
592 void ConstantStruct::destroyConstant() {
593   StructConstants.remove(this);
594   destroyConstantImpl();
595 }
596
597
598 //---- ConstantPointerNull::get() implementation...
599 //
600 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
601
602 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
603   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
604   if (!Result)   // If no preexisting value, create one now...
605     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
606   return Result;
607 }
608
609 // destroyConstant - Remove the constant from the constant table...
610 //
611 void ConstantPointerNull::destroyConstant() {
612   NullPtrConstants.remove(this);
613   destroyConstantImpl();
614 }
615
616
617 //---- ConstantPointerRef::get() implementation...
618 //
619 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
620   assert(GV->getParent() && "Global Value must be attached to a module!");
621   
622   // The Module handles the pointer reference sharing...
623   return GV->getParent()->getConstantPointerRef(GV);
624 }
625
626 // destroyConstant - Remove the constant from the constant table...
627 //
628 void ConstantPointerRef::destroyConstant() {
629   getValue()->getParent()->destroyConstantPointerRef(this);
630   destroyConstantImpl();
631 }
632
633
634 //---- ConstantExpr::get() implementations...
635 //
636 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
637 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
638
639 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
640   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
641     return FC;          // Fold a few common cases...
642
643   // Look up the constant in the table first to ensure uniqueness
644   vector<Constant*> argVec(1, C);
645   const ExprMapKeyType &Key = make_pair(Instruction::Cast, argVec);
646   ConstantExpr *Result = ExprConstants.get(Ty, Key);
647   if (Result) return Result;
648   
649   // Its not in the table so create a new one and put it in the table.
650   Result = new ConstantExpr(Instruction::Cast, C, Ty);
651   ExprConstants.add(Ty, Key, Result);
652   return Result;
653 }
654
655 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
656   
657   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
658     return FC;          // Fold a few common cases...
659
660   // Look up the constant in the table first to ensure uniqueness
661   vector<Constant*> argVec(1, C1); argVec.push_back(C2);
662   const ExprMapKeyType &Key = make_pair(Opcode, argVec);
663   ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
664   if (Result) return Result;
665   
666   // Its not in the table so create a new one and put it in the table.
667   // Check the operands for consistency first
668   assert((Opcode >= Instruction::BinaryOpsBegin &&
669           Opcode < Instruction::BinaryOpsEnd) &&
670          "Invalid opcode in binary constant expression");
671
672   assert(C1->getType() == C2->getType() &&
673          "Operand types in binary constant expression should match");
674   
675   Result = new ConstantExpr(Opcode, C1, C2);
676   ExprConstants.add(C1->getType(), Key, Result);
677   return Result;
678 }
679
680 Constant *ConstantExpr::getGetElementPtr(Constant *C,
681                                          const std::vector<Constant*> &IdxList){
682   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
683     return FC;          // Fold a few common cases...
684   const Type *Ty = C->getType();
685
686   // Look up the constant in the table first to ensure uniqueness
687   vector<Constant*> argVec(1, C);
688   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
689   
690   const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
691   ConstantExpr *Result = ExprConstants.get(Ty, Key);
692   if (Result) return Result;
693
694   // Its not in the table so create a new one and put it in the table.
695   // Check the operands for consistency first
696   // 
697   assert(isa<PointerType>(Ty) &&
698          "Non-pointer type for constant GelElementPtr expression");
699
700   // Check that the indices list is valid...
701   std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
702   const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
703   assert(DestTy && "Invalid index list for constant GelElementPtr expression");
704   
705   Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
706   ExprConstants.add(Ty, Key, Result);
707   return Result;
708 }
709
710 // destroyConstant - Remove the constant from the constant table...
711 //
712 void ConstantExpr::destroyConstant() {
713   ExprConstants.remove(this);
714   destroyConstantImpl();
715 }
716
717 const char *ConstantExpr::getOpcodeName() const {
718   return Instruction::getOpcodeName(getOpcode());
719 }
720
721 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
722   // Uses of constant pointer refs are global values, not constants!
723   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
724     GlobalValue *NewGV = cast<GlobalValue>(NewV);
725     GlobalValue *OldGV = CPR->getValue();
726
727     assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
728
729     OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
730     Operands[0] = NewGV;
731     return 1;
732   } else {
733     Constant *NewC = cast<Constant>(NewV);
734     unsigned NumReplaced = 0;
735     for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
736       if (Operands[i] == OldV) {
737         ++NumReplaced;
738         Operands[i] = NewC;
739       }
740     return NumReplaced;
741   }
742 }