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