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