1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Constants.h"
8 #include "llvm/ConstantHandling.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/SymbolTable.h"
12 #include "llvm/Module.h"
13 #include "Support/StringExtras.h"
16 ConstantBool *ConstantBool::True = new ConstantBool(true);
17 ConstantBool *ConstantBool::False = new ConstantBool(false);
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // Specialize setName to take care of symbol table majik
25 void Constant::setName(const std::string &Name, SymbolTable *ST) {
26 assert(ST && "Type::setName - Must provide symbol table argument!");
28 if (Name.size()) ST->insert(Name, this);
31 void Constant::destroyConstantImpl() {
32 // When a Constant is destroyed, there may be lingering
33 // references to the constant by other constants in the constant pool. These
34 // constants are implicitly dependent on the module that is being deleted,
35 // but they don't know that. Because we only find out when the CPV is
36 // deleted, we must now notify all of our users (that should only be
37 // Constants) that they are, in fact, invalid now and should be deleted.
39 while (!use_empty()) {
40 Value *V = use_back();
41 #ifndef NDEBUG // Only in -g mode...
42 if (!isa<Constant>(V))
43 std::cerr << "While deleting: " << *this
44 << "\n\nUse still stuck around after Def is destroyed: "
47 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
48 Constant *CPV = cast<Constant>(V);
49 CPV->destroyConstant();
51 // The constant should remove itself from our use list...
52 assert((use_empty() || use_back() != V) && "Constant not removed!");
55 // Value has no outstanding references it is safe to delete it now...
59 // Static constructor to create a '0' constant of arbitrary type...
60 Constant *Constant::getNullValue(const Type *Ty) {
61 switch (Ty->getPrimitiveID()) {
62 case Type::BoolTyID: {
63 static Constant *NullBool = ConstantBool::get(false);
66 case Type::SByteTyID: {
67 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
70 case Type::UByteTyID: {
71 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
74 case Type::ShortTyID: {
75 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
78 case Type::UShortTyID: {
79 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
83 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
86 case Type::UIntTyID: {
87 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
90 case Type::LongTyID: {
91 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
94 case Type::ULongTyID: {
95 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
99 case Type::FloatTyID: {
100 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
103 case Type::DoubleTyID: {
104 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
108 case Type::PointerTyID:
109 return ConstantPointerNull::get(cast<PointerType>(Ty));
111 case Type::StructTyID: {
112 const StructType *ST = cast<StructType>(Ty);
113 const StructType::ElementTypes &ETs = ST->getElementTypes();
114 std::vector<Constant*> Elements;
115 Elements.resize(ETs.size());
116 for (unsigned i = 0, e = ETs.size(); i != e; ++i)
117 Elements[i] = Constant::getNullValue(ETs[i]);
118 return ConstantStruct::get(ST, Elements);
120 case Type::ArrayTyID: {
121 const ArrayType *AT = cast<ArrayType>(Ty);
122 Constant *El = Constant::getNullValue(AT->getElementType());
123 unsigned NumElements = AT->getNumElements();
124 return ConstantArray::get(AT, std::vector<Constant*>(NumElements, El));
127 // Function, Type, Label, or Opaque type?
128 assert(0 && "Cannot create a null constant of that type!");
133 // Static constructor to create the maximum constant of an integral type...
134 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
135 switch (Ty->getPrimitiveID()) {
136 case Type::BoolTyID: return ConstantBool::True;
137 case Type::SByteTyID:
138 case Type::ShortTyID:
140 case Type::LongTyID: {
141 // Calculate 011111111111111...
142 unsigned TypeBits = Ty->getPrimitiveSize()*8;
143 int64_t Val = INT64_MAX; // All ones
144 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
145 return ConstantSInt::get(Ty, Val);
148 case Type::UByteTyID:
149 case Type::UShortTyID:
151 case Type::ULongTyID: return getAllOnesValue(Ty);
157 // Static constructor to create the minimum constant for an integral type...
158 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
159 switch (Ty->getPrimitiveID()) {
160 case Type::BoolTyID: return ConstantBool::False;
161 case Type::SByteTyID:
162 case Type::ShortTyID:
164 case Type::LongTyID: {
165 // Calculate 1111111111000000000000
166 unsigned TypeBits = Ty->getPrimitiveSize()*8;
167 int64_t Val = -1; // All ones
168 Val <<= TypeBits-1; // Shift over to the right spot
169 return ConstantSInt::get(Ty, Val);
172 case Type::UByteTyID:
173 case Type::UShortTyID:
175 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
181 // Static constructor to create an integral constant with all bits set
182 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
183 switch (Ty->getPrimitiveID()) {
184 case Type::BoolTyID: return ConstantBool::True;
185 case Type::SByteTyID:
186 case Type::ShortTyID:
188 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
190 case Type::UByteTyID:
191 case Type::UShortTyID:
193 case Type::ULongTyID: {
194 // Calculate ~0 of the right type...
195 unsigned TypeBits = Ty->getPrimitiveSize()*8;
196 uint64_t Val = ~0ULL; // All ones
197 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
198 return ConstantUInt::get(Ty, Val);
204 bool ConstantUInt::isAllOnesValue() const {
205 unsigned TypeBits = getType()->getPrimitiveSize()*8;
206 uint64_t Val = ~0ULL; // All ones
207 Val >>= 64-TypeBits; // Shift out inappropriate bits
208 return getValue() == Val;
212 //===----------------------------------------------------------------------===//
213 // ConstantXXX Classes
214 //===----------------------------------------------------------------------===//
216 //===----------------------------------------------------------------------===//
217 // Normal Constructors
219 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
223 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
227 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
228 assert(Ty->isInteger() && Ty->isSigned() &&
229 "Illegal type for unsigned integer constant!");
230 assert(isValueValidForType(Ty, V) && "Value too large for type!");
233 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
234 assert(Ty->isInteger() && Ty->isUnsigned() &&
235 "Illegal type for unsigned integer constant!");
236 assert(isValueValidForType(Ty, V) && "Value too large for type!");
239 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
240 assert(isValueValidForType(Ty, V) && "Value too large for type!");
244 ConstantArray::ConstantArray(const ArrayType *T,
245 const std::vector<Constant*> &V) : Constant(T) {
246 Operands.reserve(V.size());
247 for (unsigned i = 0, e = V.size(); i != e; ++i) {
248 assert(V[i]->getType() == T->getElementType() ||
250 V[i]->getType()->getPrimitiveID() ==
251 T->getElementType()->getPrimitiveID()));
252 Operands.push_back(Use(V[i], this));
256 ConstantStruct::ConstantStruct(const StructType *T,
257 const std::vector<Constant*> &V) : Constant(T) {
258 const StructType::ElementTypes &ETypes = T->getElementTypes();
259 assert(V.size() == ETypes.size() &&
260 "Invalid initializer vector for constant structure");
261 Operands.reserve(V.size());
262 for (unsigned i = 0, e = V.size(); i != e; ++i) {
263 assert((V[i]->getType() == ETypes[i] ||
264 (ETypes[i]->isAbstract() &&
265 ETypes[i]->getPrimitiveID()==V[i]->getType()->getPrimitiveID())) &&
266 "Initializer for struct element doesn't match struct element type!");
267 Operands.push_back(Use(V[i], this));
271 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
272 : ConstantPointer(GV->getType()) {
273 Operands.push_back(Use(GV, this));
276 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
277 : Constant(Ty), iType(Opcode) {
278 Operands.push_back(Use(C, this));
281 static bool isSetCC(unsigned Opcode) {
282 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
283 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
284 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
287 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
288 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
289 Operands.push_back(Use(C1, this));
290 Operands.push_back(Use(C2, this));
293 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
295 : Constant(DestTy), iType(Instruction::GetElementPtr) {
296 Operands.reserve(1+IdxList.size());
297 Operands.push_back(Use(C, this));
298 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
299 Operands.push_back(Use(IdxList[i], this));
304 //===----------------------------------------------------------------------===//
305 // classof implementations
307 bool ConstantIntegral::classof(const Constant *CPV) {
308 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
311 bool ConstantInt::classof(const Constant *CPV) {
312 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
314 bool ConstantSInt::classof(const Constant *CPV) {
315 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
317 bool ConstantUInt::classof(const Constant *CPV) {
318 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
320 bool ConstantFP::classof(const Constant *CPV) {
321 const Type *Ty = CPV->getType();
322 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
323 !isa<ConstantExpr>(CPV));
325 bool ConstantArray::classof(const Constant *CPV) {
326 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
328 bool ConstantStruct::classof(const Constant *CPV) {
329 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
331 bool ConstantPointer::classof(const Constant *CPV) {
332 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
337 //===----------------------------------------------------------------------===//
338 // isValueValidForType implementations
340 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
341 switch (Ty->getPrimitiveID()) {
343 return false; // These can't be represented as integers!!!
346 case Type::SByteTyID:
347 return (Val <= INT8_MAX && Val >= INT8_MIN);
348 case Type::ShortTyID:
349 return (Val <= INT16_MAX && Val >= INT16_MIN);
351 return (Val <= INT32_MAX && Val >= INT32_MIN);
353 return true; // This is the largest type...
359 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
360 switch (Ty->getPrimitiveID()) {
362 return false; // These can't be represented as integers!!!
365 case Type::UByteTyID:
366 return (Val <= UINT8_MAX);
367 case Type::UShortTyID:
368 return (Val <= UINT16_MAX);
370 return (Val <= UINT32_MAX);
371 case Type::ULongTyID:
372 return true; // This is the largest type...
378 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
379 switch (Ty->getPrimitiveID()) {
381 return false; // These can't be represented as floating point!
383 // TODO: Figure out how to test if a double can be cast to a float!
384 case Type::FloatTyID:
385 case Type::DoubleTyID:
386 return true; // This is the largest type...
390 //===----------------------------------------------------------------------===//
391 // replaceUsesOfWithOnConstant implementations
393 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
394 bool DisableChecking) {
395 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
397 std::vector<Constant*> Values;
398 Values.reserve(getValues().size()); // Build replacement array...
399 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
400 Constant *Val = cast<Constant>(getValues()[i]);
401 if (Val == From) Val = cast<Constant>(To);
402 Values.push_back(Val);
405 ConstantArray *Replacement = ConstantArray::get(getType(), Values);
406 assert(Replacement != this && "I didn't contain From!");
408 // Everyone using this now uses the replacement...
410 uncheckedReplaceAllUsesWith(Replacement);
412 replaceAllUsesWith(Replacement);
414 // Delete the old constant!
418 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
419 bool DisableChecking) {
420 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
422 std::vector<Constant*> Values;
423 Values.reserve(getValues().size());
424 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
425 Constant *Val = cast<Constant>(getValues()[i]);
426 if (Val == From) Val = cast<Constant>(To);
427 Values.push_back(Val);
430 ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
431 assert(Replacement != this && "I didn't contain From!");
433 // Everyone using this now uses the replacement...
435 uncheckedReplaceAllUsesWith(Replacement);
437 replaceAllUsesWith(Replacement);
439 // Delete the old constant!
443 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
444 bool DisableChecking) {
445 if (isa<GlobalValue>(To)) {
446 assert(From == getOperand(0) && "Doesn't contain from!");
447 ConstantPointerRef *Replacement =
448 ConstantPointerRef::get(cast<GlobalValue>(To));
450 // Everyone using this now uses the replacement...
452 uncheckedReplaceAllUsesWith(Replacement);
454 replaceAllUsesWith(Replacement);
457 // Just replace ourselves with the To value specified.
459 uncheckedReplaceAllUsesWith(To);
461 replaceAllUsesWith(To);
464 // Delete the old constant!
468 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
469 bool DisableChecking) {
470 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
471 Constant *To = cast<Constant>(ToV);
473 Constant *Replacement = 0;
474 if (getOpcode() == Instruction::GetElementPtr) {
475 std::vector<Constant*> Indices;
476 Constant *Pointer = getOperand(0);
477 Indices.reserve(getNumOperands()-1);
478 if (Pointer == From) Pointer = To;
480 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
481 Constant *Val = getOperand(i);
482 if (Val == From) Val = To;
483 Indices.push_back(Val);
485 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
486 } else if (getOpcode() == Instruction::Cast) {
487 assert(getOperand(0) == From && "Cast only has one use!");
488 Replacement = ConstantExpr::getCast(To, getType());
489 } else if (getNumOperands() == 2) {
490 Constant *C1 = getOperand(0);
491 Constant *C2 = getOperand(1);
492 if (C1 == From) C1 = To;
493 if (C2 == From) C2 = To;
494 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
496 assert(0 && "Unknown ConstantExpr type!");
500 assert(Replacement != this && "I didn't contain From!");
502 // Everyone using this now uses the replacement...
504 uncheckedReplaceAllUsesWith(Replacement);
506 replaceAllUsesWith(Replacement);
508 // Delete the old constant!
512 //===----------------------------------------------------------------------===//
513 // Factory Function Implementation
515 // ConstantCreator - A class that is used to create constants by
516 // ValueMap*. This class should be partially specialized if there is
517 // something strange that needs to be done to interface to the ctor for the
520 template<class ConstantClass, class TypeClass, class ValType>
521 struct ConstantCreator {
522 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
523 return new ConstantClass(Ty, V);
527 template<class ConstantClass, class TypeClass>
528 struct ConvertConstantType {
529 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
530 assert(0 && "This type cannot be converted!\n");
536 template<class ValType, class TypeClass, class ConstantClass>
537 class ValueMap : public AbstractTypeUser {
538 typedef std::pair<const TypeClass*, ValType> MapKey;
539 typedef std::map<MapKey, ConstantClass *> MapTy;
540 typedef typename MapTy::iterator MapIterator;
543 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
544 AbstractTypeMapTy AbstractTypeMap;
546 // getOrCreate - Return the specified constant from the map, creating it if
548 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
549 MapKey Lookup(Ty, V);
550 MapIterator I = Map.lower_bound(Lookup);
551 if (I != Map.end() && I->first == Lookup)
552 return I->second; // Is it in the map?
554 // If no preexisting value, create one now...
555 ConstantClass *Result =
556 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
559 /// FIXME: why does this assert fail when loading 176.gcc?
560 //assert(Result->getType() == Ty && "Type specified is not correct!");
561 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
563 // If the type of the constant is abstract, make sure that an entry exists
564 // for it in the AbstractTypeMap.
565 if (Ty->isAbstract()) {
566 typename AbstractTypeMapTy::iterator TI =
567 AbstractTypeMap.lower_bound(Ty);
569 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
570 // Add ourselves to the ATU list of the type.
571 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
573 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
579 void remove(ConstantClass *CP) {
580 // FIXME: This should not use a linear scan. If this gets to be a
581 // performance problem, someone should look at this.
582 MapIterator I = Map.begin();
583 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
586 assert(I != Map.end() && "Constant not found in constant table!");
588 // Now that we found the entry, make sure this isn't the entry that
589 // the AbstractTypeMap points to.
590 const TypeClass *Ty = I->first.first;
591 if (Ty->isAbstract()) {
592 assert(AbstractTypeMap.count(Ty) &&
593 "Abstract type not in AbstractTypeMap?");
594 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
595 if (ATMEntryIt == I) {
596 // Yes, we are removing the representative entry for this type.
597 // See if there are any other entries of the same type.
598 MapIterator TmpIt = ATMEntryIt;
600 // First check the entry before this one...
601 if (TmpIt != Map.begin()) {
603 if (TmpIt->first.first != Ty) // Not the same type, move back...
607 // If we didn't find the same type, try to move forward...
608 if (TmpIt == ATMEntryIt) {
610 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
611 --TmpIt; // No entry afterwards with the same type
614 // If there is another entry in the map of the same abstract type,
615 // update the AbstractTypeMap entry now.
616 if (TmpIt != ATMEntryIt) {
619 // Otherwise, we are removing the last instance of this type
620 // from the table. Remove from the ATM, and from user list.
621 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
622 AbstractTypeMap.erase(Ty);
630 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
631 typename AbstractTypeMapTy::iterator I =
632 AbstractTypeMap.find(cast<TypeClass>(OldTy));
634 assert(I != AbstractTypeMap.end() &&
635 "Abstract type not in AbstractTypeMap?");
637 // Convert a constant at a time until the last one is gone. The last one
638 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
639 // eliminated eventually.
641 ConvertConstantType<ConstantClass,
642 TypeClass>::convert(I->second->second,
643 cast<TypeClass>(NewTy));
645 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
646 } while (I != AbstractTypeMap.end());
649 // If the type became concrete without being refined to any other existing
650 // type, we just remove ourselves from the ATU list.
651 void typeBecameConcrete(const DerivedType *AbsTy) {
652 AbsTy->removeAbstractTypeUser(this);
656 std::cerr << "Constant.cpp: ValueMap\n";
663 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
665 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
666 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
668 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
669 return SIntConstants.getOrCreate(Ty, V);
672 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
673 return UIntConstants.getOrCreate(Ty, V);
676 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
677 assert(V <= 127 && "Can only be used with very small positive constants!");
678 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
679 return ConstantUInt::get(Ty, V);
682 //---- ConstantFP::get() implementation...
684 static ValueMap<double, Type, ConstantFP> FPConstants;
686 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
687 return FPConstants.getOrCreate(Ty, V);
690 //---- ConstantArray::get() implementation...
694 struct ConvertConstantType<ConstantArray, ArrayType> {
695 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
696 // Make everyone now use a constant of the new type...
697 std::vector<Constant*> C;
698 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
699 C.push_back(cast<Constant>(OldC->getOperand(i)));
700 Constant *New = ConstantArray::get(NewTy, C);
701 assert(New != OldC && "Didn't replace constant??");
702 OldC->uncheckedReplaceAllUsesWith(New);
703 OldC->destroyConstant(); // This constant is now dead, destroy it.
708 static ValueMap<std::vector<Constant*>, ArrayType,
709 ConstantArray> ArrayConstants;
711 ConstantArray *ConstantArray::get(const ArrayType *Ty,
712 const std::vector<Constant*> &V) {
713 return ArrayConstants.getOrCreate(Ty, V);
716 // destroyConstant - Remove the constant from the constant table...
718 void ConstantArray::destroyConstant() {
719 ArrayConstants.remove(this);
720 destroyConstantImpl();
723 // ConstantArray::get(const string&) - Return an array that is initialized to
724 // contain the specified string. A null terminator is added to the specified
725 // string so that it may be used in a natural way...
727 ConstantArray *ConstantArray::get(const std::string &Str) {
728 std::vector<Constant*> ElementVals;
730 for (unsigned i = 0; i < Str.length(); ++i)
731 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
733 // Add a null terminator to the string...
734 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
736 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
737 return ConstantArray::get(ATy, ElementVals);
740 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
741 // then this method converts the array to an std::string and returns it.
742 // Otherwise, it asserts out.
744 std::string ConstantArray::getAsString() const {
745 assert((getType()->getElementType() == Type::UByteTy ||
746 getType()->getElementType() == Type::SByteTy) && "Not a string!");
749 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
750 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
755 //---- ConstantStruct::get() implementation...
759 struct ConvertConstantType<ConstantStruct, StructType> {
760 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
761 // Make everyone now use a constant of the new type...
762 std::vector<Constant*> C;
763 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
764 C.push_back(cast<Constant>(OldC->getOperand(i)));
765 Constant *New = ConstantStruct::get(NewTy, C);
766 assert(New != OldC && "Didn't replace constant??");
768 OldC->uncheckedReplaceAllUsesWith(New);
769 OldC->destroyConstant(); // This constant is now dead, destroy it.
773 static ValueMap<std::vector<Constant*>, StructType,
774 ConstantStruct> StructConstants;
776 ConstantStruct *ConstantStruct::get(const StructType *Ty,
777 const std::vector<Constant*> &V) {
778 return StructConstants.getOrCreate(Ty, V);
781 // destroyConstant - Remove the constant from the constant table...
783 void ConstantStruct::destroyConstant() {
784 StructConstants.remove(this);
785 destroyConstantImpl();
788 //---- ConstantPointerNull::get() implementation...
791 // ConstantPointerNull does not take extra "value" argument...
792 template<class ValType>
793 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
794 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
795 return new ConstantPointerNull(Ty);
800 struct ConvertConstantType<ConstantPointerNull, PointerType> {
801 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
802 // Make everyone now use a constant of the new type...
803 Constant *New = ConstantPointerNull::get(NewTy);
804 assert(New != OldC && "Didn't replace constant??");
805 OldC->uncheckedReplaceAllUsesWith(New);
806 OldC->destroyConstant(); // This constant is now dead, destroy it.
810 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
812 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
813 return NullPtrConstants.getOrCreate(Ty, 0);
816 // destroyConstant - Remove the constant from the constant table...
818 void ConstantPointerNull::destroyConstant() {
819 NullPtrConstants.remove(this);
820 destroyConstantImpl();
824 //---- ConstantPointerRef::get() implementation...
826 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
827 assert(GV->getParent() && "Global Value must be attached to a module!");
829 // The Module handles the pointer reference sharing...
830 return GV->getParent()->getConstantPointerRef(GV);
833 // destroyConstant - Remove the constant from the constant table...
835 void ConstantPointerRef::destroyConstant() {
836 getValue()->getParent()->destroyConstantPointerRef(this);
837 destroyConstantImpl();
841 //---- ConstantExpr::get() implementations...
843 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
846 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
847 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
848 if (V.first == Instruction::Cast)
849 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
850 if ((V.first >= Instruction::BinaryOpsBegin &&
851 V.first < Instruction::BinaryOpsEnd) ||
852 V.first == Instruction::Shl || V.first == Instruction::Shr)
853 return new ConstantExpr(V.first, V.second[0], V.second[1]);
855 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
857 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
858 return new ConstantExpr(V.second[0], IdxList, Ty);
863 struct ConvertConstantType<ConstantExpr, Type> {
864 static void convert(ConstantExpr *OldC, const Type *NewTy) {
866 switch (OldC->getOpcode()) {
867 case Instruction::Cast:
868 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
870 case Instruction::Shl:
871 case Instruction::Shr:
872 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
873 OldC->getOperand(0), OldC->getOperand(1));
876 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
877 OldC->getOpcode() < Instruction::BinaryOpsEnd);
878 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
879 OldC->getOperand(1));
881 case Instruction::GetElementPtr:
882 // Make everyone now use a constant of the new type...
883 std::vector<Constant*> C;
884 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
885 C.push_back(cast<Constant>(OldC->getOperand(i)));
886 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
890 assert(New != OldC && "Didn't replace constant??");
891 OldC->uncheckedReplaceAllUsesWith(New);
892 OldC->destroyConstant(); // This constant is now dead, destroy it.
897 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
899 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
900 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
902 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
903 return FC; // Fold a few common cases...
905 // Look up the constant in the table first to ensure uniqueness
906 std::vector<Constant*> argVec(1, C);
907 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
908 return ExprConstants.getOrCreate(Ty, Key);
911 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
912 Constant *C1, Constant *C2) {
913 // Check the operands for consistency first
914 assert((Opcode >= Instruction::BinaryOpsBegin &&
915 Opcode < Instruction::BinaryOpsEnd) &&
916 "Invalid opcode in binary constant expression");
917 assert(C1->getType() == C2->getType() &&
918 "Operand types in binary constant expression should match");
920 if (ReqTy == C1->getType())
921 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
922 return FC; // Fold a few common cases...
924 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
925 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
926 return ExprConstants.getOrCreate(ReqTy, Key);
929 /// getShift - Return a shift left or shift right constant expr
930 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
931 Constant *C1, Constant *C2) {
932 // Check the operands for consistency first
933 assert((Opcode == Instruction::Shl ||
934 Opcode == Instruction::Shr) &&
935 "Invalid opcode in binary constant expression");
936 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
937 "Invalid operand types for Shift constant expr!");
939 if (Constant *FC = ConstantFoldShiftInstruction(Opcode, C1, C2))
940 return FC; // Fold a few common cases...
942 // Look up the constant in the table first to ensure uniqueness
943 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
944 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
945 return ExprConstants.getOrCreate(ReqTy, Key);
949 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
950 const std::vector<Constant*> &IdxList) {
951 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
952 return FC; // Fold a few common cases...
953 assert(isa<PointerType>(C->getType()) &&
954 "Non-pointer type for constant GetElementPtr expression");
956 // Look up the constant in the table first to ensure uniqueness
957 std::vector<Constant*> argVec(1, C);
958 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
959 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
960 return ExprConstants.getOrCreate(ReqTy, Key);
963 Constant *ConstantExpr::getGetElementPtr(Constant *C,
964 const std::vector<Constant*> &IdxList){
965 // Get the result type of the getelementptr!
966 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
968 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
970 assert(Ty && "GEP indices invalid!");
971 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
975 // destroyConstant - Remove the constant from the constant table...
977 void ConstantExpr::destroyConstant() {
978 ExprConstants.remove(this);
979 destroyConstantImpl();
982 const char *ConstantExpr::getOpcodeName() const {
983 return Instruction::getOpcodeName(getOpcode());
986 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
987 // Uses of constant pointer refs are global values, not constants!
988 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
989 GlobalValue *NewGV = cast<GlobalValue>(NewV);
990 GlobalValue *OldGV = CPR->getValue();
992 assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
994 OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
997 Constant *NewC = cast<Constant>(NewV);
998 unsigned NumReplaced = 0;
999 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
1000 if (Operands[i] == OldV) {