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/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/MathExtras.h"
27 ConstantBool *ConstantBool::True = new ConstantBool(true);
28 ConstantBool *ConstantBool::False = new ConstantBool(false);
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
37 // references to the constant by other constants in the constant pool. These
38 // constants are implicitly dependent on the module that is being deleted,
39 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
41 // Constants) that they are, in fact, invalid now and should be deleted.
43 while (!use_empty()) {
44 Value *V = use_back();
45 #ifndef NDEBUG // Only in -g mode...
46 if (!isa<Constant>(V))
47 std::cerr << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
51 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
52 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
55 // The constant should remove itself from our use list...
56 assert((use_empty() || use_back() != V) && "Constant not removed!");
59 // Value has no outstanding references it is safe to delete it now...
63 // Static constructor to create a '0' constant of arbitrary type...
64 Constant *Constant::getNullValue(const Type *Ty) {
65 switch (Ty->getTypeID()) {
66 case Type::BoolTyID: {
67 static Constant *NullBool = ConstantBool::get(false);
70 case Type::SByteTyID: {
71 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
74 case Type::UByteTyID: {
75 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
78 case Type::ShortTyID: {
79 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
82 case Type::UShortTyID: {
83 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
87 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
90 case Type::UIntTyID: {
91 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
94 case Type::LongTyID: {
95 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
98 case Type::ULongTyID: {
99 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
103 case Type::FloatTyID: {
104 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
107 case Type::DoubleTyID: {
108 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
112 case Type::PointerTyID:
113 return ConstantPointerNull::get(cast<PointerType>(Ty));
115 case Type::StructTyID:
116 case Type::ArrayTyID:
117 case Type::PackedTyID:
118 return ConstantAggregateZero::get(Ty);
120 // Function, Label, or Opaque type?
121 assert(!"Cannot create a null constant of that type!");
126 // Static constructor to create the maximum constant of an integral type...
127 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
128 switch (Ty->getTypeID()) {
129 case Type::BoolTyID: return ConstantBool::True;
130 case Type::SByteTyID:
131 case Type::ShortTyID:
133 case Type::LongTyID: {
134 // Calculate 011111111111111...
135 unsigned TypeBits = Ty->getPrimitiveSize()*8;
136 int64_t Val = INT64_MAX; // All ones
137 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
138 return ConstantSInt::get(Ty, Val);
141 case Type::UByteTyID:
142 case Type::UShortTyID:
144 case Type::ULongTyID: return getAllOnesValue(Ty);
150 // Static constructor to create the minimum constant for an integral type...
151 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
152 switch (Ty->getTypeID()) {
153 case Type::BoolTyID: return ConstantBool::False;
154 case Type::SByteTyID:
155 case Type::ShortTyID:
157 case Type::LongTyID: {
158 // Calculate 1111111111000000000000
159 unsigned TypeBits = Ty->getPrimitiveSize()*8;
160 int64_t Val = -1; // All ones
161 Val <<= TypeBits-1; // Shift over to the right spot
162 return ConstantSInt::get(Ty, Val);
165 case Type::UByteTyID:
166 case Type::UShortTyID:
168 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
174 // Static constructor to create an integral constant with all bits set
175 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
176 switch (Ty->getTypeID()) {
177 case Type::BoolTyID: return ConstantBool::True;
178 case Type::SByteTyID:
179 case Type::ShortTyID:
181 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
183 case Type::UByteTyID:
184 case Type::UShortTyID:
186 case Type::ULongTyID: {
187 // Calculate ~0 of the right type...
188 unsigned TypeBits = Ty->getPrimitiveSize()*8;
189 uint64_t Val = ~0ULL; // All ones
190 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
191 return ConstantUInt::get(Ty, Val);
197 bool ConstantUInt::isAllOnesValue() const {
198 unsigned TypeBits = getType()->getPrimitiveSize()*8;
199 uint64_t Val = ~0ULL; // All ones
200 Val >>= 64-TypeBits; // Shift out inappropriate bits
201 return getValue() == Val;
205 //===----------------------------------------------------------------------===//
206 // ConstantXXX Classes
207 //===----------------------------------------------------------------------===//
209 //===----------------------------------------------------------------------===//
210 // Normal Constructors
212 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
213 : Constant(Ty, VT, 0, 0) {
217 ConstantBool::ConstantBool(bool V)
218 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, V) {
221 ConstantInt::ConstantInt(const Type *Ty, ValueTy VT, uint64_t V)
222 : ConstantIntegral(Ty, VT, V) {
225 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V)
226 : ConstantInt(Ty, ConstantSIntVal, V) {
227 assert(Ty->isInteger() && Ty->isSigned() &&
228 "Illegal type for signed integer constant!");
229 assert(isValueValidForType(Ty, V) && "Value too large for type!");
232 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V)
233 : ConstantInt(Ty, ConstantUIntVal, 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)
240 : Constant(Ty, ConstantFPVal, 0, 0) {
241 assert(isValueValidForType(Ty, V) && "Value too large for type!");
245 ConstantArray::ConstantArray(const ArrayType *T,
246 const std::vector<Constant*> &V)
247 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
248 assert(V.size() == T->getNumElements() &&
249 "Invalid initializer vector for constant array");
250 Use *OL = OperandList;
251 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
254 assert((C->getType() == T->getElementType() ||
256 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
257 "Initializer for array element doesn't match array element type!");
262 ConstantArray::~ConstantArray() {
263 delete [] OperandList;
266 ConstantStruct::ConstantStruct(const StructType *T,
267 const std::vector<Constant*> &V)
268 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
269 assert(V.size() == T->getNumElements() &&
270 "Invalid initializer vector for constant structure");
271 Use *OL = OperandList;
272 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
275 assert((C->getType() == T->getElementType(I-V.begin()) ||
276 ((T->getElementType(I-V.begin())->isAbstract() ||
277 C->getType()->isAbstract()) &&
278 T->getElementType(I-V.begin())->getTypeID() ==
279 C->getType()->getTypeID())) &&
280 "Initializer for struct element doesn't match struct element type!");
285 ConstantStruct::~ConstantStruct() {
286 delete [] OperandList;
290 ConstantPacked::ConstantPacked(const PackedType *T,
291 const std::vector<Constant*> &V)
292 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
293 Use *OL = OperandList;
294 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
297 assert((C->getType() == T->getElementType() ||
299 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
300 "Initializer for packed element doesn't match packed element type!");
305 ConstantPacked::~ConstantPacked() {
306 delete [] OperandList;
309 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
310 /// behind the scenes to implement unary constant exprs.
311 class UnaryConstantExpr : public ConstantExpr {
314 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
315 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
318 static bool isSetCC(unsigned Opcode) {
319 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
320 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
321 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
324 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
325 /// behind the scenes to implement binary constant exprs.
326 class BinaryConstantExpr : public ConstantExpr {
329 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
330 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
332 Ops[0].init(C1, this);
333 Ops[1].init(C2, this);
337 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
338 /// behind the scenes to implement select constant exprs.
339 class SelectConstantExpr : public ConstantExpr {
342 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
343 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
344 Ops[0].init(C1, this);
345 Ops[1].init(C2, this);
346 Ops[2].init(C3, this);
350 /// ExtractElementConstantExpr - This class is private to Constants.cpp, and is used
351 /// behind the scenes to implement extractelement constant exprs.
352 class ExtractElementConstantExpr : public ConstantExpr {
355 ExtractElementConstantExpr(Constant *C1, Constant *C2)
356 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
357 Instruction::ExtractElement, Ops, 2) {
358 Ops[0].init(C1, this);
359 Ops[1].init(C2, this);
363 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
364 /// used behind the scenes to implement getelementpr constant exprs.
365 struct GetElementPtrConstantExpr : public ConstantExpr {
366 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
368 : ConstantExpr(DestTy, Instruction::GetElementPtr,
369 new Use[IdxList.size()+1], IdxList.size()+1) {
370 OperandList[0].init(C, this);
371 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
372 OperandList[i+1].init(IdxList[i], this);
374 ~GetElementPtrConstantExpr() {
375 delete [] OperandList;
379 /// ConstantExpr::get* - Return some common constants without having to
380 /// specify the full Instruction::OPCODE identifier.
382 Constant *ConstantExpr::getNeg(Constant *C) {
383 if (!C->getType()->isFloatingPoint())
384 return get(Instruction::Sub, getNullValue(C->getType()), C);
386 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
388 Constant *ConstantExpr::getNot(Constant *C) {
389 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
390 return get(Instruction::Xor, C,
391 ConstantIntegral::getAllOnesValue(C->getType()));
393 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
394 return get(Instruction::Add, C1, C2);
396 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
397 return get(Instruction::Sub, C1, C2);
399 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
400 return get(Instruction::Mul, C1, C2);
402 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
403 return get(Instruction::Div, C1, C2);
405 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
406 return get(Instruction::Rem, C1, C2);
408 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
409 return get(Instruction::And, C1, C2);
411 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
412 return get(Instruction::Or, C1, C2);
414 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
415 return get(Instruction::Xor, C1, C2);
417 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
418 return get(Instruction::SetEQ, C1, C2);
420 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
421 return get(Instruction::SetNE, C1, C2);
423 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
424 return get(Instruction::SetLT, C1, C2);
426 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
427 return get(Instruction::SetGT, C1, C2);
429 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
430 return get(Instruction::SetLE, C1, C2);
432 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
433 return get(Instruction::SetGE, C1, C2);
435 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
436 return get(Instruction::Shl, C1, C2);
438 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
439 return get(Instruction::Shr, C1, C2);
442 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
443 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
444 return getCast(getShr(getCast(C1,
445 C1->getType()->getUnsignedVersion()), C2), C1->getType());
448 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
449 if (C1->getType()->isSigned()) return getShr(C1, C2);
450 return getCast(getShr(getCast(C1,
451 C1->getType()->getSignedVersion()), C2), C1->getType());
455 //===----------------------------------------------------------------------===//
456 // isValueValidForType implementations
458 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
459 switch (Ty->getTypeID()) {
461 return false; // These can't be represented as integers!!!
463 case Type::SByteTyID:
464 return (Val <= INT8_MAX && Val >= INT8_MIN);
465 case Type::ShortTyID:
466 return (Val <= INT16_MAX && Val >= INT16_MIN);
468 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
470 return true; // This is the largest type...
474 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
475 switch (Ty->getTypeID()) {
477 return false; // These can't be represented as integers!!!
480 case Type::UByteTyID:
481 return (Val <= UINT8_MAX);
482 case Type::UShortTyID:
483 return (Val <= UINT16_MAX);
485 return (Val <= UINT32_MAX);
486 case Type::ULongTyID:
487 return true; // This is the largest type...
491 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
492 switch (Ty->getTypeID()) {
494 return false; // These can't be represented as floating point!
496 // TODO: Figure out how to test if a double can be cast to a float!
497 case Type::FloatTyID:
498 case Type::DoubleTyID:
499 return true; // This is the largest type...
503 //===----------------------------------------------------------------------===//
504 // Factory Function Implementation
506 // ConstantCreator - A class that is used to create constants by
507 // ValueMap*. This class should be partially specialized if there is
508 // something strange that needs to be done to interface to the ctor for the
512 template<class ConstantClass, class TypeClass, class ValType>
513 struct ConstantCreator {
514 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
515 return new ConstantClass(Ty, V);
519 template<class ConstantClass, class TypeClass>
520 struct ConvertConstantType {
521 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
522 assert(0 && "This type cannot be converted!\n");
529 template<class ValType, class TypeClass, class ConstantClass,
530 bool HasLargeKey = false /*true for arrays and structs*/ >
531 class ValueMap : public AbstractTypeUser {
533 typedef std::pair<const TypeClass*, ValType> MapKey;
534 typedef std::map<MapKey, ConstantClass *> MapTy;
535 typedef typename MapTy::iterator MapIterator;
537 /// Map - This is the main map from the element descriptor to the Constants.
538 /// This is the primary way we avoid creating two of the same shape
542 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
543 /// from the constants to their element in Map. This is important for
544 /// removal of constants from the array, which would otherwise have to scan
545 /// through the map with very large keys.
546 std::map<ConstantClass*, MapIterator> InverseMap;
548 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
549 AbstractTypeMapTy AbstractTypeMap;
551 friend void Constant::clearAllValueMaps();
553 void clear(std::vector<Constant *> &Constants) {
554 for(MapIterator I = Map.begin(); I != Map.end(); ++I)
555 Constants.push_back(I->second);
557 AbstractTypeMap.clear();
562 MapIterator map_end() { return Map.end(); }
564 /// InsertOrGetItem - Return an iterator for the specified element.
565 /// If the element exists in the map, the returned iterator points to the
566 /// entry and Exists=true. If not, the iterator points to the newly
567 /// inserted entry and returns Exists=false. Newly inserted entries have
568 /// I->second == 0, and should be filled in.
569 MapIterator InsertOrGetItem(std::pair<MapKey, ConstantClass *> &InsertVal,
571 std::pair<MapIterator, bool> IP = Map.insert(InsertVal);
577 MapIterator FindExistingElement(ConstantClass *CP) {
579 typename std::map<ConstantClass*, MapIterator>::iterator
580 IMI = InverseMap.find(CP);
581 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
582 IMI->second->second == CP &&
583 "InverseMap corrupt!");
588 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
589 if (I == Map.end() || I->second != CP) {
590 // FIXME: This should not use a linear scan. If this gets to be a
591 // performance problem, someone should look at this.
592 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
599 /// getOrCreate - Return the specified constant from the map, creating it if
601 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
602 MapKey Lookup(Ty, V);
603 MapIterator I = Map.lower_bound(Lookup);
604 if (I != Map.end() && I->first == Lookup)
605 return I->second; // Is it in the map?
607 // If no preexisting value, create one now...
608 ConstantClass *Result =
609 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
611 /// FIXME: why does this assert fail when loading 176.gcc?
612 //assert(Result->getType() == Ty && "Type specified is not correct!");
613 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
615 if (HasLargeKey) // Remember the reverse mapping if needed.
616 InverseMap.insert(std::make_pair(Result, I));
618 // If the type of the constant is abstract, make sure that an entry exists
619 // for it in the AbstractTypeMap.
620 if (Ty->isAbstract()) {
621 typename AbstractTypeMapTy::iterator TI =
622 AbstractTypeMap.lower_bound(Ty);
624 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
625 // Add ourselves to the ATU list of the type.
626 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
628 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
634 void remove(ConstantClass *CP) {
635 MapIterator I = FindExistingElement(CP);
636 assert(I != Map.end() && "Constant not found in constant table!");
637 assert(I->second == CP && "Didn't find correct element?");
639 if (HasLargeKey) // Remember the reverse mapping if needed.
640 InverseMap.erase(CP);
642 // Now that we found the entry, make sure this isn't the entry that
643 // the AbstractTypeMap points to.
644 const TypeClass *Ty = I->first.first;
645 if (Ty->isAbstract()) {
646 assert(AbstractTypeMap.count(Ty) &&
647 "Abstract type not in AbstractTypeMap?");
648 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
649 if (ATMEntryIt == I) {
650 // Yes, we are removing the representative entry for this type.
651 // See if there are any other entries of the same type.
652 MapIterator TmpIt = ATMEntryIt;
654 // First check the entry before this one...
655 if (TmpIt != Map.begin()) {
657 if (TmpIt->first.first != Ty) // Not the same type, move back...
661 // If we didn't find the same type, try to move forward...
662 if (TmpIt == ATMEntryIt) {
664 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
665 --TmpIt; // No entry afterwards with the same type
668 // If there is another entry in the map of the same abstract type,
669 // update the AbstractTypeMap entry now.
670 if (TmpIt != ATMEntryIt) {
673 // Otherwise, we are removing the last instance of this type
674 // from the table. Remove from the ATM, and from user list.
675 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
676 AbstractTypeMap.erase(Ty);
685 /// MoveConstantToNewSlot - If we are about to change C to be the element
686 /// specified by I, update our internal data structures to reflect this
688 void MoveConstantToNewSlot(ConstantClass *C, MapIterator I) {
689 // First, remove the old location of the specified constant in the map.
690 MapIterator OldI = FindExistingElement(C);
691 assert(OldI != Map.end() && "Constant not found in constant table!");
692 assert(OldI->second == C && "Didn't find correct element?");
694 // If this constant is the representative element for its abstract type,
695 // update the AbstractTypeMap so that the representative element is I.
696 if (C->getType()->isAbstract()) {
697 typename AbstractTypeMapTy::iterator ATI =
698 AbstractTypeMap.find(C->getType());
699 assert(ATI != AbstractTypeMap.end() &&
700 "Abstract type not in AbstractTypeMap?");
701 if (ATI->second == OldI)
705 // Remove the old entry from the map.
708 // Update the inverse map so that we know that this constant is now
709 // located at descriptor I.
711 assert(I->second == C && "Bad inversemap entry!");
716 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
717 typename AbstractTypeMapTy::iterator I =
718 AbstractTypeMap.find(cast<TypeClass>(OldTy));
720 assert(I != AbstractTypeMap.end() &&
721 "Abstract type not in AbstractTypeMap?");
723 // Convert a constant at a time until the last one is gone. The last one
724 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
725 // eliminated eventually.
727 ConvertConstantType<ConstantClass,
728 TypeClass>::convert(I->second->second,
729 cast<TypeClass>(NewTy));
731 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
732 } while (I != AbstractTypeMap.end());
735 // If the type became concrete without being refined to any other existing
736 // type, we just remove ourselves from the ATU list.
737 void typeBecameConcrete(const DerivedType *AbsTy) {
738 AbsTy->removeAbstractTypeUser(this);
742 std::cerr << "Constant.cpp: ValueMap\n";
747 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
749 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
750 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
752 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
753 return SIntConstants.getOrCreate(Ty, V);
756 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
757 return UIntConstants.getOrCreate(Ty, V);
760 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
761 assert(V <= 127 && "Can only be used with very small positive constants!");
762 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
763 return ConstantUInt::get(Ty, V);
766 //---- ConstantFP::get() implementation...
770 struct ConstantCreator<ConstantFP, Type, uint64_t> {
771 static ConstantFP *create(const Type *Ty, uint64_t V) {
772 assert(Ty == Type::DoubleTy);
773 return new ConstantFP(Ty, BitsToDouble(V));
777 struct ConstantCreator<ConstantFP, Type, uint32_t> {
778 static ConstantFP *create(const Type *Ty, uint32_t V) {
779 assert(Ty == Type::FloatTy);
780 return new ConstantFP(Ty, BitsToFloat(V));
785 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
786 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
788 bool ConstantFP::isNullValue() const {
789 return DoubleToBits(Val) == 0;
792 bool ConstantFP::isExactlyValue(double V) const {
793 return DoubleToBits(V) == DoubleToBits(Val);
797 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
798 if (Ty == Type::FloatTy) {
799 // Force the value through memory to normalize it.
800 return FloatConstants.getOrCreate(Ty, FloatToBits(V));
802 assert(Ty == Type::DoubleTy);
803 return DoubleConstants.getOrCreate(Ty, DoubleToBits(V));
807 //---- ConstantAggregateZero::get() implementation...
810 // ConstantAggregateZero does not take extra "value" argument...
811 template<class ValType>
812 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
813 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
814 return new ConstantAggregateZero(Ty);
819 struct ConvertConstantType<ConstantAggregateZero, Type> {
820 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
821 // Make everyone now use a constant of the new type...
822 Constant *New = ConstantAggregateZero::get(NewTy);
823 assert(New != OldC && "Didn't replace constant??");
824 OldC->uncheckedReplaceAllUsesWith(New);
825 OldC->destroyConstant(); // This constant is now dead, destroy it.
830 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
832 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
834 Constant *ConstantAggregateZero::get(const Type *Ty) {
835 return AggZeroConstants.getOrCreate(Ty, 0);
838 // destroyConstant - Remove the constant from the constant table...
840 void ConstantAggregateZero::destroyConstant() {
841 AggZeroConstants.remove(this);
842 destroyConstantImpl();
845 //---- ConstantArray::get() implementation...
849 struct ConvertConstantType<ConstantArray, ArrayType> {
850 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
851 // Make everyone now use a constant of the new type...
852 std::vector<Constant*> C;
853 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
854 C.push_back(cast<Constant>(OldC->getOperand(i)));
855 Constant *New = ConstantArray::get(NewTy, C);
856 assert(New != OldC && "Didn't replace constant??");
857 OldC->uncheckedReplaceAllUsesWith(New);
858 OldC->destroyConstant(); // This constant is now dead, destroy it.
863 static std::vector<Constant*> getValType(ConstantArray *CA) {
864 std::vector<Constant*> Elements;
865 Elements.reserve(CA->getNumOperands());
866 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
867 Elements.push_back(cast<Constant>(CA->getOperand(i)));
871 typedef ValueMap<std::vector<Constant*>, ArrayType,
872 ConstantArray, true /*largekey*/> ArrayConstantsTy;
873 static ArrayConstantsTy ArrayConstants;
875 Constant *ConstantArray::get(const ArrayType *Ty,
876 const std::vector<Constant*> &V) {
877 // If this is an all-zero array, return a ConstantAggregateZero object
880 if (!C->isNullValue())
881 return ArrayConstants.getOrCreate(Ty, V);
882 for (unsigned i = 1, e = V.size(); i != e; ++i)
884 return ArrayConstants.getOrCreate(Ty, V);
886 return ConstantAggregateZero::get(Ty);
889 // destroyConstant - Remove the constant from the constant table...
891 void ConstantArray::destroyConstant() {
892 ArrayConstants.remove(this);
893 destroyConstantImpl();
896 // ConstantArray::get(const string&) - Return an array that is initialized to
897 // contain the specified string. A null terminator is added to the specified
898 // string so that it may be used in a natural way...
900 Constant *ConstantArray::get(const std::string &Str) {
901 std::vector<Constant*> ElementVals;
903 for (unsigned i = 0; i < Str.length(); ++i)
904 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
906 // Add a null terminator to the string...
907 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
909 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
910 return ConstantArray::get(ATy, ElementVals);
913 /// isString - This method returns true if the array is an array of sbyte or
914 /// ubyte, and if the elements of the array are all ConstantInt's.
915 bool ConstantArray::isString() const {
916 // Check the element type for sbyte or ubyte...
917 if (getType()->getElementType() != Type::UByteTy &&
918 getType()->getElementType() != Type::SByteTy)
920 // Check the elements to make sure they are all integers, not constant
922 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
923 if (!isa<ConstantInt>(getOperand(i)))
928 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
929 // then this method converts the array to an std::string and returns it.
930 // Otherwise, it asserts out.
932 std::string ConstantArray::getAsString() const {
933 assert(isString() && "Not a string!");
935 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
936 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
941 //---- ConstantStruct::get() implementation...
946 struct ConvertConstantType<ConstantStruct, StructType> {
947 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
948 // Make everyone now use a constant of the new type...
949 std::vector<Constant*> C;
950 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
951 C.push_back(cast<Constant>(OldC->getOperand(i)));
952 Constant *New = ConstantStruct::get(NewTy, C);
953 assert(New != OldC && "Didn't replace constant??");
955 OldC->uncheckedReplaceAllUsesWith(New);
956 OldC->destroyConstant(); // This constant is now dead, destroy it.
961 typedef ValueMap<std::vector<Constant*>, StructType,
962 ConstantStruct, true /*largekey*/> StructConstantsTy;
963 static StructConstantsTy StructConstants;
965 static std::vector<Constant*> getValType(ConstantStruct *CS) {
966 std::vector<Constant*> Elements;
967 Elements.reserve(CS->getNumOperands());
968 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
969 Elements.push_back(cast<Constant>(CS->getOperand(i)));
973 Constant *ConstantStruct::get(const StructType *Ty,
974 const std::vector<Constant*> &V) {
975 // Create a ConstantAggregateZero value if all elements are zeros...
976 for (unsigned i = 0, e = V.size(); i != e; ++i)
977 if (!V[i]->isNullValue())
978 return StructConstants.getOrCreate(Ty, V);
980 return ConstantAggregateZero::get(Ty);
983 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
984 std::vector<const Type*> StructEls;
985 StructEls.reserve(V.size());
986 for (unsigned i = 0, e = V.size(); i != e; ++i)
987 StructEls.push_back(V[i]->getType());
988 return get(StructType::get(StructEls), V);
991 // destroyConstant - Remove the constant from the constant table...
993 void ConstantStruct::destroyConstant() {
994 StructConstants.remove(this);
995 destroyConstantImpl();
998 //---- ConstantPacked::get() implementation...
1002 struct ConvertConstantType<ConstantPacked, PackedType> {
1003 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1004 // Make everyone now use a constant of the new type...
1005 std::vector<Constant*> C;
1006 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1007 C.push_back(cast<Constant>(OldC->getOperand(i)));
1008 Constant *New = ConstantPacked::get(NewTy, C);
1009 assert(New != OldC && "Didn't replace constant??");
1010 OldC->uncheckedReplaceAllUsesWith(New);
1011 OldC->destroyConstant(); // This constant is now dead, destroy it.
1016 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1017 std::vector<Constant*> Elements;
1018 Elements.reserve(CP->getNumOperands());
1019 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1020 Elements.push_back(CP->getOperand(i));
1024 static ValueMap<std::vector<Constant*>, PackedType,
1025 ConstantPacked> PackedConstants;
1027 Constant *ConstantPacked::get(const PackedType *Ty,
1028 const std::vector<Constant*> &V) {
1029 // If this is an all-zero packed, return a ConstantAggregateZero object
1032 if (!C->isNullValue())
1033 return PackedConstants.getOrCreate(Ty, V);
1034 for (unsigned i = 1, e = V.size(); i != e; ++i)
1036 return PackedConstants.getOrCreate(Ty, V);
1038 return ConstantAggregateZero::get(Ty);
1041 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1042 assert(!V.empty() && "Cannot infer type if V is empty");
1043 return get(PackedType::get(V.front()->getType(),V.size()), V);
1046 // destroyConstant - Remove the constant from the constant table...
1048 void ConstantPacked::destroyConstant() {
1049 PackedConstants.remove(this);
1050 destroyConstantImpl();
1053 //---- ConstantPointerNull::get() implementation...
1057 // ConstantPointerNull does not take extra "value" argument...
1058 template<class ValType>
1059 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1060 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1061 return new ConstantPointerNull(Ty);
1066 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1067 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1068 // Make everyone now use a constant of the new type...
1069 Constant *New = ConstantPointerNull::get(NewTy);
1070 assert(New != OldC && "Didn't replace constant??");
1071 OldC->uncheckedReplaceAllUsesWith(New);
1072 OldC->destroyConstant(); // This constant is now dead, destroy it.
1077 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1079 static char getValType(ConstantPointerNull *) {
1084 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1085 return NullPtrConstants.getOrCreate(Ty, 0);
1088 // destroyConstant - Remove the constant from the constant table...
1090 void ConstantPointerNull::destroyConstant() {
1091 NullPtrConstants.remove(this);
1092 destroyConstantImpl();
1096 //---- UndefValue::get() implementation...
1100 // UndefValue does not take extra "value" argument...
1101 template<class ValType>
1102 struct ConstantCreator<UndefValue, Type, ValType> {
1103 static UndefValue *create(const Type *Ty, const ValType &V) {
1104 return new UndefValue(Ty);
1109 struct ConvertConstantType<UndefValue, Type> {
1110 static void convert(UndefValue *OldC, const Type *NewTy) {
1111 // Make everyone now use a constant of the new type.
1112 Constant *New = UndefValue::get(NewTy);
1113 assert(New != OldC && "Didn't replace constant??");
1114 OldC->uncheckedReplaceAllUsesWith(New);
1115 OldC->destroyConstant(); // This constant is now dead, destroy it.
1120 static ValueMap<char, Type, UndefValue> UndefValueConstants;
1122 static char getValType(UndefValue *) {
1127 UndefValue *UndefValue::get(const Type *Ty) {
1128 return UndefValueConstants.getOrCreate(Ty, 0);
1131 // destroyConstant - Remove the constant from the constant table.
1133 void UndefValue::destroyConstant() {
1134 UndefValueConstants.remove(this);
1135 destroyConstantImpl();
1141 //---- ConstantExpr::get() implementations...
1143 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1147 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1148 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1149 if (V.first == Instruction::Cast)
1150 return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1151 if ((V.first >= Instruction::BinaryOpsBegin &&
1152 V.first < Instruction::BinaryOpsEnd) ||
1153 V.first == Instruction::Shl || V.first == Instruction::Shr)
1154 return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1155 if (V.first == Instruction::Select)
1156 return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1157 if (V.first == Instruction::ExtractElement)
1158 return new ExtractElementConstantExpr(V.second[0], V.second[1]);
1160 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1162 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1163 return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1168 struct ConvertConstantType<ConstantExpr, Type> {
1169 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1171 switch (OldC->getOpcode()) {
1172 case Instruction::Cast:
1173 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1175 case Instruction::Select:
1176 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1177 OldC->getOperand(1),
1178 OldC->getOperand(2));
1180 case Instruction::Shl:
1181 case Instruction::Shr:
1182 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1183 OldC->getOperand(0), OldC->getOperand(1));
1186 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1187 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1188 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1189 OldC->getOperand(1));
1191 case Instruction::GetElementPtr:
1192 // Make everyone now use a constant of the new type...
1193 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1194 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1198 assert(New != OldC && "Didn't replace constant??");
1199 OldC->uncheckedReplaceAllUsesWith(New);
1200 OldC->destroyConstant(); // This constant is now dead, destroy it.
1203 } // end namespace llvm
1206 static ExprMapKeyType getValType(ConstantExpr *CE) {
1207 std::vector<Constant*> Operands;
1208 Operands.reserve(CE->getNumOperands());
1209 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1210 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1211 return ExprMapKeyType(CE->getOpcode(), Operands);
1214 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1216 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1217 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1219 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1220 return FC; // Fold a few common cases...
1222 // Look up the constant in the table first to ensure uniqueness
1223 std::vector<Constant*> argVec(1, C);
1224 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1225 return ExprConstants.getOrCreate(Ty, Key);
1228 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1229 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1230 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1231 "This is an illegal sign extension!");
1232 if (C->getType() != Type::BoolTy) {
1233 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1234 return ConstantExpr::getCast(C, Ty);
1236 if (C == ConstantBool::True)
1237 return ConstantIntegral::getAllOnesValue(Ty);
1239 return ConstantIntegral::getNullValue(Ty);
1243 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1244 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1245 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1246 "This is an illegal zero extension!");
1247 if (C->getType() != Type::BoolTy)
1248 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1249 return ConstantExpr::getCast(C, Ty);
1252 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1253 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1255 getGetElementPtr(getNullValue(PointerType::get(Ty)),
1256 std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1260 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1261 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1262 static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1264 return ConstantExpr::getGetElementPtr(C, Indices);
1267 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1268 Constant *C1, Constant *C2) {
1269 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1270 return getShiftTy(ReqTy, Opcode, C1, C2);
1271 // Check the operands for consistency first
1272 assert((Opcode >= Instruction::BinaryOpsBegin &&
1273 Opcode < Instruction::BinaryOpsEnd) &&
1274 "Invalid opcode in binary constant expression");
1275 assert(C1->getType() == C2->getType() &&
1276 "Operand types in binary constant expression should match");
1278 if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1279 ReqTy == Type::BoolTy))
1280 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1281 return FC; // Fold a few common cases...
1283 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1284 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1285 return ExprConstants.getOrCreate(ReqTy, Key);
1288 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1291 case Instruction::Add: case Instruction::Sub:
1292 case Instruction::Mul: case Instruction::Div:
1293 case Instruction::Rem:
1294 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1295 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1296 isa<PackedType>(C1->getType())) &&
1297 "Tried to create an arithmetic operation on a non-arithmetic type!");
1299 case Instruction::And:
1300 case Instruction::Or:
1301 case Instruction::Xor:
1302 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1303 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1304 "Tried to create a logical operation on a non-integral type!");
1306 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1307 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1308 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1310 case Instruction::Shl:
1311 case Instruction::Shr:
1312 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1313 assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
1314 "Tried to create a shift operation on a non-integer type!");
1321 if (Instruction::isRelational(Opcode))
1322 return getTy(Type::BoolTy, Opcode, C1, C2);
1324 return getTy(C1->getType(), Opcode, C1, C2);
1327 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1328 Constant *V1, Constant *V2) {
1329 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1330 assert(V1->getType() == V2->getType() && "Select value types must match!");
1331 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1333 if (ReqTy == V1->getType())
1334 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1335 return SC; // Fold common cases
1337 std::vector<Constant*> argVec(3, C);
1340 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1341 return ExprConstants.getOrCreate(ReqTy, Key);
1344 /// getShiftTy - Return a shift left or shift right constant expr
1345 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1346 Constant *C1, Constant *C2) {
1347 // Check the operands for consistency first
1348 assert((Opcode == Instruction::Shl ||
1349 Opcode == Instruction::Shr) &&
1350 "Invalid opcode in binary constant expression");
1351 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1352 "Invalid operand types for Shift constant expr!");
1354 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1355 return FC; // Fold a few common cases...
1357 // Look up the constant in the table first to ensure uniqueness
1358 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1359 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1360 return ExprConstants.getOrCreate(ReqTy, Key);
1364 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1365 const std::vector<Value*> &IdxList) {
1366 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1367 "GEP indices invalid!");
1369 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1370 return FC; // Fold a few common cases...
1372 assert(isa<PointerType>(C->getType()) &&
1373 "Non-pointer type for constant GetElementPtr expression");
1374 // Look up the constant in the table first to ensure uniqueness
1375 std::vector<Constant*> ArgVec;
1376 ArgVec.reserve(IdxList.size()+1);
1377 ArgVec.push_back(C);
1378 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1379 ArgVec.push_back(cast<Constant>(IdxList[i]));
1380 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1381 return ExprConstants.getOrCreate(ReqTy, Key);
1384 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1385 const std::vector<Constant*> &IdxList){
1386 // Get the result type of the getelementptr!
1387 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1389 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1391 assert(Ty && "GEP indices invalid!");
1392 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1395 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1396 const std::vector<Value*> &IdxList) {
1397 // Get the result type of the getelementptr!
1398 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1400 assert(Ty && "GEP indices invalid!");
1401 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1404 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1406 // Look up the constant in the table first to ensure uniqueness
1407 std::vector<Constant*> ArgVec(1, Val);
1408 ArgVec.push_back(Idx);
1409 const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
1410 return ExprConstants.getOrCreate(ReqTy, Key);
1413 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1414 assert(isa<PackedType>(Val->getType()) &&
1415 "Tried to create extractelement operation on non-packed type!");
1416 assert(Idx->getType() == Type::UIntTy &&
1417 "Index must be uint type!");
1418 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1422 // destroyConstant - Remove the constant from the constant table...
1424 void ConstantExpr::destroyConstant() {
1425 ExprConstants.remove(this);
1426 destroyConstantImpl();
1429 const char *ConstantExpr::getOpcodeName() const {
1430 return Instruction::getOpcodeName(getOpcode());
1433 //===----------------------------------------------------------------------===//
1434 // replaceUsesOfWithOnConstant implementations
1436 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1438 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1439 Constant *ToC = cast<Constant>(To);
1441 unsigned OperandToUpdate = U-OperandList;
1442 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1444 std::pair<ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1445 Lookup.first.first = getType();
1446 Lookup.second = this;
1448 std::vector<Constant*> &Values = Lookup.first.second;
1449 Values.reserve(getNumOperands()); // Build replacement array.
1451 // Fill values with the modified operands of the constant array. Also,
1452 // compute whether this turns into an all-zeros array.
1453 bool isAllZeros = false;
1454 if (!ToC->isNullValue()) {
1455 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1456 Values.push_back(cast<Constant>(O->get()));
1459 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1460 Constant *Val = cast<Constant>(O->get());
1461 Values.push_back(Val);
1462 if (isAllZeros) isAllZeros = Val->isNullValue();
1465 Values[OperandToUpdate] = ToC;
1467 Constant *Replacement = 0;
1469 Replacement = ConstantAggregateZero::get(getType());
1471 // Check to see if we have this array type already.
1473 ArrayConstantsTy::MapIterator I =
1474 ArrayConstants.InsertOrGetItem(Lookup, Exists);
1477 Replacement = I->second;
1479 // Okay, the new shape doesn't exist in the system yet. Instead of
1480 // creating a new constant array, inserting it, replaceallusesof'ing the
1481 // old with the new, then deleting the old... just update the current one
1483 ArrayConstants.MoveConstantToNewSlot(this, I);
1485 // Update to the new value.
1486 setOperand(OperandToUpdate, ToC);
1491 // Otherwise, I do need to replace this with an existing value.
1492 assert(Replacement != this && "I didn't contain From!");
1494 // Everyone using this now uses the replacement.
1495 uncheckedReplaceAllUsesWith(Replacement);
1497 // Delete the old constant!
1501 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1503 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1504 Constant *ToC = cast<Constant>(To);
1506 unsigned OperandToUpdate = U-OperandList;
1507 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1509 std::pair<StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1510 Lookup.first.first = getType();
1511 Lookup.second = this;
1512 std::vector<Constant*> &Values = Lookup.first.second;
1513 Values.reserve(getNumOperands()); // Build replacement struct.
1516 // Fill values with the modified operands of the constant struct. Also,
1517 // compute whether this turns into an all-zeros struct.
1518 bool isAllZeros = false;
1519 if (!ToC->isNullValue()) {
1520 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1521 Values.push_back(cast<Constant>(O->get()));
1524 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1525 Constant *Val = cast<Constant>(O->get());
1526 Values.push_back(Val);
1527 if (isAllZeros) isAllZeros = Val->isNullValue();
1530 Values[OperandToUpdate] = ToC;
1532 Constant *Replacement = 0;
1534 Replacement = ConstantAggregateZero::get(getType());
1536 // Check to see if we have this array type already.
1538 StructConstantsTy::MapIterator I =
1539 StructConstants.InsertOrGetItem(Lookup, Exists);
1542 Replacement = I->second;
1544 // Okay, the new shape doesn't exist in the system yet. Instead of
1545 // creating a new constant struct, inserting it, replaceallusesof'ing the
1546 // old with the new, then deleting the old... just update the current one
1548 StructConstants.MoveConstantToNewSlot(this, I);
1550 // Update to the new value.
1551 setOperand(OperandToUpdate, ToC);
1556 assert(Replacement != this && "I didn't contain From!");
1558 // Everyone using this now uses the replacement.
1559 uncheckedReplaceAllUsesWith(Replacement);
1561 // Delete the old constant!
1565 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1567 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1569 std::vector<Constant*> Values;
1570 Values.reserve(getNumOperands()); // Build replacement array...
1571 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1572 Constant *Val = getOperand(i);
1573 if (Val == From) Val = cast<Constant>(To);
1574 Values.push_back(Val);
1577 Constant *Replacement = ConstantPacked::get(getType(), Values);
1578 assert(Replacement != this && "I didn't contain From!");
1580 // Everyone using this now uses the replacement.
1581 uncheckedReplaceAllUsesWith(Replacement);
1583 // Delete the old constant!
1587 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1589 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1590 Constant *To = cast<Constant>(ToV);
1592 Constant *Replacement = 0;
1593 if (getOpcode() == Instruction::GetElementPtr) {
1594 std::vector<Constant*> Indices;
1595 Constant *Pointer = getOperand(0);
1596 Indices.reserve(getNumOperands()-1);
1597 if (Pointer == From) Pointer = To;
1599 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1600 Constant *Val = getOperand(i);
1601 if (Val == From) Val = To;
1602 Indices.push_back(Val);
1604 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1605 } else if (getOpcode() == Instruction::Cast) {
1606 assert(getOperand(0) == From && "Cast only has one use!");
1607 Replacement = ConstantExpr::getCast(To, getType());
1608 } else if (getOpcode() == Instruction::Select) {
1609 Constant *C1 = getOperand(0);
1610 Constant *C2 = getOperand(1);
1611 Constant *C3 = getOperand(2);
1612 if (C1 == From) C1 = To;
1613 if (C2 == From) C2 = To;
1614 if (C3 == From) C3 = To;
1615 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1616 } else if (getOpcode() == Instruction::ExtractElement) {
1617 Constant *C1 = getOperand(0);
1618 Constant *C2 = getOperand(1);
1619 if (C1 == From) C1 = To;
1620 if (C2 == From) C2 = To;
1621 Replacement = ConstantExpr::getExtractElement(C1, C2);
1622 } else if (getNumOperands() == 2) {
1623 Constant *C1 = getOperand(0);
1624 Constant *C2 = getOperand(1);
1625 if (C1 == From) C1 = To;
1626 if (C2 == From) C2 = To;
1627 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1629 assert(0 && "Unknown ConstantExpr type!");
1633 assert(Replacement != this && "I didn't contain From!");
1635 // Everyone using this now uses the replacement.
1636 uncheckedReplaceAllUsesWith(Replacement);
1638 // Delete the old constant!
1644 /// clearAllValueMaps - This method frees all internal memory used by the
1645 /// constant subsystem, which can be used in environments where this memory
1646 /// is otherwise reported as a leak.
1647 void Constant::clearAllValueMaps() {
1648 std::vector<Constant *> Constants;
1650 DoubleConstants.clear(Constants);
1651 FloatConstants.clear(Constants);
1652 SIntConstants.clear(Constants);
1653 UIntConstants.clear(Constants);
1654 AggZeroConstants.clear(Constants);
1655 ArrayConstants.clear(Constants);
1656 StructConstants.clear(Constants);
1657 PackedConstants.clear(Constants);
1658 NullPtrConstants.clear(Constants);
1659 UndefValueConstants.clear(Constants);
1660 ExprConstants.clear(Constants);
1662 for (std::vector<Constant *>::iterator I = Constants.begin(),
1663 E = Constants.end(); I != E; ++I)
1664 (*I)->dropAllReferences();
1665 for (std::vector<Constant *>::iterator I = Constants.begin(),
1666 E = Constants.end(); I != E; ++I)
1667 (*I)->destroyConstantImpl();