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