1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/Module.h"
20 #include "Support/StringExtras.h"
24 ConstantBool *ConstantBool::True = new ConstantBool(true);
25 ConstantBool *ConstantBool::False = new ConstantBool(false);
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 // Specialize setName to take care of symbol table majik
33 void Constant::setName(const std::string &Name, SymbolTable *ST) {
34 assert(ST && "Type::setName - Must provide symbol table argument!");
36 if (Name.size()) ST->insert(Name, this);
39 void Constant::destroyConstantImpl() {
40 // When a Constant is destroyed, there may be lingering
41 // references to the constant by other constants in the constant pool. These
42 // constants are implicitly dependent on the module that is being deleted,
43 // but they don't know that. Because we only find out when the CPV is
44 // deleted, we must now notify all of our users (that should only be
45 // Constants) that they are, in fact, invalid now and should be deleted.
47 while (!use_empty()) {
48 Value *V = use_back();
49 #ifndef NDEBUG // Only in -g mode...
50 if (!isa<Constant>(V))
51 std::cerr << "While deleting: " << *this
52 << "\n\nUse still stuck around after Def is destroyed: "
55 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
56 Constant *CPV = cast<Constant>(V);
57 CPV->destroyConstant();
59 // The constant should remove itself from our use list...
60 assert((use_empty() || use_back() != V) && "Constant not removed!");
63 // Value has no outstanding references it is safe to delete it now...
67 // Static constructor to create a '0' constant of arbitrary type...
68 Constant *Constant::getNullValue(const Type *Ty) {
69 switch (Ty->getPrimitiveID()) {
70 case Type::BoolTyID: {
71 static Constant *NullBool = ConstantBool::get(false);
74 case Type::SByteTyID: {
75 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
78 case Type::UByteTyID: {
79 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
82 case Type::ShortTyID: {
83 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
86 case Type::UShortTyID: {
87 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
91 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
94 case Type::UIntTyID: {
95 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
98 case Type::LongTyID: {
99 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
102 case Type::ULongTyID: {
103 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
107 case Type::FloatTyID: {
108 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
111 case Type::DoubleTyID: {
112 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
116 case Type::PointerTyID:
117 return ConstantPointerNull::get(cast<PointerType>(Ty));
119 case Type::StructTyID: {
120 const StructType *ST = cast<StructType>(Ty);
121 const StructType::ElementTypes &ETs = ST->getElementTypes();
122 std::vector<Constant*> Elements;
123 Elements.resize(ETs.size());
124 for (unsigned i = 0, e = ETs.size(); i != e; ++i)
125 Elements[i] = Constant::getNullValue(ETs[i]);
126 return ConstantStruct::get(ST, Elements);
128 case Type::ArrayTyID: {
129 const ArrayType *AT = cast<ArrayType>(Ty);
130 Constant *El = Constant::getNullValue(AT->getElementType());
131 unsigned NumElements = AT->getNumElements();
132 return ConstantArray::get(AT, std::vector<Constant*>(NumElements, El));
135 // Function, Type, Label, or Opaque type?
136 assert(0 && "Cannot create a null constant of that type!");
141 // Static constructor to create the maximum constant of an integral type...
142 ConstantIntegral *ConstantIntegral::getMaxValue(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: {
149 // Calculate 011111111111111...
150 unsigned TypeBits = Ty->getPrimitiveSize()*8;
151 int64_t Val = INT64_MAX; // All ones
152 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
153 return ConstantSInt::get(Ty, Val);
156 case Type::UByteTyID:
157 case Type::UShortTyID:
159 case Type::ULongTyID: return getAllOnesValue(Ty);
165 // Static constructor to create the minimum constant for an integral type...
166 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
167 switch (Ty->getPrimitiveID()) {
168 case Type::BoolTyID: return ConstantBool::False;
169 case Type::SByteTyID:
170 case Type::ShortTyID:
172 case Type::LongTyID: {
173 // Calculate 1111111111000000000000
174 unsigned TypeBits = Ty->getPrimitiveSize()*8;
175 int64_t Val = -1; // All ones
176 Val <<= TypeBits-1; // Shift over to the right spot
177 return ConstantSInt::get(Ty, Val);
180 case Type::UByteTyID:
181 case Type::UShortTyID:
183 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
189 // Static constructor to create an integral constant with all bits set
190 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
191 switch (Ty->getPrimitiveID()) {
192 case Type::BoolTyID: return ConstantBool::True;
193 case Type::SByteTyID:
194 case Type::ShortTyID:
196 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
198 case Type::UByteTyID:
199 case Type::UShortTyID:
201 case Type::ULongTyID: {
202 // Calculate ~0 of the right type...
203 unsigned TypeBits = Ty->getPrimitiveSize()*8;
204 uint64_t Val = ~0ULL; // All ones
205 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
206 return ConstantUInt::get(Ty, Val);
212 bool ConstantUInt::isAllOnesValue() const {
213 unsigned TypeBits = getType()->getPrimitiveSize()*8;
214 uint64_t Val = ~0ULL; // All ones
215 Val >>= 64-TypeBits; // Shift out inappropriate bits
216 return getValue() == Val;
220 //===----------------------------------------------------------------------===//
221 // ConstantXXX Classes
222 //===----------------------------------------------------------------------===//
224 //===----------------------------------------------------------------------===//
225 // Normal Constructors
227 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
231 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
235 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
236 assert(Ty->isInteger() && Ty->isSigned() &&
237 "Illegal type for unsigned integer constant!");
238 assert(isValueValidForType(Ty, V) && "Value too large for type!");
241 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
242 assert(Ty->isInteger() && Ty->isUnsigned() &&
243 "Illegal type for unsigned integer constant!");
244 assert(isValueValidForType(Ty, V) && "Value too large for type!");
247 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
248 assert(isValueValidForType(Ty, V) && "Value too large for type!");
252 ConstantArray::ConstantArray(const ArrayType *T,
253 const std::vector<Constant*> &V) : Constant(T) {
254 Operands.reserve(V.size());
255 for (unsigned i = 0, e = V.size(); i != e; ++i) {
256 assert(V[i]->getType() == T->getElementType() ||
258 V[i]->getType()->getPrimitiveID() ==
259 T->getElementType()->getPrimitiveID()));
260 Operands.push_back(Use(V[i], this));
264 ConstantStruct::ConstantStruct(const StructType *T,
265 const std::vector<Constant*> &V) : Constant(T) {
266 const StructType::ElementTypes &ETypes = T->getElementTypes();
267 assert(V.size() == ETypes.size() &&
268 "Invalid initializer vector for constant structure");
269 Operands.reserve(V.size());
270 for (unsigned i = 0, e = V.size(); i != e; ++i) {
271 assert((V[i]->getType() == ETypes[i] ||
272 ((ETypes[i]->isAbstract() || V[i]->getType()->isAbstract()) &&
273 ETypes[i]->getPrimitiveID()==V[i]->getType()->getPrimitiveID())) &&
274 "Initializer for struct element doesn't match struct element type!");
275 Operands.push_back(Use(V[i], this));
279 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
280 : Constant(GV->getType()) {
281 Operands.push_back(Use(GV, this));
284 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
285 : Constant(Ty), iType(Opcode) {
286 Operands.push_back(Use(C, this));
289 static bool isSetCC(unsigned Opcode) {
290 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
291 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
292 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
295 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
296 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
297 Operands.push_back(Use(C1, this));
298 Operands.push_back(Use(C2, this));
301 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
303 : Constant(DestTy), iType(Instruction::GetElementPtr) {
304 Operands.reserve(1+IdxList.size());
305 Operands.push_back(Use(C, this));
306 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
307 Operands.push_back(Use(IdxList[i], this));
312 //===----------------------------------------------------------------------===//
313 // classof implementations
315 bool ConstantIntegral::classof(const Constant *CPV) {
316 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
319 bool ConstantInt::classof(const Constant *CPV) {
320 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
322 bool ConstantSInt::classof(const Constant *CPV) {
323 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
325 bool ConstantUInt::classof(const Constant *CPV) {
326 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
328 bool ConstantFP::classof(const Constant *CPV) {
329 const Type *Ty = CPV->getType();
330 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
331 !isa<ConstantExpr>(CPV));
333 bool ConstantArray::classof(const Constant *CPV) {
334 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
336 bool ConstantStruct::classof(const Constant *CPV) {
337 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
340 bool ConstantPointerNull::classof(const Constant *CPV) {
341 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
342 CPV->getNumOperands() == 0;
345 bool ConstantPointerRef::classof(const Constant *CPV) {
346 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
347 CPV->getNumOperands() == 1;
352 //===----------------------------------------------------------------------===//
353 // isValueValidForType implementations
355 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
356 switch (Ty->getPrimitiveID()) {
358 return false; // These can't be represented as integers!!!
361 case Type::SByteTyID:
362 return (Val <= INT8_MAX && Val >= INT8_MIN);
363 case Type::ShortTyID:
364 return (Val <= INT16_MAX && Val >= INT16_MIN);
366 return (Val <= INT32_MAX && Val >= INT32_MIN);
368 return true; // This is the largest type...
374 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
375 switch (Ty->getPrimitiveID()) {
377 return false; // These can't be represented as integers!!!
380 case Type::UByteTyID:
381 return (Val <= UINT8_MAX);
382 case Type::UShortTyID:
383 return (Val <= UINT16_MAX);
385 return (Val <= UINT32_MAX);
386 case Type::ULongTyID:
387 return true; // This is the largest type...
393 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
394 switch (Ty->getPrimitiveID()) {
396 return false; // These can't be represented as floating point!
398 // TODO: Figure out how to test if a double can be cast to a float!
399 case Type::FloatTyID:
400 case Type::DoubleTyID:
401 return true; // This is the largest type...
405 //===----------------------------------------------------------------------===//
406 // replaceUsesOfWithOnConstant implementations
408 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
409 bool DisableChecking) {
410 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
412 std::vector<Constant*> Values;
413 Values.reserve(getValues().size()); // Build replacement array...
414 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
415 Constant *Val = cast<Constant>(getValues()[i]);
416 if (Val == From) Val = cast<Constant>(To);
417 Values.push_back(Val);
420 ConstantArray *Replacement = ConstantArray::get(getType(), Values);
421 assert(Replacement != this && "I didn't contain From!");
423 // Everyone using this now uses the replacement...
425 uncheckedReplaceAllUsesWith(Replacement);
427 replaceAllUsesWith(Replacement);
429 // Delete the old constant!
433 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
434 bool DisableChecking) {
435 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
437 std::vector<Constant*> Values;
438 Values.reserve(getValues().size());
439 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
440 Constant *Val = cast<Constant>(getValues()[i]);
441 if (Val == From) Val = cast<Constant>(To);
442 Values.push_back(Val);
445 ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
446 assert(Replacement != this && "I didn't contain From!");
448 // Everyone using this now uses the replacement...
450 uncheckedReplaceAllUsesWith(Replacement);
452 replaceAllUsesWith(Replacement);
454 // Delete the old constant!
458 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
459 bool DisableChecking) {
460 if (isa<GlobalValue>(To)) {
461 assert(From == getOperand(0) && "Doesn't contain from!");
462 ConstantPointerRef *Replacement =
463 ConstantPointerRef::get(cast<GlobalValue>(To));
465 // Everyone using this now uses the replacement...
467 uncheckedReplaceAllUsesWith(Replacement);
469 replaceAllUsesWith(Replacement);
472 // Just replace ourselves with the To value specified.
474 uncheckedReplaceAllUsesWith(To);
476 replaceAllUsesWith(To);
479 // Delete the old constant!
483 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
484 bool DisableChecking) {
485 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
486 Constant *To = cast<Constant>(ToV);
488 Constant *Replacement = 0;
489 if (getOpcode() == Instruction::GetElementPtr) {
490 std::vector<Constant*> Indices;
491 Constant *Pointer = getOperand(0);
492 Indices.reserve(getNumOperands()-1);
493 if (Pointer == From) Pointer = To;
495 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
496 Constant *Val = getOperand(i);
497 if (Val == From) Val = To;
498 Indices.push_back(Val);
500 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
501 } else if (getOpcode() == Instruction::Cast) {
502 assert(getOperand(0) == From && "Cast only has one use!");
503 Replacement = ConstantExpr::getCast(To, getType());
504 } else if (getNumOperands() == 2) {
505 Constant *C1 = getOperand(0);
506 Constant *C2 = getOperand(1);
507 if (C1 == From) C1 = To;
508 if (C2 == From) C2 = To;
509 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
511 assert(0 && "Unknown ConstantExpr type!");
515 assert(Replacement != this && "I didn't contain From!");
517 // Everyone using this now uses the replacement...
519 uncheckedReplaceAllUsesWith(Replacement);
521 replaceAllUsesWith(Replacement);
523 // Delete the old constant!
527 //===----------------------------------------------------------------------===//
528 // Factory Function Implementation
530 // ConstantCreator - A class that is used to create constants by
531 // ValueMap*. This class should be partially specialized if there is
532 // something strange that needs to be done to interface to the ctor for the
536 template<class ConstantClass, class TypeClass, class ValType>
537 struct ConstantCreator {
538 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
539 return new ConstantClass(Ty, V);
543 template<class ConstantClass, class TypeClass>
544 struct ConvertConstantType {
545 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
546 assert(0 && "This type cannot be converted!\n");
553 template<class ValType, class TypeClass, class ConstantClass>
554 class ValueMap : public AbstractTypeUser {
555 typedef std::pair<const TypeClass*, ValType> MapKey;
556 typedef std::map<MapKey, ConstantClass *> MapTy;
557 typedef typename MapTy::iterator MapIterator;
560 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
561 AbstractTypeMapTy AbstractTypeMap;
563 // getOrCreate - Return the specified constant from the map, creating it if
565 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
566 MapKey Lookup(Ty, V);
567 MapIterator I = Map.lower_bound(Lookup);
568 if (I != Map.end() && I->first == Lookup)
569 return I->second; // Is it in the map?
571 // If no preexisting value, create one now...
572 ConstantClass *Result =
573 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
576 /// FIXME: why does this assert fail when loading 176.gcc?
577 //assert(Result->getType() == Ty && "Type specified is not correct!");
578 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
580 // If the type of the constant is abstract, make sure that an entry exists
581 // for it in the AbstractTypeMap.
582 if (Ty->isAbstract()) {
583 typename AbstractTypeMapTy::iterator TI =
584 AbstractTypeMap.lower_bound(Ty);
586 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
587 // Add ourselves to the ATU list of the type.
588 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
590 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
596 void remove(ConstantClass *CP) {
597 // FIXME: This should not use a linear scan. If this gets to be a
598 // performance problem, someone should look at this.
599 MapIterator I = Map.begin();
600 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
603 assert(I != Map.end() && "Constant not found in constant table!");
605 // Now that we found the entry, make sure this isn't the entry that
606 // the AbstractTypeMap points to.
607 const TypeClass *Ty = I->first.first;
608 if (Ty->isAbstract()) {
609 assert(AbstractTypeMap.count(Ty) &&
610 "Abstract type not in AbstractTypeMap?");
611 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
612 if (ATMEntryIt == I) {
613 // Yes, we are removing the representative entry for this type.
614 // See if there are any other entries of the same type.
615 MapIterator TmpIt = ATMEntryIt;
617 // First check the entry before this one...
618 if (TmpIt != Map.begin()) {
620 if (TmpIt->first.first != Ty) // Not the same type, move back...
624 // If we didn't find the same type, try to move forward...
625 if (TmpIt == ATMEntryIt) {
627 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
628 --TmpIt; // No entry afterwards with the same type
631 // If there is another entry in the map of the same abstract type,
632 // update the AbstractTypeMap entry now.
633 if (TmpIt != ATMEntryIt) {
636 // Otherwise, we are removing the last instance of this type
637 // from the table. Remove from the ATM, and from user list.
638 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
639 AbstractTypeMap.erase(Ty);
647 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
648 typename AbstractTypeMapTy::iterator I =
649 AbstractTypeMap.find(cast<TypeClass>(OldTy));
651 assert(I != AbstractTypeMap.end() &&
652 "Abstract type not in AbstractTypeMap?");
654 // Convert a constant at a time until the last one is gone. The last one
655 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
656 // eliminated eventually.
658 ConvertConstantType<ConstantClass,
659 TypeClass>::convert(I->second->second,
660 cast<TypeClass>(NewTy));
662 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
663 } while (I != AbstractTypeMap.end());
666 // If the type became concrete without being refined to any other existing
667 // type, we just remove ourselves from the ATU list.
668 void typeBecameConcrete(const DerivedType *AbsTy) {
669 AbsTy->removeAbstractTypeUser(this);
673 std::cerr << "Constant.cpp: ValueMap\n";
680 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
682 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
683 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
685 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
686 return SIntConstants.getOrCreate(Ty, V);
689 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
690 return UIntConstants.getOrCreate(Ty, V);
693 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
694 assert(V <= 127 && "Can only be used with very small positive constants!");
695 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
696 return ConstantUInt::get(Ty, V);
699 //---- ConstantFP::get() implementation...
701 static ValueMap<double, Type, ConstantFP> FPConstants;
703 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
704 return FPConstants.getOrCreate(Ty, V);
707 //---- ConstantArray::get() implementation...
711 struct ConvertConstantType<ConstantArray, ArrayType> {
712 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
713 // Make everyone now use a constant of the new type...
714 std::vector<Constant*> C;
715 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
716 C.push_back(cast<Constant>(OldC->getOperand(i)));
717 Constant *New = ConstantArray::get(NewTy, C);
718 assert(New != OldC && "Didn't replace constant??");
719 OldC->uncheckedReplaceAllUsesWith(New);
720 OldC->destroyConstant(); // This constant is now dead, destroy it.
725 static ValueMap<std::vector<Constant*>, ArrayType,
726 ConstantArray> ArrayConstants;
728 ConstantArray *ConstantArray::get(const ArrayType *Ty,
729 const std::vector<Constant*> &V) {
730 return ArrayConstants.getOrCreate(Ty, V);
733 // destroyConstant - Remove the constant from the constant table...
735 void ConstantArray::destroyConstant() {
736 ArrayConstants.remove(this);
737 destroyConstantImpl();
740 // ConstantArray::get(const string&) - Return an array that is initialized to
741 // contain the specified string. A null terminator is added to the specified
742 // string so that it may be used in a natural way...
744 ConstantArray *ConstantArray::get(const std::string &Str) {
745 std::vector<Constant*> ElementVals;
747 for (unsigned i = 0; i < Str.length(); ++i)
748 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
750 // Add a null terminator to the string...
751 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
753 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
754 return ConstantArray::get(ATy, ElementVals);
757 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
758 // then this method converts the array to an std::string and returns it.
759 // Otherwise, it asserts out.
761 std::string ConstantArray::getAsString() const {
762 assert((getType()->getElementType() == Type::UByteTy ||
763 getType()->getElementType() == Type::SByteTy) && "Not a string!");
766 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
767 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
772 //---- ConstantStruct::get() implementation...
777 struct ConvertConstantType<ConstantStruct, StructType> {
778 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
779 // Make everyone now use a constant of the new type...
780 std::vector<Constant*> C;
781 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
782 C.push_back(cast<Constant>(OldC->getOperand(i)));
783 Constant *New = ConstantStruct::get(NewTy, C);
784 assert(New != OldC && "Didn't replace constant??");
786 OldC->uncheckedReplaceAllUsesWith(New);
787 OldC->destroyConstant(); // This constant is now dead, destroy it.
792 static ValueMap<std::vector<Constant*>, StructType,
793 ConstantStruct> StructConstants;
795 ConstantStruct *ConstantStruct::get(const StructType *Ty,
796 const std::vector<Constant*> &V) {
797 return StructConstants.getOrCreate(Ty, V);
800 // destroyConstant - Remove the constant from the constant table...
802 void ConstantStruct::destroyConstant() {
803 StructConstants.remove(this);
804 destroyConstantImpl();
807 //---- ConstantPointerNull::get() implementation...
811 // ConstantPointerNull does not take extra "value" argument...
812 template<class ValType>
813 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
814 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
815 return new ConstantPointerNull(Ty);
820 struct ConvertConstantType<ConstantPointerNull, PointerType> {
821 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
822 // Make everyone now use a constant of the new type...
823 Constant *New = ConstantPointerNull::get(NewTy);
824 assert(New != OldC && "Didn't replace constant??");
825 OldC->uncheckedReplaceAllUsesWith(New);
826 OldC->destroyConstant(); // This constant is now dead, destroy it.
831 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
833 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
834 return NullPtrConstants.getOrCreate(Ty, 0);
837 // destroyConstant - Remove the constant from the constant table...
839 void ConstantPointerNull::destroyConstant() {
840 NullPtrConstants.remove(this);
841 destroyConstantImpl();
845 //---- ConstantPointerRef::get() implementation...
847 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
848 assert(GV->getParent() && "Global Value must be attached to a module!");
850 // The Module handles the pointer reference sharing...
851 return GV->getParent()->getConstantPointerRef(GV);
854 // destroyConstant - Remove the constant from the constant table...
856 void ConstantPointerRef::destroyConstant() {
857 getValue()->getParent()->destroyConstantPointerRef(this);
858 destroyConstantImpl();
862 //---- ConstantExpr::get() implementations...
864 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
868 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
869 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
870 if (V.first == Instruction::Cast)
871 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
872 if ((V.first >= Instruction::BinaryOpsBegin &&
873 V.first < Instruction::BinaryOpsEnd) ||
874 V.first == Instruction::Shl || V.first == Instruction::Shr)
875 return new ConstantExpr(V.first, V.second[0], V.second[1]);
877 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
879 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
880 return new ConstantExpr(V.second[0], IdxList, Ty);
885 struct ConvertConstantType<ConstantExpr, Type> {
886 static void convert(ConstantExpr *OldC, const Type *NewTy) {
888 switch (OldC->getOpcode()) {
889 case Instruction::Cast:
890 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
892 case Instruction::Shl:
893 case Instruction::Shr:
894 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
895 OldC->getOperand(0), OldC->getOperand(1));
898 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
899 OldC->getOpcode() < Instruction::BinaryOpsEnd);
900 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
901 OldC->getOperand(1));
903 case Instruction::GetElementPtr:
904 // Make everyone now use a constant of the new type...
905 std::vector<Constant*> C;
906 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
907 C.push_back(cast<Constant>(OldC->getOperand(i)));
908 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
912 assert(New != OldC && "Didn't replace constant??");
913 OldC->uncheckedReplaceAllUsesWith(New);
914 OldC->destroyConstant(); // This constant is now dead, destroy it.
917 } // end namespace llvm
920 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
922 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
923 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
925 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
926 return FC; // Fold a few common cases...
928 // Look up the constant in the table first to ensure uniqueness
929 std::vector<Constant*> argVec(1, C);
930 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
931 return ExprConstants.getOrCreate(Ty, Key);
934 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
935 Constant *C1, Constant *C2) {
936 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
937 return getShiftTy(ReqTy, Opcode, C1, C2);
938 // Check the operands for consistency first
939 assert((Opcode >= Instruction::BinaryOpsBegin &&
940 Opcode < Instruction::BinaryOpsEnd) &&
941 "Invalid opcode in binary constant expression");
942 assert(C1->getType() == C2->getType() &&
943 "Operand types in binary constant expression should match");
945 if (ReqTy == C1->getType())
946 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
947 return FC; // Fold a few common cases...
949 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
950 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
951 return ExprConstants.getOrCreate(ReqTy, Key);
954 /// getShiftTy - Return a shift left or shift right constant expr
955 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
956 Constant *C1, Constant *C2) {
957 // Check the operands for consistency first
958 assert((Opcode == Instruction::Shl ||
959 Opcode == Instruction::Shr) &&
960 "Invalid opcode in binary constant expression");
961 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
962 "Invalid operand types for Shift constant expr!");
964 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
965 return FC; // Fold a few common cases...
967 // Look up the constant in the table first to ensure uniqueness
968 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
969 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
970 return ExprConstants.getOrCreate(ReqTy, Key);
974 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
975 const std::vector<Constant*> &IdxList) {
976 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
977 return FC; // Fold a few common cases...
978 assert(isa<PointerType>(C->getType()) &&
979 "Non-pointer type for constant GetElementPtr expression");
981 // Look up the constant in the table first to ensure uniqueness
982 std::vector<Constant*> argVec(1, C);
983 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
984 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
985 return ExprConstants.getOrCreate(ReqTy, Key);
988 Constant *ConstantExpr::getGetElementPtr(Constant *C,
989 const std::vector<Constant*> &IdxList){
990 // Get the result type of the getelementptr!
991 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
993 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
995 assert(Ty && "GEP indices invalid!");
997 if (C->isNullValue()) {
999 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1000 if (!IdxList[i]->isNullValue()) {
1004 if (isNull) return ConstantPointerNull::get(PointerType::get(Ty));
1007 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1011 // destroyConstant - Remove the constant from the constant table...
1013 void ConstantExpr::destroyConstant() {
1014 ExprConstants.remove(this);
1015 destroyConstantImpl();
1018 const char *ConstantExpr::getOpcodeName() const {
1019 return Instruction::getOpcodeName(getOpcode());
1022 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
1023 // Uses of constant pointer refs are global values, not constants!
1024 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
1025 GlobalValue *NewGV = cast<GlobalValue>(NewV);
1026 GlobalValue *OldGV = CPR->getValue();
1028 assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
1029 Operands[0] = NewGV;
1030 OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
1033 Constant *NewC = cast<Constant>(NewV);
1034 unsigned NumReplaced = 0;
1035 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
1036 if (Operands[i] == OldV) {