1 //===-- Constants.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/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"
22 ConstantBool *ConstantBool::True = new ConstantBool(true);
23 ConstantBool *ConstantBool::False = new ConstantBool(false);
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
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!");
34 if (Name.size()) ST->insert(Name, this);
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.
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: "
53 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
54 Constant *CPV = cast<Constant>(V);
55 CPV->destroyConstant();
57 // The constant should remove itself from our use list...
58 assert((use_empty() || use_back() != V) && "Constant not removed!");
61 // Value has no outstanding references it is safe to delete it now...
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);
72 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
75 case Type::UShortTyID:
77 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
80 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
82 case Type::PointerTyID:
83 return ConstantPointerNull::get(cast<PointerType>(Ty));
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;
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);
104 case Type::UByteTyID:
105 case Type::UShortTyID:
107 case Type::ULongTyID: return getAllOnesValue(Ty);
110 assert(0 && "Non-integral type specified!");
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:
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);
130 case Type::UByteTyID:
131 case Type::UShortTyID:
133 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
136 assert(0 && "Non-integral type specified!");
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:
148 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
150 case Type::UByteTyID:
151 case Type::UShortTyID:
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);
161 assert(0 && "Non-integral type specified!");
167 //===----------------------------------------------------------------------===//
168 // ConstantXXX Classes
169 //===----------------------------------------------------------------------===//
171 //===----------------------------------------------------------------------===//
172 // Normal Constructors
174 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
178 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
182 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
183 assert(isValueValidForType(Ty, V) && "Value too large for type!");
186 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
187 assert(isValueValidForType(Ty, V) && "Value too large for type!");
190 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
191 assert(isValueValidForType(Ty, V) && "Value too large for type!");
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));
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));
214 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
215 : ConstantPointer(GV->getType()) {
216 Operands.push_back(Use(GV, this));
219 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
220 : Constant(Ty), iType(Opcode) {
221 Operands.push_back(Use(C, this));
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));
230 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
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));
241 //===----------------------------------------------------------------------===//
242 // classof implementations
244 bool ConstantIntegral::classof(const Constant *CPV) {
245 return (CPV->getType()->isIntegral() || CPV->getType() == Type::BoolTy) &&
246 !isa<ConstantExpr>(CPV);
249 bool ConstantInt::classof(const Constant *CPV) {
250 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
252 bool ConstantSInt::classof(const Constant *CPV) {
253 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
255 bool ConstantUInt::classof(const Constant *CPV) {
256 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
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));
263 bool ConstantArray::classof(const Constant *CPV) {
264 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
266 bool ConstantStruct::classof(const Constant *CPV) {
267 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
269 bool ConstantPointer::classof(const Constant *CPV) {
270 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
275 //===----------------------------------------------------------------------===//
276 // isValueValidForType implementations
278 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
279 switch (Ty->getPrimitiveID()) {
281 return false; // These can't be represented as integers!!!
284 case Type::SByteTyID:
285 return (Val <= INT8_MAX && Val >= INT8_MIN);
286 case Type::ShortTyID:
287 return (Val <= INT16_MAX && Val >= INT16_MIN);
289 return (Val <= INT32_MAX && Val >= INT32_MIN);
291 return true; // This is the largest type...
297 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
298 switch (Ty->getPrimitiveID()) {
300 return false; // These can't be represented as integers!!!
303 case Type::UByteTyID:
304 return (Val <= UINT8_MAX);
305 case Type::UShortTyID:
306 return (Val <= UINT16_MAX);
308 return (Val <= UINT32_MAX);
309 case Type::ULongTyID:
310 return true; // This is the largest type...
316 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
317 switch (Ty->getPrimitiveID()) {
319 return false; // These can't be represented as floating point!
321 // TODO: Figure out how to test if a double can be cast to a float!
322 case Type::FloatTyID:
324 return (Val <= UINT8_MAX);
326 case Type::DoubleTyID:
327 return true; // This is the largest type...
331 //===----------------------------------------------------------------------===//
332 // Factory Function Implementation
334 template<class ValType, class ConstantClass>
336 typedef pair<const Type*, ValType> ConstHashKey;
337 map<ConstHashKey, ConstantClass *> Map;
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;
345 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
346 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
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) {
359 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
361 static ValueMap<uint64_t, ConstantInt> IntConstants;
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));
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));
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);
383 //---- ConstantFP::get() implementation...
385 static ValueMap<double, ConstantFP> FPConstants;
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));
394 //---- ConstantArray::get() implementation...
396 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
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));
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...
410 ConstantArray *ConstantArray::get(const std::string &Str) {
411 std::vector<Constant*> ElementVals;
413 for (unsigned i = 0; i < Str.length(); ++i)
414 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
416 // Add a null terminator to the string...
417 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
419 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
420 return ConstantArray::get(ATy, ElementVals);
424 // destroyConstant - Remove the constant from the constant table...
426 void ConstantArray::destroyConstant() {
427 ArrayConstants.remove(this);
428 destroyConstantImpl();
431 //---- ConstantStruct::get() implementation...
433 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
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));
443 // destroyConstant - Remove the constant from the constant table...
445 void ConstantStruct::destroyConstant() {
446 StructConstants.remove(this);
447 destroyConstantImpl();
450 //---- ConstantPointerNull::get() implementation...
452 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
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));
461 //---- ConstantPointerRef::get() implementation...
463 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
464 assert(GV->getParent() && "Global Value must be attached to a module!");
466 // The Module handles the pointer reference sharing...
467 return GV->getParent()->getConstantPointerRef(GV);
470 //---- ConstantExpr::get() implementations...
472 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
473 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
475 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C, const Type *Ty) {
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;
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!");
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");
494 Result = new ConstantExpr(Opcode, C, Ty);
495 ExprConstants.add(Ty, Key, Result);
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;
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");
512 assert(C1->getType() == C2->getType() &&
513 "Operand types in binary constant expression should match");
515 Result = new ConstantExpr(Opcode, C1, C2);
516 ExprConstants.add(C1->getType(), Key, Result);
520 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
521 const std::vector<Constant*> &IdxList) {
522 const Type *Ty = C->getType();
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());
528 const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
529 ConstantExpr *Result = ExprConstants.get(Ty, Key);
530 if (Result) return Result;
532 // Its not in the table so create a new one and put it in the table.
533 // Check the operands for consistency first
535 assert(isa<PointerType>(Ty) &&
536 "Non-pointer type for constant GelElementPtr expression");
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");
543 Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
544 ExprConstants.add(Ty, Key, Result);
548 // destroyConstant - Remove the constant from the constant table...
550 void ConstantExpr::destroyConstant() {
551 ExprConstants.remove(this);
552 destroyConstantImpl();
555 const char *ConstantExpr::getOpcodeName() const {
556 return Instruction::getOpcodeName(getOpcode());
560 //---- ConstantPointerRef::mutateReferences() implementation...
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);
571 //---- ConstantPointerExpr::mutateReferences() implementation...
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) {