410276683d15db17cf283ce2e7da5cfd90639045
[oota-llvm.git] / lib / VMCore / Constants.cpp
1 //===-- ConstantVals.cpp - Implement Constant nodes --------------*- C++ -*--=//
2 //
3 // This file implements the Constant* classes...
4 //
5 //===----------------------------------------------------------------------===//
6
7 #define __STDC_LIMIT_MACROS           // Get defs for INT64_MAX and friends...
8 #include "llvm/ConstantVals.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/GlobalValue.h"
12 #include "llvm/Module.h"
13 #include "llvm/Analysis/SlotCalculator.h"
14 #include "Support/StringExtras.h"
15 #include <algorithm>
16
17 using std::map;
18 using std::pair;
19 using std::make_pair;
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 // Static constructor to create a '0' constant of arbitrary type...
37 Constant *Constant::getNullConstant(const Type *Ty) {
38   switch (Ty->getPrimitiveID()) {
39   case Type::BoolTyID:   return ConstantBool::get(false);
40   case Type::SByteTyID:
41   case Type::ShortTyID:
42   case Type::IntTyID:
43   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
44
45   case Type::UByteTyID:
46   case Type::UShortTyID:
47   case Type::UIntTyID:
48   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
49
50   case Type::FloatTyID:
51   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
52
53   case Type::PointerTyID: 
54     return ConstantPointerNull::get(cast<PointerType>(Ty));
55   default:
56     return 0;
57   }
58 }
59
60 #ifndef NDEBUG
61 #include "llvm/Assembly/Writer.h"
62 using std::cerr;
63 #endif
64
65 void Constant::destroyConstantImpl() {
66   // When a Constant is destroyed, there may be lingering
67   // references to the constant by other constants in the constant pool.  These
68   // constants are implicitly dependant on the module that is being deleted,
69   // but they don't know that.  Because we only find out when the CPV is
70   // deleted, we must now notify all of our users (that should only be
71   // Constants) that they are, in fact, invalid now and should be deleted.
72   //
73   while (!use_empty()) {
74     Value *V = use_back();
75 #ifndef NDEBUG      // Only in -g mode...
76     if (!isa<Constant>(V)) {
77       cerr << "While deleting: " << this << "\n";
78       cerr << "Use still stuck around after Def is destroyed: " << V << "\n";
79     }
80 #endif
81     assert(isa<Constant>(V) && "References remain to ConstantPointerRef!");
82     Constant *CPV = cast<Constant>(V);
83     CPV->destroyConstant();
84
85     // The constant should remove itself from our use list...
86     assert((use_empty() || use_back() == V) && "Constant not removed!");
87   }
88
89   // Value has no outstanding references it is safe to delete it now...
90   delete this;
91 }
92
93 //===----------------------------------------------------------------------===//
94 //                            ConstantXXX Classes
95 //===----------------------------------------------------------------------===//
96
97 //===----------------------------------------------------------------------===//
98 //                             Normal Constructors
99
100 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
101   Val = V;
102 }
103
104 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
105   Val.Unsigned = V;
106 }
107
108 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
109   assert(isValueValidForType(Ty, V) && "Value too large for type!");
110 }
111
112 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
113   assert(isValueValidForType(Ty, V) && "Value too large for type!");
114 }
115
116 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
117   assert(isValueValidForType(Ty, V) && "Value too large for type!");
118   Val = V;
119 }
120
121 ConstantArray::ConstantArray(const ArrayType *T,
122                              const std::vector<Constant*> &V) : Constant(T) {
123   for (unsigned i = 0; i < V.size(); i++) {
124     assert(V[i]->getType() == T->getElementType());
125     Operands.push_back(Use(V[i], this));
126   }
127 }
128
129 ConstantStruct::ConstantStruct(const StructType *T,
130                                const std::vector<Constant*> &V) : Constant(T) {
131   const StructType::ElementTypes &ETypes = T->getElementTypes();
132   
133   for (unsigned i = 0; i < V.size(); i++) {
134     assert(V[i]->getType() == ETypes[i]);
135     Operands.push_back(Use(V[i], this));
136   }
137 }
138
139 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
140   : ConstantPointer(GV->getType()) {
141   Operands.push_back(Use(GV, this));
142 }
143
144
145
146 //===----------------------------------------------------------------------===//
147 //                          getStrValue implementations
148
149 std::string ConstantBool::getStrValue() const {
150   return Val ? "true" : "false";
151 }
152
153 std::string ConstantSInt::getStrValue() const {
154   return itostr(Val.Signed);
155 }
156
157 std::string ConstantUInt::getStrValue() const {
158   return utostr(Val.Unsigned);
159 }
160
161 // ConstantFP::getStrValue - We would like to output the FP constant value in
162 // exponential notation, but we cannot do this if doing so will lose precision.
163 // Check here to make sure that we only output it in exponential format if we
164 // can parse the value back and get the same value.
165 //
166 std::string ConstantFP::getStrValue() const {
167   std::string StrVal = ftostr(Val);
168   double TestVal = atof(StrVal.c_str());  // Reparse stringized version!
169   if (TestVal == Val)
170     return StrVal;
171
172   // Otherwise we could not reparse it to exactly the same value, so we must
173   // output the string in hexadecimal format!
174   //
175   // Behave nicely in the face of C TBAA rules... see:
176   // http://www.nullstone.com/htmls/category/aliastyp.htm
177   //
178   char *Ptr = (char*)&Val;
179   assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
180          "assuming that double is 64 bits!");
181   return "0x"+utohexstr(*(uint64_t*)Ptr);
182 }
183
184 std::string ConstantArray::getStrValue() const {
185   std::string Result;
186   
187   // As a special case, print the array as a string if it is an array of
188   // ubytes or an array of sbytes with positive values.
189   // 
190   const Type *ETy = cast<ArrayType>(getType())->getElementType();
191   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
192
193   if (ETy == Type::SByteTy) {
194     for (unsigned i = 0; i < Operands.size(); ++i)
195       if (ETy == Type::SByteTy &&
196           cast<ConstantSInt>(Operands[i])->getValue() < 0) {
197         isString = false;
198         break;
199       }
200   }
201
202   if (isString) {
203     Result = "c\"";
204     for (unsigned i = 0; i < Operands.size(); ++i) {
205       unsigned char C = (ETy == Type::SByteTy) ?
206         (unsigned char)cast<ConstantSInt>(Operands[i])->getValue() :
207         (unsigned char)cast<ConstantUInt>(Operands[i])->getValue();
208
209       if (isprint(C)) {
210         Result += C;
211       } else {
212         Result += '\\';
213         Result += ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
214         Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
215       }
216     }
217     Result += "\"";
218
219   } else {
220     Result = "[";
221     if (Operands.size()) {
222       Result += " " + Operands[0]->getType()->getDescription() + 
223                 " " + cast<Constant>(Operands[0])->getStrValue();
224       for (unsigned i = 1; i < Operands.size(); i++)
225         Result += ", " + Operands[i]->getType()->getDescription() + 
226                   " " + cast<Constant>(Operands[i])->getStrValue();
227     }
228     Result += " ]";
229   }
230   
231   return Result;
232 }
233
234 std::string ConstantStruct::getStrValue() const {
235   std::string Result = "{";
236   if (Operands.size()) {
237     Result += " " + Operands[0]->getType()->getDescription() + 
238               " " + cast<Constant>(Operands[0])->getStrValue();
239     for (unsigned i = 1; i < Operands.size(); i++)
240       Result += ", " + Operands[i]->getType()->getDescription() + 
241                 " " + cast<Constant>(Operands[i])->getStrValue();
242   }
243
244   return Result + " }";
245 }
246
247 std::string ConstantPointerNull::getStrValue() const {
248   return "null";
249 }
250
251 std::string ConstantPointerRef::getStrValue() const {
252   const GlobalValue *V = getValue();
253   if (V->hasName()) return "%" + V->getName();
254
255   SlotCalculator *Table = new SlotCalculator(V->getParent(), true);
256   int Slot = Table->getValSlot(V);
257   delete Table;
258
259   if (Slot >= 0) return std::string(" %") + itostr(Slot);
260   else return "<pointer reference badref>";
261 }
262
263
264 //===----------------------------------------------------------------------===//
265 //                           classof implementations
266
267 bool ConstantInt::classof(const Constant *CPV) {
268   return CPV->getType()->isIntegral();
269 }
270 bool ConstantSInt::classof(const Constant *CPV) {
271   return CPV->getType()->isSigned();
272 }
273 bool ConstantUInt::classof(const Constant *CPV) {
274   return CPV->getType()->isUnsigned();
275 }
276 bool ConstantFP::classof(const Constant *CPV) {
277   const Type *Ty = CPV->getType();
278   return Ty == Type::FloatTy || Ty == Type::DoubleTy;
279 }
280 bool ConstantArray::classof(const Constant *CPV) {
281   return isa<ArrayType>(CPV->getType());
282 }
283 bool ConstantStruct::classof(const Constant *CPV) {
284   return isa<StructType>(CPV->getType());
285 }
286 bool ConstantPointer::classof(const Constant *CPV) {
287   return isa<PointerType>(CPV->getType());
288 }
289
290
291 //===----------------------------------------------------------------------===//
292 //                      isValueValidForType implementations
293
294 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
295   switch (Ty->getPrimitiveID()) {
296   default:
297     return false;         // These can't be represented as integers!!!
298
299     // Signed types...
300   case Type::SByteTyID:
301     return (Val <= INT8_MAX && Val >= INT8_MIN);
302   case Type::ShortTyID:
303     return (Val <= INT16_MAX && Val >= INT16_MIN);
304   case Type::IntTyID:
305     return (Val <= INT32_MAX && Val >= INT32_MIN);
306   case Type::LongTyID:
307     return true;          // This is the largest type...
308   }
309   assert(0 && "WTF?");
310   return false;
311 }
312
313 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
314   switch (Ty->getPrimitiveID()) {
315   default:
316     return false;         // These can't be represented as integers!!!
317
318     // Unsigned types...
319   case Type::UByteTyID:
320     return (Val <= UINT8_MAX);
321   case Type::UShortTyID:
322     return (Val <= UINT16_MAX);
323   case Type::UIntTyID:
324     return (Val <= UINT32_MAX);
325   case Type::ULongTyID:
326     return true;          // This is the largest type...
327   }
328   assert(0 && "WTF?");
329   return false;
330 }
331
332 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
333   switch (Ty->getPrimitiveID()) {
334   default:
335     return false;         // These can't be represented as floating point!
336
337     // TODO: Figure out how to test if a double can be cast to a float!
338   case Type::FloatTyID:
339     /*
340     return (Val <= UINT8_MAX);
341     */
342   case Type::DoubleTyID:
343     return true;          // This is the largest type...
344   }
345 };
346
347 //===----------------------------------------------------------------------===//
348 //                      Hash Function Implementations
349 #if 0
350 unsigned ConstantSInt::hash(const Type *Ty, int64_t V) {
351   return unsigned(Ty->getPrimitiveID() ^ V);
352 }
353
354 unsigned ConstantUInt::hash(const Type *Ty, uint64_t V) {
355   return unsigned(Ty->getPrimitiveID() ^ V);
356 }
357
358 unsigned ConstantFP::hash(const Type *Ty, double V) {
359   return Ty->getPrimitiveID() ^ unsigned(V);
360 }
361
362 unsigned ConstantArray::hash(const ArrayType *Ty,
363                              const std::vector<Constant*> &V) {
364   unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
365   for (unsigned i = 0; i < V.size(); ++i)
366     Result ^= V[i]->getHash() << (i & 7);
367   return Result;
368 }
369
370 unsigned ConstantStruct::hash(const StructType *Ty,
371                               const std::vector<Constant*> &V) {
372   unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
373   for (unsigned i = 0; i < V.size(); ++i)
374     Result ^= V[i]->getHash() << (i & 7);
375   return Result;
376 }
377 #endif
378
379 //===----------------------------------------------------------------------===//
380 //                      Factory Function Implementation
381
382 template<class ValType, class ConstantClass>
383 struct ValueMap {
384   typedef pair<const Type*, ValType> ConstHashKey;
385   map<ConstHashKey, ConstantClass *> Map;
386
387   inline ConstantClass *get(const Type *Ty, ValType V) {
388     map<ConstHashKey,ConstantClass *>::iterator I =
389       Map.find(ConstHashKey(Ty, V));
390     return (I != Map.end()) ? I->second : 0;
391   }
392
393   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
394     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
395   }
396
397   inline void remove(ConstantClass *CP) {
398     for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
399                                                       E = Map.end(); I != E;++I)
400       if (I->second == CP) {
401         Map.erase(I);
402         return;
403       }
404   }
405 };
406
407 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
408 //
409 static ValueMap<uint64_t, ConstantInt> IntConstants;
410
411 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
412   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
413   if (!Result)   // If no preexisting value, create one now...
414     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
415   return Result;
416 }
417
418 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
419   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
420   if (!Result)   // If no preexisting value, create one now...
421     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
422   return Result;
423 }
424
425 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
426   assert(V <= 127 && "Can only be used with very small positive constants!");
427   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
428   return ConstantUInt::get(Ty, V);
429 }
430
431 //---- ConstantFP::get() implementation...
432 //
433 static ValueMap<double, ConstantFP> FPConstants;
434
435 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
436   ConstantFP *Result = FPConstants.get(Ty, V);
437   if (!Result)   // If no preexisting value, create one now...
438     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
439   return Result;
440 }
441
442 //---- ConstantArray::get() implementation...
443 //
444 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
445
446 ConstantArray *ConstantArray::get(const ArrayType *Ty,
447                                   const std::vector<Constant*> &V) {
448   ConstantArray *Result = ArrayConstants.get(Ty, V);
449   if (!Result)   // If no preexisting value, create one now...
450     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
451   return Result;
452 }
453
454 // ConstantArray::get(const string&) - Return an array that is initialized to
455 // contain the specified string.  A null terminator is added to the specified
456 // string so that it may be used in a natural way...
457 //
458 ConstantArray *ConstantArray::get(const std::string &Str) {
459   std::vector<Constant*> ElementVals;
460
461   for (unsigned i = 0; i < Str.length(); ++i)
462     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
463
464   // Add a null terminator to the string...
465   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
466
467   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
468   return ConstantArray::get(ATy, ElementVals);
469 }
470
471
472 // destroyConstant - Remove the constant from the constant table...
473 //
474 void ConstantArray::destroyConstant() {
475   ArrayConstants.remove(this);
476   destroyConstantImpl();
477 }
478
479 //---- ConstantStruct::get() implementation...
480 //
481 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
482
483 ConstantStruct *ConstantStruct::get(const StructType *Ty,
484                                     const std::vector<Constant*> &V) {
485   ConstantStruct *Result = StructConstants.get(Ty, V);
486   if (!Result)   // If no preexisting value, create one now...
487     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
488   return Result;
489 }
490
491 // destroyConstant - Remove the constant from the constant table...
492 //
493 void ConstantStruct::destroyConstant() {
494   StructConstants.remove(this);
495   destroyConstantImpl();
496 }
497
498 //---- ConstantPointerNull::get() implementation...
499 //
500 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
501
502 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
503   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
504   if (!Result)   // If no preexisting value, create one now...
505     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
506   return Result;
507 }
508
509 //---- ConstantPointerRef::get() implementation...
510 //
511 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
512   assert(GV->getParent() && "Global Value must be attached to a module!");
513
514   // The Module handles the pointer reference sharing...
515   return GV->getParent()->getConstantPointerRef(GV);
516 }
517
518
519 void ConstantPointerRef::mutateReference(GlobalValue *NewGV) {
520   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
521   Operands[0] = NewGV;
522 }