192f5f7c65f3f4c290d78a731e5addfaade8a4c2
[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/iMemory.h"
11 #include "llvm/SymbolTable.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 Constant being destroyed");
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   assert(V.size() == ETypes.size() &&
131          "Invalid initializer vector for constant structure");
132   for (unsigned i = 0; i < V.size(); i++) {
133     assert(V[i]->getType() == ETypes[i]);
134     Operands.push_back(Use(V[i], this));
135   }
136 }
137
138 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
139   : ConstantPointer(GV->getType()) {
140   Operands.push_back(Use(GV, this));
141 }
142
143 ConstantExpr::ConstantExpr(unsigned opCode, Constant *C,  const Type *Ty)
144   : Constant(Ty), iType(opCode) {
145   Operands.push_back(Use(C, this));
146 }
147
148 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C1,
149                            Constant* C2, const Type *Ty)
150   : Constant(Ty), iType(opCode) {
151   Operands.push_back(Use(C1, this));
152   Operands.push_back(Use(C2, this));
153 }
154
155 ConstantExpr::ConstantExpr(unsigned opCode, Constant* C,
156                            const std::vector<Value*>& IdxList, const Type *Ty)
157   : Constant(Ty), iType(opCode) {
158   Operands.reserve(1+IdxList.size());
159   Operands.push_back(Use(C, this));
160   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
161     Operands.push_back(Use(IdxList[i], this));
162 }
163
164
165
166 //===----------------------------------------------------------------------===//
167 //                           classof implementations
168
169 bool ConstantInt::classof(const Constant *CPV) {
170   return CPV->getType()->isIntegral() && ! isa<ConstantExpr>(CPV);
171 }
172 bool ConstantSInt::classof(const Constant *CPV) {
173   return CPV->getType()->isSigned() && ! isa<ConstantExpr>(CPV);
174 }
175 bool ConstantUInt::classof(const Constant *CPV) {
176   return CPV->getType()->isUnsigned() && ! isa<ConstantExpr>(CPV);
177 }
178 bool ConstantFP::classof(const Constant *CPV) {
179   const Type *Ty = CPV->getType();
180   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
181           ! isa<ConstantExpr>(CPV));
182 }
183 bool ConstantArray::classof(const Constant *CPV) {
184   return isa<ArrayType>(CPV->getType()) && ! isa<ConstantExpr>(CPV);
185 }
186 bool ConstantStruct::classof(const Constant *CPV) {
187   return isa<StructType>(CPV->getType()) && ! isa<ConstantExpr>(CPV);
188 }
189 bool ConstantPointer::classof(const Constant *CPV) {
190   return (isa<PointerType>(CPV->getType()) && ! isa<ConstantExpr>(CPV));
191 }
192
193
194
195 //===----------------------------------------------------------------------===//
196 //                      isValueValidForType implementations
197
198 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
199   switch (Ty->getPrimitiveID()) {
200   default:
201     return false;         // These can't be represented as integers!!!
202
203     // Signed types...
204   case Type::SByteTyID:
205     return (Val <= INT8_MAX && Val >= INT8_MIN);
206   case Type::ShortTyID:
207     return (Val <= INT16_MAX && Val >= INT16_MIN);
208   case Type::IntTyID:
209     return (Val <= INT32_MAX && Val >= INT32_MIN);
210   case Type::LongTyID:
211     return true;          // This is the largest type...
212   }
213   assert(0 && "WTF?");
214   return false;
215 }
216
217 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
218   switch (Ty->getPrimitiveID()) {
219   default:
220     return false;         // These can't be represented as integers!!!
221
222     // Unsigned types...
223   case Type::UByteTyID:
224     return (Val <= UINT8_MAX);
225   case Type::UShortTyID:
226     return (Val <= UINT16_MAX);
227   case Type::UIntTyID:
228     return (Val <= UINT32_MAX);
229   case Type::ULongTyID:
230     return true;          // This is the largest type...
231   }
232   assert(0 && "WTF?");
233   return false;
234 }
235
236 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
237   switch (Ty->getPrimitiveID()) {
238   default:
239     return false;         // These can't be represented as floating point!
240
241     // TODO: Figure out how to test if a double can be cast to a float!
242   case Type::FloatTyID:
243     /*
244     return (Val <= UINT8_MAX);
245     */
246   case Type::DoubleTyID:
247     return true;          // This is the largest type...
248   }
249 };
250
251 //===----------------------------------------------------------------------===//
252 //                      Factory Function Implementation
253
254 template<class ValType, class ConstantClass>
255 struct ValueMap {
256   typedef pair<const Type*, ValType> ConstHashKey;
257   map<ConstHashKey, ConstantClass *> Map;
258
259   inline ConstantClass *get(const Type *Ty, ValType V) {
260     map<ConstHashKey,ConstantClass *>::iterator I =
261       Map.find(ConstHashKey(Ty, V));
262     return (I != Map.end()) ? I->second : 0;
263   }
264
265   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
266     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
267   }
268
269   inline void remove(ConstantClass *CP) {
270     for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
271                                                       E = Map.end(); I != E;++I)
272       if (I->second == CP) {
273         Map.erase(I);
274         return;
275       }
276   }
277 };
278
279 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
280 //
281 static ValueMap<uint64_t, ConstantInt> IntConstants;
282
283 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
284   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
285   if (!Result)   // If no preexisting value, create one now...
286     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
287   return Result;
288 }
289
290 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
291   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
292   if (!Result)   // If no preexisting value, create one now...
293     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
294   return Result;
295 }
296
297 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
298   assert(V <= 127 && "Can only be used with very small positive constants!");
299   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
300   return ConstantUInt::get(Ty, V);
301 }
302
303 //---- ConstantFP::get() implementation...
304 //
305 static ValueMap<double, ConstantFP> FPConstants;
306
307 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
308   ConstantFP *Result = FPConstants.get(Ty, V);
309   if (!Result)   // If no preexisting value, create one now...
310     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
311   return Result;
312 }
313
314 //---- ConstantArray::get() implementation...
315 //
316 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
317
318 ConstantArray *ConstantArray::get(const ArrayType *Ty,
319                                   const std::vector<Constant*> &V) {
320   ConstantArray *Result = ArrayConstants.get(Ty, V);
321   if (!Result)   // If no preexisting value, create one now...
322     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
323   return Result;
324 }
325
326 // ConstantArray::get(const string&) - Return an array that is initialized to
327 // contain the specified string.  A null terminator is added to the specified
328 // string so that it may be used in a natural way...
329 //
330 ConstantArray *ConstantArray::get(const std::string &Str) {
331   std::vector<Constant*> ElementVals;
332
333   for (unsigned i = 0; i < Str.length(); ++i)
334     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
335
336   // Add a null terminator to the string...
337   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
338
339   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
340   return ConstantArray::get(ATy, ElementVals);
341 }
342
343
344 // destroyConstant - Remove the constant from the constant table...
345 //
346 void ConstantArray::destroyConstant() {
347   ArrayConstants.remove(this);
348   destroyConstantImpl();
349 }
350
351 //---- ConstantStruct::get() implementation...
352 //
353 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
354
355 ConstantStruct *ConstantStruct::get(const StructType *Ty,
356                                     const std::vector<Constant*> &V) {
357   ConstantStruct *Result = StructConstants.get(Ty, V);
358   if (!Result)   // If no preexisting value, create one now...
359     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
360   return Result;
361 }
362
363 // destroyConstant - Remove the constant from the constant table...
364 //
365 void ConstantStruct::destroyConstant() {
366   StructConstants.remove(this);
367   destroyConstantImpl();
368 }
369
370 //---- ConstantPointerNull::get() implementation...
371 //
372 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
373
374 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
375   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
376   if (!Result)   // If no preexisting value, create one now...
377     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
378   return Result;
379 }
380
381 //---- ConstantPointerRef::get() implementation...
382 //
383 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
384   assert(GV->getParent() && "Global Value must be attached to a module!");
385   
386   // The Module handles the pointer reference sharing...
387   return GV->getParent()->getConstantPointerRef(GV);
388 }
389
390 //---- ConstantExpr::get() implementations...
391 // Return NULL on invalid expressions.
392 //
393 ConstantExpr*
394 ConstantExpr::get(unsigned opCode, Constant *C, const Type *Ty) {
395   if (opCode != Instruction::Cast &&
396       (opCode < Instruction::FirstUnaryOp ||
397        opCode >= Instruction::NumUnaryOps)) {
398     cerr << "Invalid opcode " << ConstantExpr::getOpcodeName(opCode)
399          << " in unary constant expression" << endl;
400     return NULL;       // Not Cast or other unary opcode
401   }
402   // type of operand will not match result for Cast operation
403   if (opCode != Instruction::Cast && Ty != C->getType()) {
404     cerr << "Type of operand in unary constant expression should match result" << endl;
405     return NULL;
406   }
407   return new ConstantExpr(opCode, C, Ty);
408 }
409
410 ConstantExpr*
411 ConstantExpr::get(unsigned opCode, Constant *C1, Constant *C2,const Type *Ty) {
412   if (opCode < Instruction::FirstBinaryOp ||
413       opCode >= Instruction::NumBinaryOps) {
414     cerr << "Invalid opcode " << ConstantExpr::getOpcodeName(opCode)
415          << " in binary constant expression" << endl;
416     return NULL;
417   }
418   if (Ty != C1->getType() || Ty != C2->getType()) {
419     cerr << "Types of both operands in binary constant expression should match result" << endl;
420     return NULL;
421   }
422   return new ConstantExpr(opCode, C1, C2, Ty);
423 }
424
425 ConstantExpr*
426 ConstantExpr::get(unsigned opCode, Constant*C,
427                    const std::vector<Value*>& idxList, const Type *Ty) {
428   // Must be a getElementPtr.  Check for valid getElementPtr expression.
429   // 
430   if (opCode != Instruction::GetElementPtr) {
431     cerr << "operator other than GetElementPtr used with an index list" << endl;
432     return NULL;
433   }
434   if (!isa<ConstantPointer>(C)) {
435     cerr << "Constant GelElementPtr expression using something other than a constant pointer" << endl;
436     return NULL;
437   }
438   if (!isa<PointerType>(Ty)) {
439     cerr << "Non-pointer type for constant GelElementPtr expression" << endl;
440     return NULL;
441   }
442   const Type* fldType = GetElementPtrInst::getIndexedType(C->getType(),
443                                                           idxList, true);
444   if (!fldType) {
445     cerr << "Invalid index list for constant GelElementPtr expression" << endl;
446     return NULL;
447   }
448   if (cast<PointerType>(Ty)->getElementType() != fldType) {
449     cerr << "Type for constant GelElementPtr expression does not match field type" << endl;
450     return NULL;
451   }
452   
453   return new ConstantExpr(opCode, C, idxList, Ty);
454 }
455
456 const char*
457 ConstantExpr::getOpcodeName(unsigned opCode) {
458   return Instruction::getOpcodeName(opCode);
459 }
460
461
462 //---- ConstantPointerRef::mutateReferences() implementation...
463 //
464 unsigned
465 ConstantPointerRef::mutateReferences(Value* OldV, Value *NewV) {
466   assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
467   GlobalValue* NewGV = cast<GlobalValue>(NewV);
468   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
469   Operands[0] = NewGV;
470   return 1;
471 }
472
473
474 //---- ConstantPointerExpr::mutateReferences() implementation...
475 //
476 unsigned
477 ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
478   unsigned numReplaced = 0;
479   Constant* NewC = cast<Constant>(NewV);
480   for (unsigned i=0, N = getNumOperands(); i < N; ++i)
481     if (Operands[i] == OldV) {
482       ++numReplaced;
483       Operands[i] = NewC;
484     }
485   return numReplaced;
486 }