Split ConstantVals.h into Constant.h and Constants.h
[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 #define __STDC_LIMIT_MACROS           // Get defs for INT64_MAX and friends...
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/GlobalValue.h"
12 #include "llvm/Module.h"
13 #include "llvm/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::getNullValue(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 void Constant::destroyConstantImpl() {
61   // When a Constant is destroyed, there may be lingering
62   // references to the constant by other constants in the constant pool.  These
63   // constants are implicitly dependant on the module that is being deleted,
64   // but they don't know that.  Because we only find out when the CPV is
65   // deleted, we must now notify all of our users (that should only be
66   // Constants) that they are, in fact, invalid now and should be deleted.
67   //
68   while (!use_empty()) {
69     Value *V = use_back();
70 #ifndef NDEBUG      // Only in -g mode...
71     if (!isa<Constant>(V)) {
72       std::cerr << "While deleting: ";
73       dump();
74       std::cerr << "\nUse still stuck around after Def is destroyed: ";
75       V->dump();
76       std::cerr << "\n";
77     }
78 #endif
79     assert(isa<Constant>(V) && "References remain to ConstantPointerRef!");
80     Constant *CPV = cast<Constant>(V);
81     CPV->destroyConstant();
82
83     // The constant should remove itself from our use list...
84     assert((use_empty() || use_back() == V) && "Constant not removed!");
85   }
86
87   // Value has no outstanding references it is safe to delete it now...
88   delete this;
89 }
90
91 //===----------------------------------------------------------------------===//
92 //                            ConstantXXX Classes
93 //===----------------------------------------------------------------------===//
94
95 //===----------------------------------------------------------------------===//
96 //                             Normal Constructors
97
98 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
99   Val = V;
100 }
101
102 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
103   Val.Unsigned = V;
104 }
105
106 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
107   assert(isValueValidForType(Ty, V) && "Value too large for type!");
108 }
109
110 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
111   assert(isValueValidForType(Ty, V) && "Value too large for type!");
112 }
113
114 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
115   assert(isValueValidForType(Ty, V) && "Value too large for type!");
116   Val = V;
117 }
118
119 ConstantArray::ConstantArray(const ArrayType *T,
120                              const std::vector<Constant*> &V) : Constant(T) {
121   for (unsigned i = 0; i < V.size(); i++) {
122     assert(V[i]->getType() == T->getElementType());
123     Operands.push_back(Use(V[i], this));
124   }
125 }
126
127 ConstantStruct::ConstantStruct(const StructType *T,
128                                const std::vector<Constant*> &V) : Constant(T) {
129   const StructType::ElementTypes &ETypes = T->getElementTypes();
130   
131   for (unsigned i = 0; i < V.size(); i++) {
132     assert(V[i]->getType() == ETypes[i]);
133     Operands.push_back(Use(V[i], this));
134   }
135 }
136
137 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
138   : ConstantPointer(GV->getType()) {
139   Operands.push_back(Use(GV, this));
140 }
141
142
143
144 //===----------------------------------------------------------------------===//
145 //                           classof implementations
146
147 bool ConstantInt::classof(const Constant *CPV) {
148   return CPV->getType()->isIntegral();
149 }
150 bool ConstantSInt::classof(const Constant *CPV) {
151   return CPV->getType()->isSigned();
152 }
153 bool ConstantUInt::classof(const Constant *CPV) {
154   return CPV->getType()->isUnsigned();
155 }
156 bool ConstantFP::classof(const Constant *CPV) {
157   const Type *Ty = CPV->getType();
158   return Ty == Type::FloatTy || Ty == Type::DoubleTy;
159 }
160 bool ConstantArray::classof(const Constant *CPV) {
161   return isa<ArrayType>(CPV->getType());
162 }
163 bool ConstantStruct::classof(const Constant *CPV) {
164   return isa<StructType>(CPV->getType());
165 }
166 bool ConstantPointer::classof(const Constant *CPV) {
167   return isa<PointerType>(CPV->getType());
168 }
169
170
171 //===----------------------------------------------------------------------===//
172 //                      isValueValidForType implementations
173
174 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
175   switch (Ty->getPrimitiveID()) {
176   default:
177     return false;         // These can't be represented as integers!!!
178
179     // Signed types...
180   case Type::SByteTyID:
181     return (Val <= INT8_MAX && Val >= INT8_MIN);
182   case Type::ShortTyID:
183     return (Val <= INT16_MAX && Val >= INT16_MIN);
184   case Type::IntTyID:
185     return (Val <= INT32_MAX && Val >= INT32_MIN);
186   case Type::LongTyID:
187     return true;          // This is the largest type...
188   }
189   assert(0 && "WTF?");
190   return false;
191 }
192
193 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
194   switch (Ty->getPrimitiveID()) {
195   default:
196     return false;         // These can't be represented as integers!!!
197
198     // Unsigned types...
199   case Type::UByteTyID:
200     return (Val <= UINT8_MAX);
201   case Type::UShortTyID:
202     return (Val <= UINT16_MAX);
203   case Type::UIntTyID:
204     return (Val <= UINT32_MAX);
205   case Type::ULongTyID:
206     return true;          // This is the largest type...
207   }
208   assert(0 && "WTF?");
209   return false;
210 }
211
212 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
213   switch (Ty->getPrimitiveID()) {
214   default:
215     return false;         // These can't be represented as floating point!
216
217     // TODO: Figure out how to test if a double can be cast to a float!
218   case Type::FloatTyID:
219     /*
220     return (Val <= UINT8_MAX);
221     */
222   case Type::DoubleTyID:
223     return true;          // This is the largest type...
224   }
225 };
226
227 //===----------------------------------------------------------------------===//
228 //                      Factory Function Implementation
229
230 template<class ValType, class ConstantClass>
231 struct ValueMap {
232   typedef pair<const Type*, ValType> ConstHashKey;
233   map<ConstHashKey, ConstantClass *> Map;
234
235   inline ConstantClass *get(const Type *Ty, ValType V) {
236     map<ConstHashKey,ConstantClass *>::iterator I =
237       Map.find(ConstHashKey(Ty, V));
238     return (I != Map.end()) ? I->second : 0;
239   }
240
241   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
242     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
243   }
244
245   inline void remove(ConstantClass *CP) {
246     for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
247                                                       E = Map.end(); I != E;++I)
248       if (I->second == CP) {
249         Map.erase(I);
250         return;
251       }
252   }
253 };
254
255 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
256 //
257 static ValueMap<uint64_t, ConstantInt> IntConstants;
258
259 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
260   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
261   if (!Result)   // If no preexisting value, create one now...
262     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
263   return Result;
264 }
265
266 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
267   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
268   if (!Result)   // If no preexisting value, create one now...
269     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
270   return Result;
271 }
272
273 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
274   assert(V <= 127 && "Can only be used with very small positive constants!");
275   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
276   return ConstantUInt::get(Ty, V);
277 }
278
279 //---- ConstantFP::get() implementation...
280 //
281 static ValueMap<double, ConstantFP> FPConstants;
282
283 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
284   ConstantFP *Result = FPConstants.get(Ty, V);
285   if (!Result)   // If no preexisting value, create one now...
286     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
287   return Result;
288 }
289
290 //---- ConstantArray::get() implementation...
291 //
292 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
293
294 ConstantArray *ConstantArray::get(const ArrayType *Ty,
295                                   const std::vector<Constant*> &V) {
296   ConstantArray *Result = ArrayConstants.get(Ty, V);
297   if (!Result)   // If no preexisting value, create one now...
298     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
299   return Result;
300 }
301
302 // ConstantArray::get(const string&) - Return an array that is initialized to
303 // contain the specified string.  A null terminator is added to the specified
304 // string so that it may be used in a natural way...
305 //
306 ConstantArray *ConstantArray::get(const std::string &Str) {
307   std::vector<Constant*> ElementVals;
308
309   for (unsigned i = 0; i < Str.length(); ++i)
310     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
311
312   // Add a null terminator to the string...
313   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
314
315   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
316   return ConstantArray::get(ATy, ElementVals);
317 }
318
319
320 // destroyConstant - Remove the constant from the constant table...
321 //
322 void ConstantArray::destroyConstant() {
323   ArrayConstants.remove(this);
324   destroyConstantImpl();
325 }
326
327 //---- ConstantStruct::get() implementation...
328 //
329 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
330
331 ConstantStruct *ConstantStruct::get(const StructType *Ty,
332                                     const std::vector<Constant*> &V) {
333   ConstantStruct *Result = StructConstants.get(Ty, V);
334   if (!Result)   // If no preexisting value, create one now...
335     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
336   return Result;
337 }
338
339 // destroyConstant - Remove the constant from the constant table...
340 //
341 void ConstantStruct::destroyConstant() {
342   StructConstants.remove(this);
343   destroyConstantImpl();
344 }
345
346 //---- ConstantPointerNull::get() implementation...
347 //
348 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
349
350 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
351   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
352   if (!Result)   // If no preexisting value, create one now...
353     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
354   return Result;
355 }
356
357 //---- ConstantPointerRef::get() implementation...
358 //
359 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
360   assert(GV->getParent() && "Global Value must be attached to a module!");
361
362   // The Module handles the pointer reference sharing...
363   return GV->getParent()->getConstantPointerRef(GV);
364 }
365
366
367 void ConstantPointerRef::mutateReference(GlobalValue *NewGV) {
368   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
369   Operands[0] = NewGV;
370 }