eb68ef68095b65fd5faa7b16c370b012f9c0a557
[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 void Constant::destroyConstantImpl() {
38   // When a Constant is destroyed, there may be lingering
39   // references to the constant by other constants in the constant pool.  These
40   // constants are implicitly dependant on the module that is being deleted,
41   // but they don't know that.  Because we only find out when the CPV is
42   // deleted, we must now notify all of our users (that should only be
43   // Constants) that they are, in fact, invalid now and should be deleted.
44   //
45   while (!use_empty()) {
46     Value *V = use_back();
47 #ifndef NDEBUG      // Only in -g mode...
48     if (!isa<Constant>(V))
49       std::cerr << "While deleting: " << *this
50                 << "\n\nUse still stuck around after Def is destroyed: "
51                 << *V << "\n\n";
52 #endif
53     assert(isa<Constant>(V) && "References remain to Constant being destroyed");
54     Constant *CPV = cast<Constant>(V);
55     CPV->destroyConstant();
56
57     // The constant should remove itself from our use list...
58     assert((use_empty() || use_back() != V) && "Constant not removed!");
59   }
60
61   // Value has no outstanding references it is safe to delete it now...
62   delete this;
63 }
64
65 // Static constructor to create a '0' constant of arbitrary type...
66 Constant *Constant::getNullValue(const Type *Ty) {
67   switch (Ty->getPrimitiveID()) {
68   case Type::BoolTyID:   return ConstantBool::get(false);
69   case Type::SByteTyID:
70   case Type::ShortTyID:
71   case Type::IntTyID:
72   case Type::LongTyID:   return ConstantSInt::get(Ty, 0);
73
74   case Type::UByteTyID:
75   case Type::UShortTyID:
76   case Type::UIntTyID:
77   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
78
79   case Type::FloatTyID:
80   case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
81
82   case Type::PointerTyID: 
83     return ConstantPointerNull::get(cast<PointerType>(Ty));
84   default:
85     return 0;
86   }
87 }
88
89 // Static constructor to create the maximum constant of an integral type...
90 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
91   switch (Ty->getPrimitiveID()) {
92   case Type::BoolTyID:   return ConstantBool::True;
93   case Type::SByteTyID:
94   case Type::ShortTyID:
95   case Type::IntTyID:
96   case Type::LongTyID: {
97     // Calculate 011111111111111... 
98     unsigned TypeBits = Ty->getPrimitiveSize()*8;
99     int64_t Val = INT64_MAX;             // All ones
100     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
101     return ConstantSInt::get(Ty, Val);
102   }
103
104   case Type::UByteTyID:
105   case Type::UShortTyID:
106   case Type::UIntTyID:
107   case Type::ULongTyID:  return getAllOnesValue(Ty);
108
109   default:
110     assert(0 && "Non-integral type specified!");
111     return 0;
112   }
113 }
114
115 // Static constructor to create the minimum constant for an integral type...
116 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
117   switch (Ty->getPrimitiveID()) {
118   case Type::BoolTyID:   return ConstantBool::False;
119   case Type::SByteTyID:
120   case Type::ShortTyID:
121   case Type::IntTyID:
122   case Type::LongTyID: {
123      // Calculate 1111111111000000000000 
124      unsigned TypeBits = Ty->getPrimitiveSize()*8;
125      int64_t Val = -1;                    // All ones
126      Val <<= TypeBits-1;                  // Shift over to the right spot
127      return ConstantSInt::get(Ty, Val);
128   }
129
130   case Type::UByteTyID:
131   case Type::UShortTyID:
132   case Type::UIntTyID:
133   case Type::ULongTyID:  return ConstantUInt::get(Ty, 0);
134
135   default:
136     assert(0 && "Non-integral type specified!");
137     return 0;
138   }
139 }
140
141 // Static constructor to create an integral constant with all bits set
142 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
143   switch (Ty->getPrimitiveID()) {
144   case Type::BoolTyID:   return ConstantBool::True;
145   case Type::SByteTyID:
146   case Type::ShortTyID:
147   case Type::IntTyID:
148   case Type::LongTyID:   return ConstantSInt::get(Ty, -1);
149
150   case Type::UByteTyID:
151   case Type::UShortTyID:
152   case Type::UIntTyID:
153   case Type::ULongTyID: {
154     // Calculate ~0 of the right type...
155     unsigned TypeBits = Ty->getPrimitiveSize()*8;
156     uint64_t Val = ~0ULL;                // All ones
157     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
158     return ConstantUInt::get(Ty, Val);
159   }
160   default:
161     assert(0 && "Non-integral type specified!");
162     return 0;
163   }
164 }
165
166
167 //===----------------------------------------------------------------------===//
168 //                            ConstantXXX Classes
169 //===----------------------------------------------------------------------===//
170
171 //===----------------------------------------------------------------------===//
172 //                             Normal Constructors
173
174 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
175   Val = V;
176 }
177
178 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
179   Val.Unsigned = V;
180 }
181
182 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
183   assert(isValueValidForType(Ty, V) && "Value too large for type!");
184 }
185
186 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
187   assert(isValueValidForType(Ty, V) && "Value too large for type!");
188 }
189
190 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
191   assert(isValueValidForType(Ty, V) && "Value too large for type!");
192   Val = V;
193 }
194
195 ConstantArray::ConstantArray(const ArrayType *T,
196                              const std::vector<Constant*> &V) : Constant(T) {
197   for (unsigned i = 0; i < V.size(); i++) {
198     assert(V[i]->getType() == T->getElementType());
199     Operands.push_back(Use(V[i], this));
200   }
201 }
202
203 ConstantStruct::ConstantStruct(const StructType *T,
204                                const std::vector<Constant*> &V) : Constant(T) {
205   const StructType::ElementTypes &ETypes = T->getElementTypes();
206   assert(V.size() == ETypes.size() &&
207          "Invalid initializer vector for constant structure");
208   for (unsigned i = 0; i < V.size(); i++) {
209     assert(V[i]->getType() == ETypes[i]);
210     Operands.push_back(Use(V[i], this));
211   }
212 }
213
214 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
215   : ConstantPointer(GV->getType()) {
216   Operands.push_back(Use(GV, this));
217 }
218
219 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
220   : Constant(Ty), iType(Opcode) {
221   Operands.push_back(Use(C, this));
222 }
223
224 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
225   : Constant(C1->getType()), iType(Opcode) {
226   Operands.push_back(Use(C1, this));
227   Operands.push_back(Use(C2, this));
228 }
229
230 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
231                            const Type *DestTy)
232   : Constant(DestTy), iType(Instruction::GetElementPtr) {
233   Operands.reserve(1+IdxList.size());
234   Operands.push_back(Use(C, this));
235   for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
236     Operands.push_back(Use(IdxList[i], this));
237 }
238
239
240
241 //===----------------------------------------------------------------------===//
242 //                           classof implementations
243
244 bool ConstantIntegral::classof(const Constant *CPV) {
245   return (CPV->getType()->isIntegral() || CPV->getType() == Type::BoolTy) &&
246           !isa<ConstantExpr>(CPV);
247 }
248
249 bool ConstantInt::classof(const Constant *CPV) {
250   return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
251 }
252 bool ConstantSInt::classof(const Constant *CPV) {
253   return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
254 }
255 bool ConstantUInt::classof(const Constant *CPV) {
256   return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
257 }
258 bool ConstantFP::classof(const Constant *CPV) {
259   const Type *Ty = CPV->getType();
260   return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
261           !isa<ConstantExpr>(CPV));
262 }
263 bool ConstantArray::classof(const Constant *CPV) {
264   return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
265 }
266 bool ConstantStruct::classof(const Constant *CPV) {
267   return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
268 }
269 bool ConstantPointer::classof(const Constant *CPV) {
270   return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
271 }
272
273
274
275 //===----------------------------------------------------------------------===//
276 //                      isValueValidForType implementations
277
278 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
279   switch (Ty->getPrimitiveID()) {
280   default:
281     return false;         // These can't be represented as integers!!!
282
283     // Signed types...
284   case Type::SByteTyID:
285     return (Val <= INT8_MAX && Val >= INT8_MIN);
286   case Type::ShortTyID:
287     return (Val <= INT16_MAX && Val >= INT16_MIN);
288   case Type::IntTyID:
289     return (Val <= INT32_MAX && Val >= INT32_MIN);
290   case Type::LongTyID:
291     return true;          // This is the largest type...
292   }
293   assert(0 && "WTF?");
294   return false;
295 }
296
297 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
298   switch (Ty->getPrimitiveID()) {
299   default:
300     return false;         // These can't be represented as integers!!!
301
302     // Unsigned types...
303   case Type::UByteTyID:
304     return (Val <= UINT8_MAX);
305   case Type::UShortTyID:
306     return (Val <= UINT16_MAX);
307   case Type::UIntTyID:
308     return (Val <= UINT32_MAX);
309   case Type::ULongTyID:
310     return true;          // This is the largest type...
311   }
312   assert(0 && "WTF?");
313   return false;
314 }
315
316 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
317   switch (Ty->getPrimitiveID()) {
318   default:
319     return false;         // These can't be represented as floating point!
320
321     // TODO: Figure out how to test if a double can be cast to a float!
322   case Type::FloatTyID:
323     /*
324     return (Val <= UINT8_MAX);
325     */
326   case Type::DoubleTyID:
327     return true;          // This is the largest type...
328   }
329 };
330
331 //===----------------------------------------------------------------------===//
332 //                      Factory Function Implementation
333
334 template<class ValType, class ConstantClass>
335 struct ValueMap {
336   typedef pair<const Type*, ValType> ConstHashKey;
337   map<ConstHashKey, ConstantClass *> Map;
338
339   inline ConstantClass *get(const Type *Ty, ValType V) {
340     typename map<ConstHashKey,ConstantClass *>::iterator I =
341       Map.find(ConstHashKey(Ty, V));
342     return (I != Map.end()) ? I->second : 0;
343   }
344
345   inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
346     Map.insert(make_pair(ConstHashKey(Ty, V), CP));
347   }
348
349   inline void remove(ConstantClass *CP) {
350     for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
351                                                       E = Map.end(); I != E;++I)
352       if (I->second == CP) {
353         Map.erase(I);
354         return;
355       }
356   }
357 };
358
359 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
360 //
361 static ValueMap<uint64_t, ConstantInt> IntConstants;
362
363 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
364   ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
365   if (!Result)   // If no preexisting value, create one now...
366     IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
367   return Result;
368 }
369
370 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
371   ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
372   if (!Result)   // If no preexisting value, create one now...
373     IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
374   return Result;
375 }
376
377 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
378   assert(V <= 127 && "Can only be used with very small positive constants!");
379   if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
380   return ConstantUInt::get(Ty, V);
381 }
382
383 //---- ConstantFP::get() implementation...
384 //
385 static ValueMap<double, ConstantFP> FPConstants;
386
387 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
388   ConstantFP *Result = FPConstants.get(Ty, V);
389   if (!Result)   // If no preexisting value, create one now...
390     FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
391   return Result;
392 }
393
394 //---- ConstantArray::get() implementation...
395 //
396 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
397
398 ConstantArray *ConstantArray::get(const ArrayType *Ty,
399                                   const std::vector<Constant*> &V) {
400   ConstantArray *Result = ArrayConstants.get(Ty, V);
401   if (!Result)   // If no preexisting value, create one now...
402     ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
403   return Result;
404 }
405
406 // ConstantArray::get(const string&) - Return an array that is initialized to
407 // contain the specified string.  A null terminator is added to the specified
408 // string so that it may be used in a natural way...
409 //
410 ConstantArray *ConstantArray::get(const std::string &Str) {
411   std::vector<Constant*> ElementVals;
412
413   for (unsigned i = 0; i < Str.length(); ++i)
414     ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
415
416   // Add a null terminator to the string...
417   ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
418
419   ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
420   return ConstantArray::get(ATy, ElementVals);
421 }
422
423
424 // destroyConstant - Remove the constant from the constant table...
425 //
426 void ConstantArray::destroyConstant() {
427   ArrayConstants.remove(this);
428   destroyConstantImpl();
429 }
430
431 //---- ConstantStruct::get() implementation...
432 //
433 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
434
435 ConstantStruct *ConstantStruct::get(const StructType *Ty,
436                                     const std::vector<Constant*> &V) {
437   ConstantStruct *Result = StructConstants.get(Ty, V);
438   if (!Result)   // If no preexisting value, create one now...
439     StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
440   return Result;
441 }
442
443 // destroyConstant - Remove the constant from the constant table...
444 //
445 void ConstantStruct::destroyConstant() {
446   StructConstants.remove(this);
447   destroyConstantImpl();
448 }
449
450 //---- ConstantPointerNull::get() implementation...
451 //
452 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
453
454 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
455   ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
456   if (!Result)   // If no preexisting value, create one now...
457     NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
458   return Result;
459 }
460
461 //---- ConstantPointerRef::get() implementation...
462 //
463 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
464   assert(GV->getParent() && "Global Value must be attached to a module!");
465   
466   // The Module handles the pointer reference sharing...
467   return GV->getParent()->getConstantPointerRef(GV);
468 }
469
470 //---- ConstantExpr::get() implementations...
471 //
472 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
473 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
474
475 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C, const Type *Ty) {
476
477   // Look up the constant in the table first to ensure uniqueness
478   vector<Constant*> argVec(1, C);
479   const ExprMapKeyType &Key = make_pair(Opcode, argVec);
480   ConstantExpr *Result = ExprConstants.get(Ty, Key);
481   if (Result) return Result;
482   
483   // Its not in the table so create a new one and put it in the table.
484   // Check the operands for consistency first
485   assert(Opcode == Instruction::Cast ||
486          (Opcode >= Instruction::FirstUnaryOp &&
487           Opcode < Instruction::NumUnaryOps) &&
488          "Invalid opcode in unary ConstantExpr!");
489
490   // type of operand will not match result for Cast operation
491   assert((Opcode == Instruction::Cast || Ty == C->getType()) &&
492          "Type of operand in unary constant expression should match result");
493   
494   Result = new ConstantExpr(Opcode, C, Ty);
495   ExprConstants.add(Ty, Key, Result);
496   return Result;
497 }
498
499 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
500   // Look up the constant in the table first to ensure uniqueness
501   vector<Constant*> argVec(1, C1); argVec.push_back(C2);
502   const ExprMapKeyType &Key = make_pair(Opcode, argVec);
503   ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
504   if (Result) return Result;
505   
506   // Its not in the table so create a new one and put it in the table.
507   // Check the operands for consistency first
508   assert((Opcode >= Instruction::FirstBinaryOp &&
509           Opcode < Instruction::NumBinaryOps) &&
510          "Invalid opcode in binary constant expression");
511
512   assert(C1->getType() == C2->getType() &&
513          "Operand types in binary constant expression should match");
514   
515   Result = new ConstantExpr(Opcode, C1, C2);
516   ExprConstants.add(C1->getType(), Key, Result);
517   return Result;
518 }
519
520 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
521                                         const std::vector<Constant*> &IdxList) {
522   const Type *Ty = C->getType();
523
524   // Look up the constant in the table first to ensure uniqueness
525   vector<Constant*> argVec(1, C);
526   argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
527   
528   const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
529   ConstantExpr *Result = ExprConstants.get(Ty, Key);
530   if (Result) return Result;
531
532   // Its not in the table so create a new one and put it in the table.
533   // Check the operands for consistency first
534   // 
535   assert(isa<PointerType>(Ty) &&
536          "Non-pointer type for constant GelElementPtr expression");
537
538   // Check that the indices list is valid...
539   std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
540   const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
541   assert(DestTy && "Invalid index list for constant GelElementPtr expression");
542   
543   Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
544   ExprConstants.add(Ty, Key, Result);
545   return Result;
546 }
547
548 // destroyConstant - Remove the constant from the constant table...
549 //
550 void ConstantExpr::destroyConstant() {
551   ExprConstants.remove(this);
552   destroyConstantImpl();
553 }
554
555 const char *ConstantExpr::getOpcodeName() const {
556   return Instruction::getOpcodeName(getOpcode());
557 }
558
559
560 //---- ConstantPointerRef::mutateReferences() implementation...
561 //
562 unsigned ConstantPointerRef::mutateReferences(Value *OldV, Value *NewV) {
563   assert(getValue() == OldV && "Cannot mutate old value if I'm not using it!");
564   GlobalValue *NewGV = cast<GlobalValue>(NewV);
565   getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);
566   Operands[0] = NewGV;
567   return 1;
568 }
569
570
571 //---- ConstantPointerExpr::mutateReferences() implementation...
572 //
573 unsigned ConstantExpr::mutateReferences(Value* OldV, Value *NewV) {
574   unsigned NumReplaced = 0;
575   Constant *NewC = cast<Constant>(NewV);
576   for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
577     if (Operands[i] == OldV) {
578       ++NumReplaced;
579       Operands[i] = NewC;
580     }
581   return NumReplaced;
582 }