856cd1ab16ebfa3adbcde028a0a9461263af0679
[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 using std::vector;
21
22 ConstantBool *ConstantBool::True  = new ConstantBool(true);
23 ConstantBool *ConstantBool::False = new ConstantBool(false);
24
25
26 //===----------------------------------------------------------------------===//
27 //                              Constant Class
28 //===----------------------------------------------------------------------===//
29
30 // Specialize setName to take care of symbol table majik
31 void Constant::setName(const std::string &Name, SymbolTable *ST) {
32   assert(ST && "Type::setName - Must provide symbol table argument!");
33
34   if (Name.size()) ST->insert(Name, this);
35 }
36
37 // Static constructor to create a '0' constant of arbitrary type...
38 Constant *Constant::getNullValue(const Type *Ty) {
39   switch (Ty->getPrimitiveID()) {
40   case Type::BoolTyID:   return ConstantBool::get(false);
41   case Type::SByteTyID:
42   case Type::ShortTyID:
43   case Type::IntTyID:
44   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
45
46   case Type::UByteTyID:
47   case Type::UShortTyID:
48   case Type::UIntTyID:
49   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
50
51   case Type::FloatTyID:
52   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
53
54   case Type::PointerTyID: 
55     return ConstantPointerNull::get(cast<PointerType>(Ty));
56   default:
57     return 0;
58   }
59 }
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       std::cerr << "While deleting: " << *this
74                 << "\n\nUse still stuck around after Def is destroyed: "
75                 << *V << "\n\n";
76 #endif
77     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
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) : ConstantGenericIntegral(Type::BoolTy) {
97   Val = V;
98 }
99
100 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
101   : ConstantGenericIntegral(Ty) {
102   Val.Unsigned = V;
103 }
104
105 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
106   assert(isValueValidForType(Ty, V) && "Value too large for type!");
107 }
108
109 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
110   assert(isValueValidForType(Ty, V) && "Value too large for type!");
111 }
112
113 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
114   assert(isValueValidForType(Ty, V) && "Value too large for type!");
115   Val = V;
116 }
117
118 ConstantArray::ConstantArray(const ArrayType *T,
119                              const std::vector<Constant*> &V) : Constant(T) {
120   for (unsigned i = 0; i < V.size(); i++) {
121     assert(V[i]->getType() == T->getElementType());
122     Operands.push_back(Use(V[i], this));
123   }
124 }
125
126 ConstantStruct::ConstantStruct(const StructType *T,
127                                const std::vector<Constant*> &V) : Constant(T) {
128   const StructType::ElementTypes &ETypes = T->getElementTypes();
129   assert(V.size() == ETypes.size() &&
130          "Invalid initializer vector for constant structure");
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 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
143   : Constant(Ty), iType(Opcode) {
144   Operands.push_back(Use(C, this));
145 }
146
147 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
148   : Constant(C1->getType()), iType(Opcode) {
149   Operands.push_back(Use(C1, this));
150   Operands.push_back(Use(C2, this));
151 }
152
153 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
154                            const Type *DestTy)
155   : Constant(DestTy), iType(Instruction::GetElementPtr) {
156   Operands.reserve(1+IdxList.size());
157   Operands.push_back(Use(C, this));
158   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
159     Operands.push_back(Use(IdxList[i], this));
160 }
161
162
163
164 //===----------------------------------------------------------------------===//
165 //                           classof implementations
166
167 bool ConstantGenericIntegral::classof(const Constant *CPV) {
168   return (CPV->getType()->isIntegral() || CPV->getType() == Type::BoolTy) &&
169           !isa<ConstantExpr>(CPV);
170 }
171
172 bool ConstantInt::classof(const Constant *CPV) {
173   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
174 }
175 bool ConstantSInt::classof(const Constant *CPV) {
176   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
177 }
178 bool ConstantUInt::classof(const Constant *CPV) {
179   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
180 }
181 bool ConstantFP::classof(const Constant *CPV) {
182   const Type *Ty = CPV->getType();
183   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
184           !isa<ConstantExpr>(CPV));
185 }
186 bool ConstantArray::classof(const Constant *CPV) {
187   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
188 }
189 bool ConstantStruct::classof(const Constant *CPV) {
190   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
191 }
192 bool ConstantPointer::classof(const Constant *CPV) {
193   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
194 }
195
196
197
198 //===----------------------------------------------------------------------===//
199 //                      isValueValidForType implementations
200
201 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
202   switch (Ty->getPrimitiveID()) {
203   default:
204     return false;         // These can't be represented as integers!!!
205
206     // Signed types...
207   case Type::SByteTyID:
208     return (Val <= INT8_MAX && Val >= INT8_MIN);
209   case Type::ShortTyID:
210     return (Val <= INT16_MAX && Val >= INT16_MIN);
211   case Type::IntTyID:
212     return (Val <= INT32_MAX && Val >= INT32_MIN);
213   case Type::LongTyID:
214     return true;          // This is the largest type...
215   }
216   assert(0 && "WTF?");
217   return false;
218 }
219
220 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
221   switch (Ty->getPrimitiveID()) {
222   default:
223     return false;         // These can't be represented as integers!!!
224
225     // Unsigned types...
226   case Type::UByteTyID:
227     return (Val <= UINT8_MAX);
228   case Type::UShortTyID:
229     return (Val <= UINT16_MAX);
230   case Type::UIntTyID:
231     return (Val <= UINT32_MAX);
232   case Type::ULongTyID:
233     return true;          // This is the largest type...
234   }
235   assert(0 && "WTF?");
236   return false;
237 }
238
239 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
240   switch (Ty->getPrimitiveID()) {
241   default:
242     return false;         // These can't be represented as floating point!
243
244     // TODO: Figure out how to test if a double can be cast to a float!
245   case Type::FloatTyID:
246     /*
247     return (Val <= UINT8_MAX);
248     */
249   case Type::DoubleTyID:
250     return true;          // This is the largest type...
251   }
252 };
253
254 //===----------------------------------------------------------------------===//
255 //                      Factory Function Implementation
256
257 template<class ValType, class ConstantClass>
258 struct ValueMap {
259   typedef pair<const Type*, ValType> ConstHashKey;
260   map<ConstHashKey, ConstantClass *> Map;
261
262   inline ConstantClass *get(const Type *Ty, ValType V) {
263     typename map<ConstHashKey,ConstantClass *>::iterator I =
264       Map.find(ConstHashKey(Ty, V));
265     return (I != Map.end()) ? I->second : 0;
266   }
267
268   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
269     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
270   }
271
272   inline void remove(ConstantClass *CP) {
273     for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
274                                                       E = Map.end(); I != E;++I)
275       if (I->second == CP) {
276         Map.erase(I);
277         return;
278       }
279   }
280 };
281
282 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
283 //
284 static ValueMap<uint64_t, ConstantInt> IntConstants;
285
286 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
287   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
288   if (!Result)   // If no preexisting value, create one now...
289     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
290   return Result;
291 }
292
293 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
294   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
295   if (!Result)   // If no preexisting value, create one now...
296     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
297   return Result;
298 }
299
300 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
301   assert(V <= 127 && "Can only be used with very small positive constants!");
302   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
303   return ConstantUInt::get(Ty, V);
304 }
305
306 //---- ConstantFP::get() implementation...
307 //
308 static ValueMap<double, ConstantFP> FPConstants;
309
310 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
311   ConstantFP *Result = FPConstants.get(Ty, V);
312   if (!Result)   // If no preexisting value, create one now...
313     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
314   return Result;
315 }
316
317 //---- ConstantArray::get() implementation...
318 //
319 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
320
321 ConstantArray *ConstantArray::get(const ArrayType *Ty,
322                                   const std::vector<Constant*> &V) {
323   ConstantArray *Result = ArrayConstants.get(Ty, V);
324   if (!Result)   // If no preexisting value, create one now...
325     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
326   return Result;
327 }
328
329 // ConstantArray::get(const string&) - Return an array that is initialized to
330 // contain the specified string.  A null terminator is added to the specified
331 // string so that it may be used in a natural way...
332 //
333 ConstantArray *ConstantArray::get(const std::string &Str) {
334   std::vector<Constant*> ElementVals;
335
336   for (unsigned i = 0; i < Str.length(); ++i)
337     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
338
339   // Add a null terminator to the string...
340   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
341
342   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
343   return ConstantArray::get(ATy, ElementVals);
344 }
345
346
347 // destroyConstant - Remove the constant from the constant table...
348 //
349 void ConstantArray::destroyConstant() {
350   ArrayConstants.remove(this);
351   destroyConstantImpl();
352 }
353
354 //---- ConstantStruct::get() implementation...
355 //
356 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
357
358 ConstantStruct *ConstantStruct::get(const StructType *Ty,
359                                     const std::vector<Constant*> &V) {
360   ConstantStruct *Result = StructConstants.get(Ty, V);
361   if (!Result)   // If no preexisting value, create one now...
362     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
363   return Result;
364 }
365
366 // destroyConstant - Remove the constant from the constant table...
367 //
368 void ConstantStruct::destroyConstant() {
369   StructConstants.remove(this);
370   destroyConstantImpl();
371 }
372
373 //---- ConstantPointerNull::get() implementation...
374 //
375 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
376
377 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
378   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
379   if (!Result)   // If no preexisting value, create one now...
380     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
381   return Result;
382 }
383
384 //---- ConstantPointerRef::get() implementation...
385 //
386 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
387   assert(GV->getParent() && "Global Value must be attached to a module!");
388   
389   // The Module handles the pointer reference sharing...
390   return GV->getParent()->getConstantPointerRef(GV);
391 }
392
393 //---- ConstantExpr::get() implementations...
394 //
395 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
396 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
397
398 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C, const Type *Ty) {
399
400   // Look up the constant in the table first to ensure uniqueness
401   vector<Constant*> argVec(1, C);
402   const ExprMapKeyType &Key = make_pair(Opcode, argVec);
403   ConstantExpr *Result = ExprConstants.get(Ty, Key);
404   if (Result) return Result;
405   
406   // Its not in the table so create a new one and put it in the table.
407   // Check the operands for consistency first
408   assert(Opcode == Instruction::Cast ||
409          (Opcode >= Instruction::FirstUnaryOp &&
410           Opcode < Instruction::NumUnaryOps) &&
411          "Invalid opcode in unary ConstantExpr!");
412
413   // type of operand will not match result for Cast operation
414   assert((Opcode == Instruction::Cast || Ty == C->getType()) &&
415          "Type of operand in unary constant expression should match result");
416   
417   Result = new ConstantExpr(Opcode, C, Ty);
418   ExprConstants.add(Ty, Key, Result);
419   return Result;
420 }
421
422 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
423   // Look up the constant in the table first to ensure uniqueness
424   vector<Constant*> argVec(1, C1); argVec.push_back(C2);
425   const ExprMapKeyType &Key = make_pair(Opcode, argVec);
426   ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
427   if (Result) return Result;
428   
429   // Its not in the table so create a new one and put it in the table.
430   // Check the operands for consistency first
431   assert((Opcode >= Instruction::FirstBinaryOp &&
432           Opcode < Instruction::NumBinaryOps) &&
433          "Invalid opcode in binary constant expression");
434
435   assert(C1->getType() == C2->getType() &&
436          "Operand types in binary constant expression should match");
437   
438   Result = new ConstantExpr(Opcode, C1, C2);
439   ExprConstants.add(C1->getType(), Key, Result);
440   return Result;
441 }
442
443 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
444                                         const std::vector<Constant*> &IdxList) {
445   const Type *Ty = C->getType();
446
447   // Look up the constant in the table first to ensure uniqueness
448   vector<Constant*> argVec(1, C);
449   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
450   
451   const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
452   ConstantExpr *Result = ExprConstants.get(Ty, Key);
453   if (Result) return Result;
454
455   // Its not in the table so create a new one and put it in the table.
456   // Check the operands for consistency first
457   // 
458   assert(isa<PointerType>(Ty) &&
459          "Non-pointer type for constant GelElementPtr expression");
460
461   // Check that the indices list is valid...
462   std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
463   const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
464   assert(DestTy && "Invalid index list for constant GelElementPtr expression");
465   
466   Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
467   ExprConstants.add(Ty, Key, Result);
468   return Result;
469 }
470
471 // destroyConstant - Remove the constant from the constant table...
472 //
473 void ConstantExpr::destroyConstant() {
474   ExprConstants.remove(this);
475   destroyConstantImpl();
476 }
477
478 const char *ConstantExpr::getOpcodeName() const {
479   return Instruction::getOpcodeName(getOpcode());
480 }
481
482
483 //---- ConstantPointerRef::mutateReferences() implementation...
484 //
485 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
486   assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
487   GlobalValue *NewGV = cast<GlobalValue>(NewV);
488   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
489   Operands[0] = NewGV;
490   return 1;
491 }
492
493
494 //---- ConstantPointerExpr::mutateReferences() implementation...
495 //
496 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
497   unsigned NumReplaced = 0;
498   Constant *NewC = cast<Constant>(NewV);
499   for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
500     if (Operands[i] == OldV) {
501       ++NumReplaced;
502       Operands[i] = NewC;
503     }
504   return NumReplaced;
505 }