1 //===-- Constants.cpp - Implement Constant nodes -----------------*- C++ -*--=//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
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"
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 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.
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: "
52 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
53 Constant *CPV = cast<Constant>(V);
54 CPV->destroyConstant();
56 // The constant should remove itself from our use list...
57 assert((use_empty() || use_back() != V) && "Constant not removed!");
60 // Value has no outstanding references it is safe to delete it now...
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);
71 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
74 case Type::UShortTyID:
76 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
79 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
81 case Type::PointerTyID:
82 return ConstantPointerNull::get(cast<PointerType>(Ty));
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;
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);
103 case Type::UByteTyID:
104 case Type::UShortTyID:
106 case Type::ULongTyID: return getAllOnesValue(Ty);
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:
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);
127 case Type::UByteTyID:
128 case Type::UShortTyID:
130 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
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:
143 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
145 case Type::UByteTyID:
146 case Type::UShortTyID:
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);
160 //===----------------------------------------------------------------------===//
161 // ConstantXXX Classes
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
165 // Normal Constructors
167 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
171 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
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!");
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!");
187 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
188 assert(isValueValidForType(Ty, V) && "Value too large for type!");
192 ConstantArray::ConstantArray(const ArrayType *T,
193 const std::vector<Constant*> &V) : Constant(T) {
194 Operands.reserve(V.size());
195 for (unsigned i = 0, e = V.size(); i != e; ++i) {
196 assert(V[i]->getType() == T->getElementType());
197 Operands.push_back(Use(V[i], this));
201 ConstantStruct::ConstantStruct(const StructType *T,
202 const std::vector<Constant*> &V) : Constant(T) {
203 const StructType::ElementTypes &ETypes = T->getElementTypes();
204 assert(V.size() == ETypes.size() &&
205 "Invalid initializer vector for constant structure");
206 Operands.reserve(V.size());
207 for (unsigned i = 0, e = V.size(); i != e; ++i) {
208 assert(V[i]->getType() == ETypes[i]);
209 Operands.push_back(Use(V[i], this));
213 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
214 : ConstantPointer(GV->getType()) {
215 Operands.push_back(Use(GV, this));
218 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
219 : Constant(Ty), iType(Opcode) {
220 Operands.push_back(Use(C, this));
223 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
224 : Constant(C1->getType()), iType(Opcode) {
225 Operands.push_back(Use(C1, this));
226 Operands.push_back(Use(C2, this));
229 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
231 : Constant(DestTy), iType(Instruction::GetElementPtr) {
232 Operands.reserve(1+IdxList.size());
233 Operands.push_back(Use(C, this));
234 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
235 Operands.push_back(Use(IdxList[i], this));
240 //===----------------------------------------------------------------------===//
241 // classof implementations
243 bool ConstantIntegral::classof(const Constant *CPV) {
244 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
247 bool ConstantInt::classof(const Constant *CPV) {
248 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
250 bool ConstantSInt::classof(const Constant *CPV) {
251 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
253 bool ConstantUInt::classof(const Constant *CPV) {
254 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
256 bool ConstantFP::classof(const Constant *CPV) {
257 const Type *Ty = CPV->getType();
258 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
259 !isa<ConstantExpr>(CPV));
261 bool ConstantArray::classof(const Constant *CPV) {
262 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
264 bool ConstantStruct::classof(const Constant *CPV) {
265 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
267 bool ConstantPointer::classof(const Constant *CPV) {
268 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
273 //===----------------------------------------------------------------------===//
274 // isValueValidForType implementations
276 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
277 switch (Ty->getPrimitiveID()) {
279 return false; // These can't be represented as integers!!!
282 case Type::SByteTyID:
283 return (Val <= INT8_MAX && Val >= INT8_MIN);
284 case Type::ShortTyID:
285 return (Val <= INT16_MAX && Val >= INT16_MIN);
287 return (Val <= INT32_MAX && Val >= INT32_MIN);
289 return true; // This is the largest type...
295 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
296 switch (Ty->getPrimitiveID()) {
298 return false; // These can't be represented as integers!!!
301 case Type::UByteTyID:
302 return (Val <= UINT8_MAX);
303 case Type::UShortTyID:
304 return (Val <= UINT16_MAX);
306 return (Val <= UINT32_MAX);
307 case Type::ULongTyID:
308 return true; // This is the largest type...
314 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
315 switch (Ty->getPrimitiveID()) {
317 return false; // These can't be represented as floating point!
319 // TODO: Figure out how to test if a double can be cast to a float!
320 case Type::FloatTyID:
322 return (Val <= UINT8_MAX);
324 case Type::DoubleTyID:
325 return true; // This is the largest type...
329 //===----------------------------------------------------------------------===//
330 // replaceUsesOfWithOnConstant implementations
332 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To) {
333 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
335 std::vector<Constant*> Values;
336 Values.reserve(getValues().size()); // Build replacement array...
337 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
338 Constant *Val = cast<Constant>(getValues()[i]);
339 if (Val == From) Val = cast<Constant>(To);
340 Values.push_back(Val);
343 ConstantArray *Replacement = ConstantArray::get(getType(), Values);
344 assert(Replacement != this && "I didn't contain From!");
346 // Everyone using this now uses the replacement...
347 replaceAllUsesWith(Replacement);
349 // Delete the old constant!
353 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To) {
354 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
356 std::vector<Constant*> Values;
357 Values.reserve(getValues().size());
358 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
359 Constant *Val = cast<Constant>(getValues()[i]);
360 if (Val == From) Val = cast<Constant>(To);
361 Values.push_back(Val);
364 ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
365 assert(Replacement != this && "I didn't contain From!");
367 // Everyone using this now uses the replacement...
368 replaceAllUsesWith(Replacement);
370 // Delete the old constant!
374 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To) {
375 if (isa<GlobalValue>(To)) {
376 assert(From == getOperand(0) && "Doesn't contain from!");
377 ConstantPointerRef *Replacement =
378 ConstantPointerRef::get(cast<GlobalValue>(To));
380 // Everyone using this now uses the replacement...
381 replaceAllUsesWith(Replacement);
383 // Delete the old constant!
386 // Just replace ourselves with the To value specified.
387 replaceAllUsesWith(To);
389 // Delete the old constant!
394 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *To) {
395 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
397 ConstantExpr *Replacement = 0;
398 if (getOpcode() == Instruction::GetElementPtr) {
399 std::vector<Constant*> Indices;
400 Constant *Pointer = cast<Constant>(getOperand(0));
401 Indices.reserve(getNumOperands()-1);
402 if (Pointer == From) Pointer = cast<Constant>(To);
404 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
405 Constant *Val = cast<Constant>(getOperand(i));
406 if (Val == From) Val = cast<Constant>(To);
407 Indices.push_back(Val);
409 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
410 } else if (getOpcode() == Instruction::Cast) {
411 assert(getOperand(0) == From && "Cast only has one use!");
412 Replacement = ConstantExpr::getCast(cast<Constant>(To), getType());
413 } else if (getNumOperands() == 2) {
414 Constant *C1 = cast<Constant>(getOperand(0));
415 Constant *C2 = cast<Constant>(getOperand(1));
416 if (C1 == From) C1 = cast<Constant>(To);
417 if (C2 == From) C2 = cast<Constant>(To);
418 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
420 assert(0 && "Unknown ConstantExpr type!");
424 assert(Replacement != this && "I didn't contain From!");
426 // Everyone using this now uses the replacement...
427 replaceAllUsesWith(Replacement);
429 // Delete the old constant!
435 //===----------------------------------------------------------------------===//
436 // Factory Function Implementation
438 template<class ValType, class ConstantClass>
440 typedef pair<const Type*, ValType> ConstHashKey;
441 map<ConstHashKey, ConstantClass *> Map;
443 inline ConstantClass *get(const Type *Ty, ValType V) {
444 typename map<ConstHashKey,ConstantClass *>::iterator I =
445 Map.find(ConstHashKey(Ty, V));
446 return (I != Map.end()) ? I->second : 0;
449 inline void add(const Type *Ty, ValType V, ConstantClass *CP) {
450 Map.insert(make_pair(ConstHashKey(Ty, V), CP));
453 inline void remove(ConstantClass *CP) {
454 for (typename map<ConstHashKey,ConstantClass *>::iterator I = Map.begin(),
455 E = Map.end(); I != E;++I)
456 if (I->second == CP) {
463 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
465 static ValueMap<uint64_t, ConstantInt> IntConstants;
467 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
468 ConstantSInt *Result = (ConstantSInt*)IntConstants.get(Ty, (uint64_t)V);
469 if (!Result) // If no preexisting value, create one now...
470 IntConstants.add(Ty, V, Result = new ConstantSInt(Ty, V));
474 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
475 ConstantUInt *Result = (ConstantUInt*)IntConstants.get(Ty, V);
476 if (!Result) // If no preexisting value, create one now...
477 IntConstants.add(Ty, V, Result = new ConstantUInt(Ty, V));
481 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
482 assert(V <= 127 && "Can only be used with very small positive constants!");
483 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
484 return ConstantUInt::get(Ty, V);
487 //---- ConstantFP::get() implementation...
489 static ValueMap<double, ConstantFP> FPConstants;
491 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
492 ConstantFP *Result = FPConstants.get(Ty, V);
493 if (!Result) // If no preexisting value, create one now...
494 FPConstants.add(Ty, V, Result = new ConstantFP(Ty, V));
498 //---- ConstantArray::get() implementation...
500 static ValueMap<std::vector<Constant*>, ConstantArray> ArrayConstants;
502 ConstantArray *ConstantArray::get(const ArrayType *Ty,
503 const std::vector<Constant*> &V) {
504 ConstantArray *Result = ArrayConstants.get(Ty, V);
505 if (!Result) // If no preexisting value, create one now...
506 ArrayConstants.add(Ty, V, Result = new ConstantArray(Ty, V));
510 // ConstantArray::get(const string&) - Return an array that is initialized to
511 // contain the specified string. A null terminator is added to the specified
512 // string so that it may be used in a natural way...
514 ConstantArray *ConstantArray::get(const std::string &Str) {
515 std::vector<Constant*> ElementVals;
517 for (unsigned i = 0; i < Str.length(); ++i)
518 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
520 // Add a null terminator to the string...
521 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
523 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
524 return ConstantArray::get(ATy, ElementVals);
528 // destroyConstant - Remove the constant from the constant table...
530 void ConstantArray::destroyConstant() {
531 ArrayConstants.remove(this);
532 destroyConstantImpl();
535 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
536 // then this method converts the array to an std::string and returns it.
537 // Otherwise, it asserts out.
539 std::string ConstantArray::getAsString() const {
541 if (getType()->getElementType() == Type::SByteTy)
542 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
543 Result += (char)cast<ConstantSInt>(getOperand(i))->getValue();
545 assert(getType()->getElementType() == Type::UByteTy && "Not a string!");
546 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
547 Result += (char)cast<ConstantUInt>(getOperand(i))->getValue();
553 //---- ConstantStruct::get() implementation...
555 static ValueMap<std::vector<Constant*>, ConstantStruct> StructConstants;
557 ConstantStruct *ConstantStruct::get(const StructType *Ty,
558 const std::vector<Constant*> &V) {
559 ConstantStruct *Result = StructConstants.get(Ty, V);
560 if (!Result) // If no preexisting value, create one now...
561 StructConstants.add(Ty, V, Result = new ConstantStruct(Ty, V));
565 // destroyConstant - Remove the constant from the constant table...
567 void ConstantStruct::destroyConstant() {
568 StructConstants.remove(this);
569 destroyConstantImpl();
573 //---- ConstantPointerNull::get() implementation...
575 static ValueMap<char, ConstantPointerNull> NullPtrConstants;
577 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
578 ConstantPointerNull *Result = NullPtrConstants.get(Ty, 0);
579 if (!Result) // If no preexisting value, create one now...
580 NullPtrConstants.add(Ty, 0, Result = new ConstantPointerNull(Ty));
584 // destroyConstant - Remove the constant from the constant table...
586 void ConstantPointerNull::destroyConstant() {
587 NullPtrConstants.remove(this);
588 destroyConstantImpl();
592 //---- ConstantPointerRef::get() implementation...
594 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
595 assert(GV->getParent() && "Global Value must be attached to a module!");
597 // The Module handles the pointer reference sharing...
598 return GV->getParent()->getConstantPointerRef(GV);
601 // destroyConstant - Remove the constant from the constant table...
603 void ConstantPointerRef::destroyConstant() {
604 getValue()->getParent()->destroyConstantPointerRef(this);
605 destroyConstantImpl();
609 //---- ConstantExpr::get() implementations...
611 typedef pair<unsigned, vector<Constant*> > ExprMapKeyType;
612 static ValueMap<const ExprMapKeyType, ConstantExpr> ExprConstants;
614 ConstantExpr *ConstantExpr::getCast(Constant *C, const Type *Ty) {
616 // Look up the constant in the table first to ensure uniqueness
617 vector<Constant*> argVec(1, C);
618 const ExprMapKeyType &Key = make_pair(Instruction::Cast, argVec);
619 ConstantExpr *Result = ExprConstants.get(Ty, Key);
620 if (Result) return Result;
622 // Its not in the table so create a new one and put it in the table.
623 Result = new ConstantExpr(Instruction::Cast, C, Ty);
624 ExprConstants.add(Ty, Key, Result);
628 ConstantExpr *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
629 // Look up the constant in the table first to ensure uniqueness
630 vector<Constant*> argVec(1, C1); argVec.push_back(C2);
631 const ExprMapKeyType &Key = make_pair(Opcode, argVec);
632 ConstantExpr *Result = ExprConstants.get(C1->getType(), Key);
633 if (Result) return Result;
635 // Its not in the table so create a new one and put it in the table.
636 // Check the operands for consistency first
637 assert((Opcode >= Instruction::BinaryOpsBegin &&
638 Opcode < Instruction::BinaryOpsEnd) &&
639 "Invalid opcode in binary constant expression");
641 assert(C1->getType() == C2->getType() &&
642 "Operand types in binary constant expression should match");
644 Result = new ConstantExpr(Opcode, C1, C2);
645 ExprConstants.add(C1->getType(), Key, Result);
649 ConstantExpr *ConstantExpr::getGetElementPtr(Constant *C,
650 const std::vector<Constant*> &IdxList) {
651 const Type *Ty = C->getType();
653 // Look up the constant in the table first to ensure uniqueness
654 vector<Constant*> argVec(1, C);
655 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
657 const ExprMapKeyType &Key = make_pair(Instruction::GetElementPtr, argVec);
658 ConstantExpr *Result = ExprConstants.get(Ty, Key);
659 if (Result) return Result;
661 // Its not in the table so create a new one and put it in the table.
662 // Check the operands for consistency first
664 assert(isa<PointerType>(Ty) &&
665 "Non-pointer type for constant GelElementPtr expression");
667 // Check that the indices list is valid...
668 std::vector<Value*> ValIdxList(IdxList.begin(), IdxList.end());
669 const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList, true);
670 assert(DestTy && "Invalid index list for constant GelElementPtr expression");
672 Result = new ConstantExpr(C, IdxList, PointerType::get(DestTy));
673 ExprConstants.add(Ty, Key, Result);
677 // destroyConstant - Remove the constant from the constant table...
679 void ConstantExpr::destroyConstant() {
680 ExprConstants.remove(this);
681 destroyConstantImpl();
684 const char *ConstantExpr::getOpcodeName() const {
685 return Instruction::getOpcodeName(getOpcode());
688 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
689 // Uses of constant pointer refs are global values, not constants!
690 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
691 GlobalValue *NewGV = cast<GlobalValue>(NewV);
692 GlobalValue *OldGV = CPR->getValue();
694 assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
696 OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
700 Constant *NewC = cast<Constant>(NewV);
701 unsigned NumReplaced = 0;
702 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
703 if (Operands[i] == OldV) {