Rename AbstractModuleProvider -> ModuleProvider, to match the header file name,
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
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 ConstantBool *ConstantBool::True  = new ConstantBool(true);
17 ConstantBool *ConstantBool::False = new ConstantBool(false);
18
19
20 //===----------------------------------------------------------------------===//
21 //                              Constant Class
22 //===----------------------------------------------------------------------===//
23
24 // Specialize setName to take care of symbol table majik
25 void Constant::setName(const std::string &Name, SymbolTable *ST) {
26   assert(ST && "Type::setName - Must provide symbol table argument!");
27
28   if (Name.size()) ST->insert(Name, this);
29 }
30
31 void Constant::destroyConstantImpl() {
32   // When a Constant is destroyed, there may be lingering
33   // references to the constant by other constants in the constant pool.  These
34   // constants are implicitly dependent on the module that is being deleted,
35   // but they don't know that.  Because we only find out when the CPV is
36   // deleted, we must now notify all of our users (that should only be
37   // Constants) that they are, in fact, invalid now and should be deleted.
38   //
39   while (!use_empty()) {
40     Value *V = use_back();
41 #ifndef NDEBUG      // Only in -g mode...
42     if (!isa<Constant>(V))
43       std::cerr << "While deleting: " << *this
44                 << "\n\nUse still stuck around after Def is destroyed: "
45                 << *V << "\n\n";
46 #endif
47     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
48     Constant *CPV = cast<Constant>(V);
49     CPV->destroyConstant();
50
51     // The constant should remove itself from our use list...
52     assert((use_empty() || use_back() != V) && "Constant not removed!");
53   }
54
55   // Value has no outstanding references it is safe to delete it now...
56   delete this;
57 }
58
59 // Static constructor to create a '0' constant of arbitrary type...
60 Constant *Constant::getNullValue(const Type *Ty) {
61   switch (Ty->getPrimitiveID()) {
62   case Type::BoolTyID: {
63     static Constant *NullBool = ConstantBool::get(false);
64     return NullBool;
65   }
66   case Type::SByteTyID: {
67     static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
68     return NullSByte;
69   }
70   case Type::UByteTyID: {
71     static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
72     return NullUByte;
73   }
74   case Type::ShortTyID: {
75     static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
76     return NullShort;
77   }
78   case Type::UShortTyID: {
79     static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
80     return NullUShort;
81   }
82   case Type::IntTyID: {
83     static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
84     return NullInt;
85   }
86   case Type::UIntTyID: {
87     static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
88     return NullUInt;
89   }
90   case Type::LongTyID: {
91     static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
92     return NullLong;
93   }
94   case Type::ULongTyID: {
95     static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
96     return NullULong;
97   }
98
99   case Type::FloatTyID: {
100     static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
101     return NullFloat;
102   }
103   case Type::DoubleTyID: {
104     static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
105     return NullDouble;
106   }
107
108   case Type::PointerTyID: 
109     return ConstantPointerNull::get(cast<PointerType>(Ty));
110
111   case Type::StructTyID: {
112     const StructType *ST = cast<StructType>(Ty);
113     const StructType::ElementTypes &ETs = ST->getElementTypes();
114     std::vector<Constant*> Elements;
115     Elements.resize(ETs.size());
116     for (unsigned i = 0, e = ETs.size(); i != e; ++i)
117       Elements[i] = Constant::getNullValue(ETs[i]);
118     return ConstantStruct::get(ST, Elements);
119   }
120   case Type::ArrayTyID: {
121     const ArrayType *AT = cast<ArrayType>(Ty);
122     Constant *El = Constant::getNullValue(AT->getElementType());
123     unsigned NumElements = AT->getNumElements();
124     return ConstantArray::get(AT, std::vector<Constant*>(NumElements, El));
125   }
126   default:
127     // Function, Type, Label, or Opaque type?
128     assert(0 && "Cannot create a null constant of that type!");
129     return 0;
130   }
131 }
132
133 // Static constructor to create the maximum constant of an integral type...
134 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
135   switch (Ty->getPrimitiveID()) {
136   case Type::BoolTyID:   return ConstantBool::True;
137   case Type::SByteTyID:
138   case Type::ShortTyID:
139   case Type::IntTyID:
140   case Type::LongTyID: {
141     // Calculate 011111111111111... 
142     unsigned TypeBits = Ty->getPrimitiveSize()*8;
143     int64_t Val = INT64_MAX;             // All ones
144     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
145     return ConstantSInt::get(Ty, Val);
146   }
147
148   case Type::UByteTyID:
149   case Type::UShortTyID:
150   case Type::UIntTyID:
151   case Type::ULongTyID:  return getAllOnesValue(Ty);
152
153   default: return 0;
154   }
155 }
156
157 // Static constructor to create the minimum constant for an integral type...
158 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
159   switch (Ty->getPrimitiveID()) {
160   case Type::BoolTyID:   return ConstantBool::False;
161   case Type::SByteTyID:
162   case Type::ShortTyID:
163   case Type::IntTyID:
164   case Type::LongTyID: {
165      // Calculate 1111111111000000000000 
166      unsigned TypeBits = Ty->getPrimitiveSize()*8;
167      int64_t Val = -1;                    // All ones
168      Val <<= TypeBits-1;                  // Shift over to the right spot
169      return ConstantSInt::get(Ty, Val);
170   }
171
172   case Type::UByteTyID:
173   case Type::UShortTyID:
174   case Type::UIntTyID:
175   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
176
177   default: return 0;
178   }
179 }
180
181 // Static constructor to create an integral constant with all bits set
182 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
183   switch (Ty->getPrimitiveID()) {
184   case Type::BoolTyID:   return ConstantBool::True;
185   case Type::SByteTyID:
186   case Type::ShortTyID:
187   case Type::IntTyID:
188   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
189
190   case Type::UByteTyID:
191   case Type::UShortTyID:
192   case Type::UIntTyID:
193   case Type::ULongTyID: {
194     // Calculate ~0 of the right type...
195     unsigned TypeBits = Ty->getPrimitiveSize()*8;
196     uint64_t Val = ~0ULL;                // All ones
197     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
198     return ConstantUInt::get(Ty, Val);
199   }
200   default: return 0;
201   }
202 }
203
204 bool ConstantUInt::isAllOnesValue() const {
205   unsigned TypeBits = getType()->getPrimitiveSize()*8;
206   uint64_t Val = ~0ULL;                // All ones
207   Val >>= 64-TypeBits;                 // Shift out inappropriate bits
208   return getValue() == Val;
209 }
210
211
212 //===----------------------------------------------------------------------===//
213 //                            ConstantXXX Classes
214 //===----------------------------------------------------------------------===//
215
216 //===----------------------------------------------------------------------===//
217 //                             Normal Constructors
218
219 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
220   Val = V;
221 }
222
223 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
224   Val.Unsigned = V;
225 }
226
227 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
228   assert(Ty->isInteger() && Ty->isSigned() &&
229          "Illegal type for unsigned integer constant!");
230   assert(isValueValidForType(Ty, V) && "Value too large for type!");
231 }
232
233 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, 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) : Constant(Ty) {
240   assert(isValueValidForType(Ty, V) && "Value too large for type!");
241   Val = V;
242 }
243
244 ConstantArray::ConstantArray(const ArrayType *T,
245                              const std::vector<Constant*> &V) : Constant(T) {
246   Operands.reserve(V.size());
247   for (unsigned i = 0, e = V.size(); i != e; ++i) {
248     assert(V[i]->getType() == T->getElementType() ||
249            (T->isAbstract() &&
250             V[i]->getType()->getPrimitiveID() ==
251             T->getElementType()->getPrimitiveID()));
252     Operands.push_back(Use(V[i], this));
253   }
254 }
255
256 ConstantStruct::ConstantStruct(const StructType *T,
257                                const std::vector<Constant*> &V) : Constant(T) {
258   const StructType::ElementTypes &ETypes = T->getElementTypes();
259   assert(V.size() == ETypes.size() &&
260          "Invalid initializer vector for constant structure");
261   Operands.reserve(V.size());
262   for (unsigned i = 0, e = V.size(); i != e; ++i) {
263     assert((V[i]->getType() == ETypes[i] ||
264             (ETypes[i]->isAbstract() &&
265              ETypes[i]->getPrimitiveID()==V[i]->getType()->getPrimitiveID())) &&
266            "Initializer for struct element doesn't match struct element type!");
267     Operands.push_back(Use(V[i], this));
268   }
269 }
270
271 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
272   : ConstantPointer(GV->getType()) {
273   Operands.push_back(Use(GV, this));
274 }
275
276 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
277   : Constant(Ty), iType(Opcode) {
278   Operands.push_back(Use(C, this));
279 }
280
281 static bool isSetCC(unsigned Opcode) {
282   return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
283          Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
284          Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
285 }
286
287 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
288   : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
289   Operands.push_back(Use(C1, this));
290   Operands.push_back(Use(C2, this));
291 }
292
293 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
294                            const Type *DestTy)
295   : Constant(DestTy), iType(Instruction::GetElementPtr) {
296   Operands.reserve(1+IdxList.size());
297   Operands.push_back(Use(C, this));
298   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
299     Operands.push_back(Use(IdxList[i], this));
300 }
301
302
303
304 //===----------------------------------------------------------------------===//
305 //                           classof implementations
306
307 bool ConstantIntegral::classof(const Constant *CPV) {
308   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
309 }
310
311 bool ConstantInt::classof(const Constant *CPV) {
312   return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
313 }
314 bool ConstantSInt::classof(const Constant *CPV) {
315   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
316 }
317 bool ConstantUInt::classof(const Constant *CPV) {
318   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
319 }
320 bool ConstantFP::classof(const Constant *CPV) {
321   const Type *Ty = CPV->getType();
322   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
323           !isa<ConstantExpr>(CPV));
324 }
325 bool ConstantArray::classof(const Constant *CPV) {
326   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
327 }
328 bool ConstantStruct::classof(const Constant *CPV) {
329   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
330 }
331 bool ConstantPointer::classof(const Constant *CPV) {
332   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
333 }
334
335
336
337 //===----------------------------------------------------------------------===//
338 //                      isValueValidForType implementations
339
340 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
341   switch (Ty->getPrimitiveID()) {
342   default:
343     return false;         // These can't be represented as integers!!!
344
345     // Signed types...
346   case Type::SByteTyID:
347     return (Val <= INT8_MAX && Val >= INT8_MIN);
348   case Type::ShortTyID:
349     return (Val <= INT16_MAX && Val >= INT16_MIN);
350   case Type::IntTyID:
351     return (Val <= INT32_MAX && Val >= INT32_MIN);
352   case Type::LongTyID:
353     return true;          // This is the largest type...
354   }
355   assert(0 && "WTF?");
356   return false;
357 }
358
359 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
360   switch (Ty->getPrimitiveID()) {
361   default:
362     return false;         // These can't be represented as integers!!!
363
364     // Unsigned types...
365   case Type::UByteTyID:
366     return (Val <= UINT8_MAX);
367   case Type::UShortTyID:
368     return (Val <= UINT16_MAX);
369   case Type::UIntTyID:
370     return (Val <= UINT32_MAX);
371   case Type::ULongTyID:
372     return true;          // This is the largest type...
373   }
374   assert(0 && "WTF?");
375   return false;
376 }
377
378 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
379   switch (Ty->getPrimitiveID()) {
380   default:
381     return false;         // These can't be represented as floating point!
382
383     // TODO: Figure out how to test if a double can be cast to a float!
384   case Type::FloatTyID:
385   case Type::DoubleTyID:
386     return true;          // This is the largest type...
387   }
388 };
389
390 //===----------------------------------------------------------------------===//
391 //                replaceUsesOfWithOnConstant implementations
392
393 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
394                                                 bool DisableChecking) {
395   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
396
397   std::vector<Constant*> Values;
398   Values.reserve(getValues().size());  // Build replacement array...
399   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
400     Constant *Val = cast<Constant>(getValues()[i]);
401     if (Val == From) Val = cast<Constant>(To);
402     Values.push_back(Val);
403   }
404   
405   ConstantArray *Replacement = ConstantArray::get(getType(), Values);
406   assert(Replacement != this && "I didn't contain From!");
407
408   // Everyone using this now uses the replacement...
409   if (DisableChecking)
410     uncheckedReplaceAllUsesWith(Replacement);
411   else
412     replaceAllUsesWith(Replacement);
413   
414   // Delete the old constant!
415   destroyConstant();  
416 }
417
418 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
419                                                  bool DisableChecking) {
420   assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
421
422   std::vector<Constant*> Values;
423   Values.reserve(getValues().size());
424   for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
425     Constant *Val = cast<Constant>(getValues()[i]);
426     if (Val == From) Val = cast<Constant>(To);
427     Values.push_back(Val);
428   }
429   
430   ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
431   assert(Replacement != this && "I didn't contain From!");
432
433   // Everyone using this now uses the replacement...
434   if (DisableChecking)
435     uncheckedReplaceAllUsesWith(Replacement);
436   else
437     replaceAllUsesWith(Replacement);
438   
439   // Delete the old constant!
440   destroyConstant();
441 }
442
443 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
444                                                      bool DisableChecking) {
445   if (isa<GlobalValue>(To)) {
446     assert(From == getOperand(0) && "Doesn't contain from!");
447     ConstantPointerRef *Replacement =
448       ConstantPointerRef::get(cast<GlobalValue>(To));
449     
450     // Everyone using this now uses the replacement...
451     if (DisableChecking)
452       uncheckedReplaceAllUsesWith(Replacement);
453     else
454       replaceAllUsesWith(Replacement);
455     
456   } else {
457     // Just replace ourselves with the To value specified.
458     if (DisableChecking)
459       uncheckedReplaceAllUsesWith(To);
460     else
461       replaceAllUsesWith(To);
462   }
463
464   // Delete the old constant!
465   destroyConstant();
466 }
467
468 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
469                                                bool DisableChecking) {
470   assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
471   Constant *To = cast<Constant>(ToV);
472
473   Constant *Replacement = 0;
474   if (getOpcode() == Instruction::GetElementPtr) {
475     std::vector<Constant*> Indices;
476     Constant *Pointer = getOperand(0);
477     Indices.reserve(getNumOperands()-1);
478     if (Pointer == From) Pointer = To;
479     
480     for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
481       Constant *Val = getOperand(i);
482       if (Val == From) Val = To;
483       Indices.push_back(Val);
484     }
485     Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
486   } else if (getOpcode() == Instruction::Cast) {
487     assert(getOperand(0) == From && "Cast only has one use!");
488     Replacement = ConstantExpr::getCast(To, getType());
489   } else if (getNumOperands() == 2) {
490     Constant *C1 = getOperand(0);
491     Constant *C2 = getOperand(1);
492     if (C1 == From) C1 = To;
493     if (C2 == From) C2 = To;
494     Replacement = ConstantExpr::get(getOpcode(), C1, C2);
495   } else {
496     assert(0 && "Unknown ConstantExpr type!");
497     return;
498   }
499   
500   assert(Replacement != this && "I didn't contain From!");
501
502   // Everyone using this now uses the replacement...
503   if (DisableChecking)
504     uncheckedReplaceAllUsesWith(Replacement);
505   else
506     replaceAllUsesWith(Replacement);
507   
508   // Delete the old constant!
509   destroyConstant();
510 }
511
512 //===----------------------------------------------------------------------===//
513 //                      Factory Function Implementation
514
515 // ConstantCreator - A class that is used to create constants by
516 // ValueMap*.  This class should be partially specialized if there is
517 // something strange that needs to be done to interface to the ctor for the
518 // constant.
519 //
520 template<class ConstantClass, class TypeClass, class ValType>
521 struct ConstantCreator {
522   static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
523     return new ConstantClass(Ty, V);
524   }
525 };
526
527 namespace {
528   template<class ValType, class TypeClass, class ConstantClass>
529   class ValueMap {
530   protected:
531     typedef std::pair<const TypeClass*, ValType> ConstHashKey;
532     std::map<ConstHashKey, ConstantClass *> Map;
533   public:
534     // getOrCreate - Return the specified constant from the map, creating it if
535     // necessary.
536     ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
537       ConstHashKey Lookup(Ty, V);
538       typename std::map<ConstHashKey,ConstantClass *>::iterator I =
539         Map.lower_bound(Lookup);
540       if (I != Map.end() && I->first == Lookup)
541         return I->second;  // Is it in the map?
542
543       // If no preexisting value, create one now...
544       ConstantClass *Result =
545         ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
546
547       Map.insert(I, std::make_pair(ConstHashKey(Ty, V), Result));
548       return Result;
549     }
550     
551     void remove(ConstantClass *CP) {
552       // FIXME: This could be sped up a LOT.  If this gets to be a performance
553       // problem, someone should look at this.
554       for (typename std::map<ConstHashKey, ConstantClass*>::iterator
555              I = Map.begin(), E = Map.end(); I != E; ++I)
556         if (I->second == CP) {
557           Map.erase(I);
558           return;
559         }
560       assert(0 && "Constant not found in constant table!");
561     }
562   };
563 }
564
565
566
567 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
568 //
569 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
570 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
571
572 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
573   return SIntConstants.getOrCreate(Ty, V);
574 }
575
576 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
577   return UIntConstants.getOrCreate(Ty, V);
578 }
579
580 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
581   assert(V <= 127 && "Can only be used with very small positive constants!");
582   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
583   return ConstantUInt::get(Ty, V);
584 }
585
586 //---- ConstantFP::get() implementation...
587 //
588 static ValueMap<double, Type, ConstantFP> FPConstants;
589
590 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
591   return FPConstants.getOrCreate(Ty, V);
592 }
593
594 //---- ConstantArray::get() implementation...
595 //
596 static ValueMap<std::vector<Constant*>, ArrayType,
597                 ConstantArray> ArrayConstants;
598
599 ConstantArray *ConstantArray::get(const ArrayType *Ty,
600                                   const std::vector<Constant*> &V) {
601   return ArrayConstants.getOrCreate(Ty, V);
602 }
603
604 // destroyConstant - Remove the constant from the constant table...
605 //
606 void ConstantArray::destroyConstant() {
607   ArrayConstants.remove(this);
608   destroyConstantImpl();
609 }
610
611 #if 0
612 /// refineAbstractType - If this callback is invoked, then this constant is of a
613 /// derived type, change all users to use a concrete constant of the new type.
614 ///
615 void ConstantArray::refineAbstractType(const DerivedType *OldTy,
616                                        const Type *NewTy) {
617   if (OldTy == NewTy) return;
618
619   // Make everyone now use a constant of the new type...
620   std::vector<Constant*> C;
621   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
622     C.push_back(cast<Constant>(getOperand(i)));
623   Constant *New = ConstantArray::get(cast<ArrayType>(NewTy), C);
624   if (New != this) {
625     uncheckedReplaceAllUsesWith(New);
626     destroyConstant();    // This constant is now dead, destroy it.
627   }
628 }
629 #endif
630
631 // ConstantArray::get(const string&) - Return an array that is initialized to
632 // contain the specified string.  A null terminator is added to the specified
633 // string so that it may be used in a natural way...
634 //
635 ConstantArray *ConstantArray::get(const std::string &Str) {
636   std::vector<Constant*> ElementVals;
637
638   for (unsigned i = 0; i < Str.length(); ++i)
639     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
640
641   // Add a null terminator to the string...
642   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
643
644   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
645   return ConstantArray::get(ATy, ElementVals);
646 }
647
648 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
649 // then this method converts the array to an std::string and returns it.
650 // Otherwise, it asserts out.
651 //
652 std::string ConstantArray::getAsString() const {
653   assert((getType()->getElementType() == Type::UByteTy ||
654           getType()->getElementType() == Type::SByteTy) && "Not a string!");
655
656   std::string Result;
657   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
658     Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
659   return Result;
660 }
661
662
663 //---- ConstantStruct::get() implementation...
664 //
665 static ValueMap<std::vector<Constant*>, StructType, 
666                 ConstantStruct> StructConstants;
667
668 ConstantStruct *ConstantStruct::get(const StructType *Ty,
669                                     const std::vector<Constant*> &V) {
670   return StructConstants.getOrCreate(Ty, V);
671 }
672
673 // destroyConstant - Remove the constant from the constant table...
674 //
675 void ConstantStruct::destroyConstant() {
676   StructConstants.remove(this);
677   destroyConstantImpl();
678 }
679
680 #if 0
681 /// refineAbstractType - If this callback is invoked, then this constant is of a
682 /// derived type, change all users to use a concrete constant of the new type.
683 ///
684 void ConstantStruct::refineAbstractType(const DerivedType *OldTy,
685                                         const Type *NewTy) {
686   if (OldTy == NewTy) return;
687
688   // Make everyone now use a constant of the new type...
689   std::vector<Constant*> C;
690   for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
691     C.push_back(cast<Constant>(getOperand(i)));
692   Constant *New = ConstantStruct::get(cast<StructType>(NewTy), C);
693   if (New != this) {
694     uncheckedReplaceAllUsesWith(New);
695     destroyConstant();    // This constant is now dead, destroy it.
696   }
697 }
698 #endif
699
700 //---- ConstantPointerNull::get() implementation...
701 //
702
703 // ConstantPointerNull does not take extra "value" argument...
704 template<class ValType>
705 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
706   static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
707     return new ConstantPointerNull(Ty);
708   }
709 };
710
711 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
712
713 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
714   return NullPtrConstants.getOrCreate(Ty, 0);
715 }
716
717 // destroyConstant - Remove the constant from the constant table...
718 //
719 void ConstantPointerNull::destroyConstant() {
720   NullPtrConstants.remove(this);
721   destroyConstantImpl();
722 }
723
724 #if 0
725 /// refineAbstractType - If this callback is invoked, then this constant is of a
726 /// derived type, change all users to use a concrete constant of the new type.
727 ///
728 void ConstantPointerNull::refineAbstractType(const DerivedType *OldTy,
729                                              const Type *NewTy) {
730   if (OldTy == NewTy) return;
731
732   // Make everyone now use a constant of the new type...
733   Constant *New = ConstantPointerNull::get(cast<PointerType>(NewTy));
734   if (New != this) {
735     uncheckedReplaceAllUsesWith(New);
736     
737     // This constant is now dead, destroy it.
738     destroyConstant();
739   }
740 }
741 #endif
742
743
744
745 //---- ConstantPointerRef::get() implementation...
746 //
747 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
748   assert(GV->getParent() && "Global Value must be attached to a module!");
749   
750   // The Module handles the pointer reference sharing...
751   return GV->getParent()->getConstantPointerRef(GV);
752 }
753
754 // destroyConstant - Remove the constant from the constant table...
755 //
756 void ConstantPointerRef::destroyConstant() {
757   getValue()->getParent()->destroyConstantPointerRef(this);
758   destroyConstantImpl();
759 }
760
761
762 //---- ConstantExpr::get() implementations...
763 //
764 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
765
766 template<>
767 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
768   static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
769     if (V.first == Instruction::Cast)
770       return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
771     if ((V.first >= Instruction::BinaryOpsBegin &&
772          V.first < Instruction::BinaryOpsEnd) ||
773         V.first == Instruction::Shl || V.first == Instruction::Shr)
774       return new ConstantExpr(V.first, V.second[0], V.second[1]);
775     
776     assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
777     
778     // Check that the indices list is valid...
779     std::vector<Value*> ValIdxList(V.second.begin()+1, V.second.end());
780     const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList,
781                                                            true);
782     assert(DestTy && "Invalid index list for GetElementPtr expression");
783     
784     std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
785     return new ConstantExpr(V.second[0], IdxList, PointerType::get(DestTy));
786   }
787 };
788
789 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
790
791 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
792   if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
793     return FC;          // Fold a few common cases...
794
795   // Look up the constant in the table first to ensure uniqueness
796   std::vector<Constant*> argVec(1, C);
797   ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
798   return ExprConstants.getOrCreate(Ty, Key);
799 }
800
801 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
802   // Check the operands for consistency first
803   assert((Opcode >= Instruction::BinaryOpsBegin &&
804           Opcode < Instruction::BinaryOpsEnd) &&
805          "Invalid opcode in binary constant expression");
806   assert(C1->getType() == C2->getType() &&
807          "Operand types in binary constant expression should match");
808   
809   if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
810     return FC;          // Fold a few common cases...
811
812   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
813   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
814   return ExprConstants.getOrCreate(C1->getType(), Key);
815 }
816
817 /// getShift - Return a shift left or shift right constant expr
818 Constant *ConstantExpr::getShift(unsigned Opcode, Constant *C1, Constant *C2) {
819   // Check the operands for consistency first
820   assert((Opcode == Instruction::Shl ||
821           Opcode == Instruction::Shr) &&
822          "Invalid opcode in binary constant expression");
823   assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
824          "Invalid operand types for Shift constant expr!");
825
826   if (Constant *FC = ConstantFoldShiftInstruction(Opcode, C1, C2))
827     return FC;          // Fold a few common cases...
828
829   // Look up the constant in the table first to ensure uniqueness
830   std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
831   ExprMapKeyType Key = std::make_pair(Opcode, argVec);
832   return ExprConstants.getOrCreate(C1->getType(), Key);
833 }
834
835
836 Constant *ConstantExpr::getGetElementPtr(Constant *C,
837                                          const std::vector<Constant*> &IdxList){
838   if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
839     return FC;          // Fold a few common cases...
840   const Type *Ty = C->getType();
841   assert(isa<PointerType>(Ty) &&
842          "Non-pointer type for constant GetElementPtr expression");
843
844   // Look up the constant in the table first to ensure uniqueness
845   std::vector<Constant*> argVec(1, C);
846   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
847   
848   const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
849   return ExprConstants.getOrCreate(Ty, Key);
850 }
851
852 // destroyConstant - Remove the constant from the constant table...
853 //
854 void ConstantExpr::destroyConstant() {
855   ExprConstants.remove(this);
856   destroyConstantImpl();
857 }
858
859 #if 0
860 /// refineAbstractType - If this callback is invoked, then this constant is of a
861 /// derived type, change all users to use a concrete constant of the new type.
862 ///
863 void ConstantExpr::refineAbstractType(const DerivedType *OldTy,
864                                       const Type *NewTy) {
865   if (OldTy == NewTy) return;
866
867   // FIXME: These need to use a lower-level implementation method, because the
868   // ::get methods intuit the type of the result based on the types of the
869   // operands.  The operand types may not have had their types resolved yet.
870   //
871   Constant *New;
872   if (getOpcode() == Instruction::Cast) {
873     New = getCast(getOperand(0), NewTy);
874   } else if (getOpcode() >= Instruction::BinaryOpsBegin &&
875              getOpcode() < Instruction::BinaryOpsEnd) {
876     New = get(getOpcode(), getOperand(0), getOperand(0));
877   } else if (getOpcode() == Instruction::Shl || getOpcode() ==Instruction::Shr){
878     New = getShift(getOpcode(), getOperand(0), getOperand(0));
879   } else {
880     assert(getOpcode() == Instruction::GetElementPtr);
881
882     // Make everyone now use a constant of the new type...
883     std::vector<Constant*> C;
884     for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
885       C.push_back(cast<Constant>(getOperand(i)));
886     New = ConstantExpr::getGetElementPtr(getOperand(0), C);
887   }
888   if (New != this) {
889     uncheckedReplaceAllUsesWith(New);
890     destroyConstant();    // This constant is now dead, destroy it.
891   }
892 }
893 #endif
894
895
896
897
898 const char *ConstantExpr::getOpcodeName() const {
899   return Instruction::getOpcodeName(getOpcode());
900 }
901
902 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
903   // Uses of constant pointer refs are global values, not constants!
904   if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
905     GlobalValue *NewGV = cast<GlobalValue>(NewV);
906     GlobalValue *OldGV = CPR->getValue();
907
908     assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
909     Operands[0] = NewGV;
910     OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
911     return 1;
912   } else {
913     Constant *NewC = cast<Constant>(NewV);
914     unsigned NumReplaced = 0;
915     for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
916       if (Operands[i] == OldV) {
917         ++NumReplaced;
918         Operands[i] = NewC;
919       }
920     return NumReplaced;
921   }
922 }