1 //===-- ConstantVals.cpp - Implement Constant nodes --------------*- C++ -*--=//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
7 #define __STDC_LIMIT_MACROS // Get defs for INT64_MAX and friends...
8 #include "llvm/ConstantVals.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/SymbolTable.h"
11 #include "llvm/GlobalValue.h"
12 #include "llvm/Module.h"
13 #include "llvm/SlotCalculator.h"
14 #include "Support/StringExtras.h"
21 ConstantBool *ConstantBool::True = new ConstantBool(true);
22 ConstantBool *ConstantBool::False = new ConstantBool(false);
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
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!");
33 if (Name.size()) ST->insert(Name, this);
36 // Static constructor to create a '0' constant of arbitrary type...
37 Constant *Constant::getNullConstant(const Type *Ty) {
38 switch (Ty->getPrimitiveID()) {
39 case Type::BoolTyID: return ConstantBool::get(false);
43 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
46 case Type::UShortTyID:
48 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
51 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
53 case Type::PointerTyID:
54 return ConstantPointerNull::get(cast<PointerType>(Ty));
60 void Constant::destroyConstantImpl() {
61 // When a Constant is destroyed, there may be lingering
62 // references to the constant by other constants in the constant pool. These
63 // constants are implicitly dependant on the module that is being deleted,
64 // but they don't know that. Because we only find out when the CPV is
65 // deleted, we must now notify all of our users (that should only be
66 // Constants) that they are, in fact, invalid now and should be deleted.
68 while (!use_empty()) {
69 Value *V = use_back();
70 #ifndef NDEBUG // Only in -g mode...
71 if (!isa<Constant>(V)) {
72 std::cerr << "While deleting: ";
74 std::cerr << "\nUse still stuck around after Def is destroyed: ";
79 assert(isa<Constant>(V) && "References remain to ConstantPointerRef!");
80 Constant *CPV = cast<Constant>(V);
81 CPV->destroyConstant();
83 // The constant should remove itself from our use list...
84 assert((use_empty() || use_back() == V) && "Constant not removed!");
87 // Value has no outstanding references it is safe to delete it now...
91 //===----------------------------------------------------------------------===//
92 // ConstantXXX Classes
93 //===----------------------------------------------------------------------===//
95 //===----------------------------------------------------------------------===//
96 // Normal Constructors
98 ConstantBool::ConstantBool(bool V) : Constant(Type::BoolTy) {
102 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : Constant(Ty) {
106 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
107 assert(isValueValidForType(Ty, V) && "Value too large for type!");
110 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
111 assert(isValueValidForType(Ty, V) && "Value too large for type!");
114 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
115 assert(isValueValidForType(Ty, V) && "Value too large for type!");
119 ConstantArray::ConstantArray(const ArrayType *T,
120 const std::vector<Constant*> &V) : Constant(T) {
121 for (unsigned i = 0; i < V.size(); i++) {
122 assert(V[i]->getType() == T->getElementType());
123 Operands.push_back(Use(V[i], this));
127 ConstantStruct::ConstantStruct(const StructType *T,
128 const std::vector<Constant*> &V) : Constant(T) {
129 const StructType::ElementTypes &ETypes = T->getElementTypes();
131 for (unsigned i = 0; i < V.size(); i++) {
132 assert(V[i]->getType() == ETypes[i]);
133 Operands.push_back(Use(V[i], this));
137 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
138 : ConstantPointer(GV->getType()) {
139 Operands.push_back(Use(GV, this));
144 //===----------------------------------------------------------------------===//
145 // getStrValue implementations
147 std::string ConstantBool::getStrValue() const {
148 return Val ? "true" : "false";
151 std::string ConstantSInt::getStrValue() const {
152 return itostr(Val.Signed);
155 std::string ConstantUInt::getStrValue() const {
156 return utostr(Val.Unsigned);
159 // ConstantFP::getStrValue - We would like to output the FP constant value in
160 // exponential notation, but we cannot do this if doing so will lose precision.
161 // Check here to make sure that we only output it in exponential format if we
162 // can parse the value back and get the same value.
164 std::string ConstantFP::getStrValue() const {
165 std::string StrVal = ftostr(Val);
167 // Check to make sure that the stringized number is not some string like "Inf"
168 // or NaN, that atof will accept, but the lexer will not. Check that the
169 // string matches the "[-+]?[0-9]" regex.
171 if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
172 ((StrVal[0] == '-' || StrVal[0] == '+') &&
173 (StrVal[0] >= '0' && StrVal[0] <= '9'))) {
174 double TestVal = atof(StrVal.c_str()); // Reparse stringized version!
179 // Otherwise we could not reparse it to exactly the same value, so we must
180 // output the string in hexadecimal format!
182 // Behave nicely in the face of C TBAA rules... see:
183 // http://www.nullstone.com/htmls/category/aliastyp.htm
185 char *Ptr = (char*)&Val;
186 assert(sizeof(double) == sizeof(uint64_t) && sizeof(double) == 8 &&
187 "assuming that double is 64 bits!");
188 return "0x"+utohexstr(*(uint64_t*)Ptr);
191 std::string ConstantArray::getStrValue() const {
194 // As a special case, print the array as a string if it is an array of
195 // ubytes or an array of sbytes with positive values.
197 const Type *ETy = cast<ArrayType>(getType())->getElementType();
198 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
200 if (ETy == Type::SByteTy) {
201 for (unsigned i = 0; i < Operands.size(); ++i)
202 if (ETy == Type::SByteTy &&
203 cast<ConstantSInt>(Operands[i])->getValue() < 0) {
211 for (unsigned i = 0; i < Operands.size(); ++i) {
212 unsigned char C = (ETy == Type::SByteTy) ?
213 (unsigned char)cast<ConstantSInt>(Operands[i])->getValue() :
214 (unsigned char)cast<ConstantUInt>(Operands[i])->getValue();
220 Result += ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
221 Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
228 if (Operands.size()) {
229 Result += " " + Operands[0]->getType()->getDescription() +
230 " " + cast<Constant>(Operands[0])->getStrValue();
231 for (unsigned i = 1; i < Operands.size(); i++)
232 Result += ", " + Operands[i]->getType()->getDescription() +
233 " " + cast<Constant>(Operands[i])->getStrValue();
241 std::string ConstantStruct::getStrValue() const {
242 std::string Result = "{";
243 if (Operands.size()) {
244 Result += " " + Operands[0]->getType()->getDescription() +
245 " " + cast<Constant>(Operands[0])->getStrValue();
246 for (unsigned i = 1; i < Operands.size(); i++)
247 Result += ", " + Operands[i]->getType()->getDescription() +
248 " " + cast<Constant>(Operands[i])->getStrValue();
251 return Result + " }";
254 std::string ConstantPointerNull::getStrValue() const {
258 std::string ConstantPointerRef::getStrValue() const {
259 const GlobalValue *V = getValue();
260 if (V->hasName()) return "%" + V->getName();
262 // FIXME: This is a gross hack.
263 SlotCalculator *Table = new SlotCalculator(V->getParent(), true);
264 int Slot = Table->getValSlot(V);
267 if (Slot >= 0) return std::string(" %") + itostr(Slot);
268 else return "<pointer reference badref>";
272 //===----------------------------------------------------------------------===//
273 // classof implementations
275 bool ConstantInt::classof(const Constant *CPV) {
276 return CPV->getType()->isIntegral();
278 bool ConstantSInt::classof(const Constant *CPV) {
279 return CPV->getType()->isSigned();
281 bool ConstantUInt::classof(const Constant *CPV) {
282 return CPV->getType()->isUnsigned();
284 bool ConstantFP::classof(const Constant *CPV) {
285 const Type *Ty = CPV->getType();
286 return Ty == Type::FloatTy || Ty == Type::DoubleTy;
288 bool ConstantArray::classof(const Constant *CPV) {
289 return isa<ArrayType>(CPV->getType());
291 bool ConstantStruct::classof(const Constant *CPV) {
292 return isa<StructType>(CPV->getType());
294 bool ConstantPointer::classof(const Constant *CPV) {
295 return isa<PointerType>(CPV->getType());
299 //===----------------------------------------------------------------------===//
300 // isValueValidForType implementations
302 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
303 switch (Ty->getPrimitiveID()) {
305 return false; // These can't be represented as integers!!!
308 case Type::SByteTyID:
309 return (Val <= INT8_MAX && Val >= INT8_MIN);
310 case Type::ShortTyID:
311 return (Val <= INT16_MAX && Val >= INT16_MIN);
313 return (Val <= INT32_MAX && Val >= INT32_MIN);
315 return true; // This is the largest type...
321 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
322 switch (Ty->getPrimitiveID()) {
324 return false; // These can't be represented as integers!!!
327 case Type::UByteTyID:
328 return (Val <= UINT8_MAX);
329 case Type::UShortTyID:
330 return (Val <= UINT16_MAX);
332 return (Val <= UINT32_MAX);
333 case Type::ULongTyID:
334 return true; // This is the largest type...
340 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
341 switch (Ty->getPrimitiveID()) {
343 return false; // These can't be represented as floating point!
345 // TODO: Figure out how to test if a double can be cast to a float!
346 case Type::FloatTyID:
348 return (Val <= UINT8_MAX);
350 case Type::DoubleTyID:
351 return true; // This is the largest type...
355 //===----------------------------------------------------------------------===//
356 // Hash Function Implementations
358 unsigned ConstantSInt::hash(const Type *Ty, int64_t V) {
359 return unsigned(Ty->getPrimitiveID() ^ V);
362 unsigned ConstantUInt::hash(const Type *Ty, uint64_t V) {
363 return unsigned(Ty->getPrimitiveID() ^ V);
366 unsigned ConstantFP::hash(const Type *Ty, double V) {
367 return Ty->getPrimitiveID() ^ unsigned(V);
370 unsigned ConstantArray::hash(const ArrayType *Ty,
371 const std::vector<Constant*> &V) {
372 unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
373 for (unsigned i = 0; i < V.size(); ++i)
374 Result ^= V[i]->getHash() << (i & 7);
378 unsigned ConstantStruct::hash(const StructType *Ty,
379 const std::vector<Constant*> &V) {
380 unsigned Result = (Ty->getUniqueID() << 5) ^ (Ty->getUniqueID() * 7);
381 for (unsigned i = 0; i < V.size(); ++i)
382 Result ^= V[i]->getHash() << (i & 7);
387 //===----------------------------------------------------------------------===//
388 // Factory Function Implementation
390 template<class ValType, class ConstantClass>
392 typedef pair<const Type*, ValType> ConstHashKey;
393 map<ConstHashKey, ConstantClass *> Map;
395 inline ConstantClass *get(const Type *Ty, ValType V) {
396 map<ConstHashKey,ConstantClass *>::iterator I =
397 Map.find(ConstHashKey(Ty, V));
398 return (I != Map.end()) ? I->second : 0;
401 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
402 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
405 inline void remove(ConstantClass *CP) {
406 for (map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
407 E = Map.end(); I != E;++I)
408 if (I->second == CP) {
415 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
417 static ValueMap<uint64_t, ConstantInt> IntConstants;
419 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
420 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
421 if (!Result) // If no preexisting value, create one now...
422 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
426 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
427 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
428 if (!Result) // If no preexisting value, create one now...
429 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
433 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
434 assert(V <= 127 && "Can only be used with very small positive constants!");
435 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
436 return ConstantUInt::get(Ty, V);
439 //---- ConstantFP::get() implementation...
441 static ValueMap<double, ConstantFP> FPConstants;
443 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
444 ConstantFP *Result = FPConstants.get(Ty, V);
445 if (!Result) // If no preexisting value, create one now...
446 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
450 //---- ConstantArray::get() implementation...
452 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
454 ConstantArray *ConstantArray::get(const ArrayType *Ty,
455 const std::vector<Constant*> &V) {
456 ConstantArray *Result = ArrayConstants.get(Ty, V);
457 if (!Result) // If no preexisting value, create one now...
458 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
462 // ConstantArray::get(const string&) - Return an array that is initialized to
463 // contain the specified string. A null terminator is added to the specified
464 // string so that it may be used in a natural way...
466 ConstantArray *ConstantArray::get(const std::string &Str) {
467 std::vector<Constant*> ElementVals;
469 for (unsigned i = 0; i < Str.length(); ++i)
470 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
472 // Add a null terminator to the string...
473 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
475 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
476 return ConstantArray::get(ATy, ElementVals);
480 // destroyConstant - Remove the constant from the constant table...
482 void ConstantArray::destroyConstant() {
483 ArrayConstants.remove(this);
484 destroyConstantImpl();
487 //---- ConstantStruct::get() implementation...
489 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
491 ConstantStruct *ConstantStruct::get(const StructType *Ty,
492 const std::vector<Constant*> &V) {
493 ConstantStruct *Result = StructConstants.get(Ty, V);
494 if (!Result) // If no preexisting value, create one now...
495 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
499 // destroyConstant - Remove the constant from the constant table...
501 void ConstantStruct::destroyConstant() {
502 StructConstants.remove(this);
503 destroyConstantImpl();
506 //---- ConstantPointerNull::get() implementation...
508 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
510 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
511 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
512 if (!Result) // If no preexisting value, create one now...
513 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
517 //---- ConstantPointerRef::get() implementation...
519 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
520 assert(GV->getParent() && "Global Value must be attached to a module!");
522 // The Module handles the pointer reference sharing...
523 return GV->getParent()->getConstantPointerRef(GV);
527 void ConstantPointerRef::mutateReference(GlobalValue *NewGV) {
528 getValue()->getParent()->mutateConstantPointerRef(getValue(), NewGV);