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