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