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
351 /// Constants.cpp, and is used behind the scenes to implement
352 /// extractelement constant exprs.
353 class ExtractElementConstantExpr : public ConstantExpr {
356 ExtractElementConstantExpr(Constant *C1, Constant *C2)
357 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
358 Instruction::ExtractElement, Ops, 2) {
359 Ops[0].init(C1, this);
360 Ops[1].init(C2, this);
364 /// InsertElementConstantExpr - This class is private to
365 /// Constants.cpp, and is used behind the scenes to implement
366 /// insertelement constant exprs.
367 class InsertElementConstantExpr : public ConstantExpr {
370 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
371 : ConstantExpr(C1->getType(), Instruction::InsertElement,
373 Ops[0].init(C1, this);
374 Ops[1].init(C2, this);
375 Ops[2].init(C3, this);
379 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
380 /// used behind the scenes to implement getelementpr constant exprs.
381 struct GetElementPtrConstantExpr : public ConstantExpr {
382 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
384 : ConstantExpr(DestTy, Instruction::GetElementPtr,
385 new Use[IdxList.size()+1], IdxList.size()+1) {
386 OperandList[0].init(C, this);
387 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
388 OperandList[i+1].init(IdxList[i], this);
390 ~GetElementPtrConstantExpr() {
391 delete [] OperandList;
395 /// ConstantExpr::get* - Return some common constants without having to
396 /// specify the full Instruction::OPCODE identifier.
398 Constant *ConstantExpr::getNeg(Constant *C) {
399 if (!C->getType()->isFloatingPoint())
400 return get(Instruction::Sub, getNullValue(C->getType()), C);
402 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
404 Constant *ConstantExpr::getNot(Constant *C) {
405 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
406 return get(Instruction::Xor, C,
407 ConstantIntegral::getAllOnesValue(C->getType()));
409 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
410 return get(Instruction::Add, C1, C2);
412 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
413 return get(Instruction::Sub, C1, C2);
415 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
416 return get(Instruction::Mul, C1, C2);
418 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
419 return get(Instruction::Div, C1, C2);
421 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
422 return get(Instruction::Rem, C1, C2);
424 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
425 return get(Instruction::And, C1, C2);
427 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
428 return get(Instruction::Or, C1, C2);
430 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
431 return get(Instruction::Xor, C1, C2);
433 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
434 return get(Instruction::SetEQ, C1, C2);
436 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
437 return get(Instruction::SetNE, C1, C2);
439 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
440 return get(Instruction::SetLT, C1, C2);
442 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
443 return get(Instruction::SetGT, C1, C2);
445 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
446 return get(Instruction::SetLE, C1, C2);
448 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
449 return get(Instruction::SetGE, C1, C2);
451 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
452 return get(Instruction::Shl, C1, C2);
454 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
455 return get(Instruction::Shr, C1, C2);
458 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
459 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
460 return getCast(getShr(getCast(C1,
461 C1->getType()->getUnsignedVersion()), C2), C1->getType());
464 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
465 if (C1->getType()->isSigned()) return getShr(C1, C2);
466 return getCast(getShr(getCast(C1,
467 C1->getType()->getSignedVersion()), C2), C1->getType());
471 //===----------------------------------------------------------------------===//
472 // isValueValidForType implementations
474 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
475 switch (Ty->getTypeID()) {
477 return false; // These can't be represented as integers!!!
479 case Type::SByteTyID:
480 return (Val <= INT8_MAX && Val >= INT8_MIN);
481 case Type::ShortTyID:
482 return (Val <= INT16_MAX && Val >= INT16_MIN);
484 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
486 return true; // This is the largest type...
490 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
491 switch (Ty->getTypeID()) {
493 return false; // These can't be represented as integers!!!
496 case Type::UByteTyID:
497 return (Val <= UINT8_MAX);
498 case Type::UShortTyID:
499 return (Val <= UINT16_MAX);
501 return (Val <= UINT32_MAX);
502 case Type::ULongTyID:
503 return true; // This is the largest type...
507 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
508 switch (Ty->getTypeID()) {
510 return false; // These can't be represented as floating point!
512 // TODO: Figure out how to test if a double can be cast to a float!
513 case Type::FloatTyID:
514 case Type::DoubleTyID:
515 return true; // This is the largest type...
519 //===----------------------------------------------------------------------===//
520 // Factory Function Implementation
522 // ConstantCreator - A class that is used to create constants by
523 // ValueMap*. This class should be partially specialized if there is
524 // something strange that needs to be done to interface to the ctor for the
528 template<class ConstantClass, class TypeClass, class ValType>
529 struct ConstantCreator {
530 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
531 return new ConstantClass(Ty, V);
535 template<class ConstantClass, class TypeClass>
536 struct ConvertConstantType {
537 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
538 assert(0 && "This type cannot be converted!\n");
545 template<class ValType, class TypeClass, class ConstantClass,
546 bool HasLargeKey = false /*true for arrays and structs*/ >
547 class ValueMap : public AbstractTypeUser {
549 typedef std::pair<const TypeClass*, ValType> MapKey;
550 typedef std::map<MapKey, ConstantClass *> MapTy;
551 typedef typename MapTy::iterator MapIterator;
553 /// Map - This is the main map from the element descriptor to the Constants.
554 /// This is the primary way we avoid creating two of the same shape
558 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
559 /// from the constants to their element in Map. This is important for
560 /// removal of constants from the array, which would otherwise have to scan
561 /// through the map with very large keys.
562 std::map<ConstantClass*, MapIterator> InverseMap;
564 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
565 AbstractTypeMapTy AbstractTypeMap;
567 friend void Constant::clearAllValueMaps();
569 void clear(std::vector<Constant *> &Constants) {
570 for(MapIterator I = Map.begin(); I != Map.end(); ++I)
571 Constants.push_back(I->second);
573 AbstractTypeMap.clear();
578 MapIterator map_end() { return Map.end(); }
580 /// InsertOrGetItem - Return an iterator for the specified element.
581 /// If the element exists in the map, the returned iterator points to the
582 /// entry and Exists=true. If not, the iterator points to the newly
583 /// inserted entry and returns Exists=false. Newly inserted entries have
584 /// I->second == 0, and should be filled in.
585 MapIterator InsertOrGetItem(std::pair<MapKey, ConstantClass *> &InsertVal,
587 std::pair<MapIterator, bool> IP = Map.insert(InsertVal);
593 MapIterator FindExistingElement(ConstantClass *CP) {
595 typename std::map<ConstantClass*, MapIterator>::iterator
596 IMI = InverseMap.find(CP);
597 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
598 IMI->second->second == CP &&
599 "InverseMap corrupt!");
604 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
605 if (I == Map.end() || I->second != CP) {
606 // FIXME: This should not use a linear scan. If this gets to be a
607 // performance problem, someone should look at this.
608 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
615 /// getOrCreate - Return the specified constant from the map, creating it if
617 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
618 MapKey Lookup(Ty, V);
619 MapIterator I = Map.lower_bound(Lookup);
620 if (I != Map.end() && I->first == Lookup)
621 return I->second; // Is it in the map?
623 // If no preexisting value, create one now...
624 ConstantClass *Result =
625 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
627 /// FIXME: why does this assert fail when loading 176.gcc?
628 //assert(Result->getType() == Ty && "Type specified is not correct!");
629 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
631 if (HasLargeKey) // Remember the reverse mapping if needed.
632 InverseMap.insert(std::make_pair(Result, I));
634 // If the type of the constant is abstract, make sure that an entry exists
635 // for it in the AbstractTypeMap.
636 if (Ty->isAbstract()) {
637 typename AbstractTypeMapTy::iterator TI =
638 AbstractTypeMap.lower_bound(Ty);
640 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
641 // Add ourselves to the ATU list of the type.
642 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
644 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
650 void remove(ConstantClass *CP) {
651 MapIterator I = FindExistingElement(CP);
652 assert(I != Map.end() && "Constant not found in constant table!");
653 assert(I->second == CP && "Didn't find correct element?");
655 if (HasLargeKey) // Remember the reverse mapping if needed.
656 InverseMap.erase(CP);
658 // Now that we found the entry, make sure this isn't the entry that
659 // the AbstractTypeMap points to.
660 const TypeClass *Ty = I->first.first;
661 if (Ty->isAbstract()) {
662 assert(AbstractTypeMap.count(Ty) &&
663 "Abstract type not in AbstractTypeMap?");
664 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
665 if (ATMEntryIt == I) {
666 // Yes, we are removing the representative entry for this type.
667 // See if there are any other entries of the same type.
668 MapIterator TmpIt = ATMEntryIt;
670 // First check the entry before this one...
671 if (TmpIt != Map.begin()) {
673 if (TmpIt->first.first != Ty) // Not the same type, move back...
677 // If we didn't find the same type, try to move forward...
678 if (TmpIt == ATMEntryIt) {
680 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
681 --TmpIt; // No entry afterwards with the same type
684 // If there is another entry in the map of the same abstract type,
685 // update the AbstractTypeMap entry now.
686 if (TmpIt != ATMEntryIt) {
689 // Otherwise, we are removing the last instance of this type
690 // from the table. Remove from the ATM, and from user list.
691 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
692 AbstractTypeMap.erase(Ty);
701 /// MoveConstantToNewSlot - If we are about to change C to be the element
702 /// specified by I, update our internal data structures to reflect this
704 void MoveConstantToNewSlot(ConstantClass *C, MapIterator I) {
705 // First, remove the old location of the specified constant in the map.
706 MapIterator OldI = FindExistingElement(C);
707 assert(OldI != Map.end() && "Constant not found in constant table!");
708 assert(OldI->second == C && "Didn't find correct element?");
710 // If this constant is the representative element for its abstract type,
711 // update the AbstractTypeMap so that the representative element is I.
712 if (C->getType()->isAbstract()) {
713 typename AbstractTypeMapTy::iterator ATI =
714 AbstractTypeMap.find(C->getType());
715 assert(ATI != AbstractTypeMap.end() &&
716 "Abstract type not in AbstractTypeMap?");
717 if (ATI->second == OldI)
721 // Remove the old entry from the map.
724 // Update the inverse map so that we know that this constant is now
725 // located at descriptor I.
727 assert(I->second == C && "Bad inversemap entry!");
732 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
733 typename AbstractTypeMapTy::iterator I =
734 AbstractTypeMap.find(cast<TypeClass>(OldTy));
736 assert(I != AbstractTypeMap.end() &&
737 "Abstract type not in AbstractTypeMap?");
739 // Convert a constant at a time until the last one is gone. The last one
740 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
741 // eliminated eventually.
743 ConvertConstantType<ConstantClass,
744 TypeClass>::convert(I->second->second,
745 cast<TypeClass>(NewTy));
747 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
748 } while (I != AbstractTypeMap.end());
751 // If the type became concrete without being refined to any other existing
752 // type, we just remove ourselves from the ATU list.
753 void typeBecameConcrete(const DerivedType *AbsTy) {
754 AbsTy->removeAbstractTypeUser(this);
758 std::cerr << "Constant.cpp: ValueMap\n";
763 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
765 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
766 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
768 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
769 return SIntConstants.getOrCreate(Ty, V);
772 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
773 return UIntConstants.getOrCreate(Ty, V);
776 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
777 assert(V <= 127 && "Can only be used with very small positive constants!");
778 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
779 return ConstantUInt::get(Ty, V);
782 //---- ConstantFP::get() implementation...
786 struct ConstantCreator<ConstantFP, Type, uint64_t> {
787 static ConstantFP *create(const Type *Ty, uint64_t V) {
788 assert(Ty == Type::DoubleTy);
789 return new ConstantFP(Ty, BitsToDouble(V));
793 struct ConstantCreator<ConstantFP, Type, uint32_t> {
794 static ConstantFP *create(const Type *Ty, uint32_t V) {
795 assert(Ty == Type::FloatTy);
796 return new ConstantFP(Ty, BitsToFloat(V));
801 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
802 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
804 bool ConstantFP::isNullValue() const {
805 return DoubleToBits(Val) == 0;
808 bool ConstantFP::isExactlyValue(double V) const {
809 return DoubleToBits(V) == DoubleToBits(Val);
813 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
814 if (Ty == Type::FloatTy) {
815 // Force the value through memory to normalize it.
816 return FloatConstants.getOrCreate(Ty, FloatToBits(V));
818 assert(Ty == Type::DoubleTy);
819 return DoubleConstants.getOrCreate(Ty, DoubleToBits(V));
823 //---- ConstantAggregateZero::get() implementation...
826 // ConstantAggregateZero does not take extra "value" argument...
827 template<class ValType>
828 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
829 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
830 return new ConstantAggregateZero(Ty);
835 struct ConvertConstantType<ConstantAggregateZero, Type> {
836 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
837 // Make everyone now use a constant of the new type...
838 Constant *New = ConstantAggregateZero::get(NewTy);
839 assert(New != OldC && "Didn't replace constant??");
840 OldC->uncheckedReplaceAllUsesWith(New);
841 OldC->destroyConstant(); // This constant is now dead, destroy it.
846 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
848 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
850 Constant *ConstantAggregateZero::get(const Type *Ty) {
851 return AggZeroConstants.getOrCreate(Ty, 0);
854 // destroyConstant - Remove the constant from the constant table...
856 void ConstantAggregateZero::destroyConstant() {
857 AggZeroConstants.remove(this);
858 destroyConstantImpl();
861 //---- ConstantArray::get() implementation...
865 struct ConvertConstantType<ConstantArray, ArrayType> {
866 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
867 // Make everyone now use a constant of the new type...
868 std::vector<Constant*> C;
869 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
870 C.push_back(cast<Constant>(OldC->getOperand(i)));
871 Constant *New = ConstantArray::get(NewTy, C);
872 assert(New != OldC && "Didn't replace constant??");
873 OldC->uncheckedReplaceAllUsesWith(New);
874 OldC->destroyConstant(); // This constant is now dead, destroy it.
879 static std::vector<Constant*> getValType(ConstantArray *CA) {
880 std::vector<Constant*> Elements;
881 Elements.reserve(CA->getNumOperands());
882 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
883 Elements.push_back(cast<Constant>(CA->getOperand(i)));
887 typedef ValueMap<std::vector<Constant*>, ArrayType,
888 ConstantArray, true /*largekey*/> ArrayConstantsTy;
889 static ArrayConstantsTy ArrayConstants;
891 Constant *ConstantArray::get(const ArrayType *Ty,
892 const std::vector<Constant*> &V) {
893 // If this is an all-zero array, return a ConstantAggregateZero object
896 if (!C->isNullValue())
897 return ArrayConstants.getOrCreate(Ty, V);
898 for (unsigned i = 1, e = V.size(); i != e; ++i)
900 return ArrayConstants.getOrCreate(Ty, V);
902 return ConstantAggregateZero::get(Ty);
905 // destroyConstant - Remove the constant from the constant table...
907 void ConstantArray::destroyConstant() {
908 ArrayConstants.remove(this);
909 destroyConstantImpl();
912 // ConstantArray::get(const string&) - Return an array that is initialized to
913 // contain the specified string. A null terminator is added to the specified
914 // string so that it may be used in a natural way...
916 Constant *ConstantArray::get(const std::string &Str) {
917 std::vector<Constant*> ElementVals;
919 for (unsigned i = 0; i < Str.length(); ++i)
920 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
922 // Add a null terminator to the string...
923 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
925 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
926 return ConstantArray::get(ATy, ElementVals);
929 /// isString - This method returns true if the array is an array of sbyte or
930 /// ubyte, and if the elements of the array are all ConstantInt's.
931 bool ConstantArray::isString() const {
932 // Check the element type for sbyte or ubyte...
933 if (getType()->getElementType() != Type::UByteTy &&
934 getType()->getElementType() != Type::SByteTy)
936 // Check the elements to make sure they are all integers, not constant
938 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
939 if (!isa<ConstantInt>(getOperand(i)))
944 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
945 // then this method converts the array to an std::string and returns it.
946 // Otherwise, it asserts out.
948 std::string ConstantArray::getAsString() const {
949 assert(isString() && "Not a string!");
951 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
952 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
957 //---- ConstantStruct::get() implementation...
962 struct ConvertConstantType<ConstantStruct, StructType> {
963 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
964 // Make everyone now use a constant of the new type...
965 std::vector<Constant*> C;
966 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
967 C.push_back(cast<Constant>(OldC->getOperand(i)));
968 Constant *New = ConstantStruct::get(NewTy, C);
969 assert(New != OldC && "Didn't replace constant??");
971 OldC->uncheckedReplaceAllUsesWith(New);
972 OldC->destroyConstant(); // This constant is now dead, destroy it.
977 typedef ValueMap<std::vector<Constant*>, StructType,
978 ConstantStruct, true /*largekey*/> StructConstantsTy;
979 static StructConstantsTy StructConstants;
981 static std::vector<Constant*> getValType(ConstantStruct *CS) {
982 std::vector<Constant*> Elements;
983 Elements.reserve(CS->getNumOperands());
984 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
985 Elements.push_back(cast<Constant>(CS->getOperand(i)));
989 Constant *ConstantStruct::get(const StructType *Ty,
990 const std::vector<Constant*> &V) {
991 // Create a ConstantAggregateZero value if all elements are zeros...
992 for (unsigned i = 0, e = V.size(); i != e; ++i)
993 if (!V[i]->isNullValue())
994 return StructConstants.getOrCreate(Ty, V);
996 return ConstantAggregateZero::get(Ty);
999 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1000 std::vector<const Type*> StructEls;
1001 StructEls.reserve(V.size());
1002 for (unsigned i = 0, e = V.size(); i != e; ++i)
1003 StructEls.push_back(V[i]->getType());
1004 return get(StructType::get(StructEls), V);
1007 // destroyConstant - Remove the constant from the constant table...
1009 void ConstantStruct::destroyConstant() {
1010 StructConstants.remove(this);
1011 destroyConstantImpl();
1014 //---- ConstantPacked::get() implementation...
1018 struct ConvertConstantType<ConstantPacked, PackedType> {
1019 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1020 // Make everyone now use a constant of the new type...
1021 std::vector<Constant*> C;
1022 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1023 C.push_back(cast<Constant>(OldC->getOperand(i)));
1024 Constant *New = ConstantPacked::get(NewTy, C);
1025 assert(New != OldC && "Didn't replace constant??");
1026 OldC->uncheckedReplaceAllUsesWith(New);
1027 OldC->destroyConstant(); // This constant is now dead, destroy it.
1032 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1033 std::vector<Constant*> Elements;
1034 Elements.reserve(CP->getNumOperands());
1035 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1036 Elements.push_back(CP->getOperand(i));
1040 static ValueMap<std::vector<Constant*>, PackedType,
1041 ConstantPacked> PackedConstants;
1043 Constant *ConstantPacked::get(const PackedType *Ty,
1044 const std::vector<Constant*> &V) {
1045 // If this is an all-zero packed, return a ConstantAggregateZero object
1048 if (!C->isNullValue())
1049 return PackedConstants.getOrCreate(Ty, V);
1050 for (unsigned i = 1, e = V.size(); i != e; ++i)
1052 return PackedConstants.getOrCreate(Ty, V);
1054 return ConstantAggregateZero::get(Ty);
1057 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1058 assert(!V.empty() && "Cannot infer type if V is empty");
1059 return get(PackedType::get(V.front()->getType(),V.size()), V);
1062 // destroyConstant - Remove the constant from the constant table...
1064 void ConstantPacked::destroyConstant() {
1065 PackedConstants.remove(this);
1066 destroyConstantImpl();
1069 //---- ConstantPointerNull::get() implementation...
1073 // ConstantPointerNull does not take extra "value" argument...
1074 template<class ValType>
1075 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1076 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1077 return new ConstantPointerNull(Ty);
1082 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1083 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1084 // Make everyone now use a constant of the new type...
1085 Constant *New = ConstantPointerNull::get(NewTy);
1086 assert(New != OldC && "Didn't replace constant??");
1087 OldC->uncheckedReplaceAllUsesWith(New);
1088 OldC->destroyConstant(); // This constant is now dead, destroy it.
1093 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1095 static char getValType(ConstantPointerNull *) {
1100 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1101 return NullPtrConstants.getOrCreate(Ty, 0);
1104 // destroyConstant - Remove the constant from the constant table...
1106 void ConstantPointerNull::destroyConstant() {
1107 NullPtrConstants.remove(this);
1108 destroyConstantImpl();
1112 //---- UndefValue::get() implementation...
1116 // UndefValue does not take extra "value" argument...
1117 template<class ValType>
1118 struct ConstantCreator<UndefValue, Type, ValType> {
1119 static UndefValue *create(const Type *Ty, const ValType &V) {
1120 return new UndefValue(Ty);
1125 struct ConvertConstantType<UndefValue, Type> {
1126 static void convert(UndefValue *OldC, const Type *NewTy) {
1127 // Make everyone now use a constant of the new type.
1128 Constant *New = UndefValue::get(NewTy);
1129 assert(New != OldC && "Didn't replace constant??");
1130 OldC->uncheckedReplaceAllUsesWith(New);
1131 OldC->destroyConstant(); // This constant is now dead, destroy it.
1136 static ValueMap<char, Type, UndefValue> UndefValueConstants;
1138 static char getValType(UndefValue *) {
1143 UndefValue *UndefValue::get(const Type *Ty) {
1144 return UndefValueConstants.getOrCreate(Ty, 0);
1147 // destroyConstant - Remove the constant from the constant table.
1149 void UndefValue::destroyConstant() {
1150 UndefValueConstants.remove(this);
1151 destroyConstantImpl();
1157 //---- ConstantExpr::get() implementations...
1159 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1163 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1164 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1165 if (V.first == Instruction::Cast)
1166 return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1167 if ((V.first >= Instruction::BinaryOpsBegin &&
1168 V.first < Instruction::BinaryOpsEnd) ||
1169 V.first == Instruction::Shl || V.first == Instruction::Shr)
1170 return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1171 if (V.first == Instruction::Select)
1172 return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1173 if (V.first == Instruction::ExtractElement)
1174 return new ExtractElementConstantExpr(V.second[0], V.second[1]);
1175 if (V.first == Instruction::InsertElement)
1176 return new InsertElementConstantExpr(V.second[0], V.second[1],
1179 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1181 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1182 return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1187 struct ConvertConstantType<ConstantExpr, Type> {
1188 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1190 switch (OldC->getOpcode()) {
1191 case Instruction::Cast:
1192 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1194 case Instruction::Select:
1195 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1196 OldC->getOperand(1),
1197 OldC->getOperand(2));
1199 case Instruction::Shl:
1200 case Instruction::Shr:
1201 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1202 OldC->getOperand(0), OldC->getOperand(1));
1205 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1206 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1207 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1208 OldC->getOperand(1));
1210 case Instruction::GetElementPtr:
1211 // Make everyone now use a constant of the new type...
1212 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1213 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1217 assert(New != OldC && "Didn't replace constant??");
1218 OldC->uncheckedReplaceAllUsesWith(New);
1219 OldC->destroyConstant(); // This constant is now dead, destroy it.
1222 } // end namespace llvm
1225 static ExprMapKeyType getValType(ConstantExpr *CE) {
1226 std::vector<Constant*> Operands;
1227 Operands.reserve(CE->getNumOperands());
1228 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1229 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1230 return ExprMapKeyType(CE->getOpcode(), Operands);
1233 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1235 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1236 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1238 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1239 return FC; // Fold a few common cases...
1241 // Look up the constant in the table first to ensure uniqueness
1242 std::vector<Constant*> argVec(1, C);
1243 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1244 return ExprConstants.getOrCreate(Ty, Key);
1247 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1248 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1249 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1250 "This is an illegal sign extension!");
1251 if (C->getType() != Type::BoolTy) {
1252 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1253 return ConstantExpr::getCast(C, Ty);
1255 if (C == ConstantBool::True)
1256 return ConstantIntegral::getAllOnesValue(Ty);
1258 return ConstantIntegral::getNullValue(Ty);
1262 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1263 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1264 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1265 "This is an illegal zero extension!");
1266 if (C->getType() != Type::BoolTy)
1267 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1268 return ConstantExpr::getCast(C, Ty);
1271 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1272 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1274 getGetElementPtr(getNullValue(PointerType::get(Ty)),
1275 std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1279 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1280 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1281 static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1283 return ConstantExpr::getGetElementPtr(C, Indices);
1286 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1287 Constant *C1, Constant *C2) {
1288 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1289 return getShiftTy(ReqTy, Opcode, C1, C2);
1290 // Check the operands for consistency first
1291 assert((Opcode >= Instruction::BinaryOpsBegin &&
1292 Opcode < Instruction::BinaryOpsEnd) &&
1293 "Invalid opcode in binary constant expression");
1294 assert(C1->getType() == C2->getType() &&
1295 "Operand types in binary constant expression should match");
1297 if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1298 ReqTy == Type::BoolTy))
1299 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1300 return FC; // Fold a few common cases...
1302 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1303 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1304 return ExprConstants.getOrCreate(ReqTy, Key);
1307 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1310 case Instruction::Add: case Instruction::Sub:
1311 case Instruction::Mul: case Instruction::Div:
1312 case Instruction::Rem:
1313 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1314 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1315 isa<PackedType>(C1->getType())) &&
1316 "Tried to create an arithmetic operation on a non-arithmetic type!");
1318 case Instruction::And:
1319 case Instruction::Or:
1320 case Instruction::Xor:
1321 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1322 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1323 "Tried to create a logical operation on a non-integral type!");
1325 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1326 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1327 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1329 case Instruction::Shl:
1330 case Instruction::Shr:
1331 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1332 assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
1333 "Tried to create a shift operation on a non-integer type!");
1340 if (Instruction::isRelational(Opcode))
1341 return getTy(Type::BoolTy, Opcode, C1, C2);
1343 return getTy(C1->getType(), Opcode, C1, C2);
1346 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1347 Constant *V1, Constant *V2) {
1348 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1349 assert(V1->getType() == V2->getType() && "Select value types must match!");
1350 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1352 if (ReqTy == V1->getType())
1353 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1354 return SC; // Fold common cases
1356 std::vector<Constant*> argVec(3, C);
1359 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1360 return ExprConstants.getOrCreate(ReqTy, Key);
1363 /// getShiftTy - Return a shift left or shift right constant expr
1364 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1365 Constant *C1, Constant *C2) {
1366 // Check the operands for consistency first
1367 assert((Opcode == Instruction::Shl ||
1368 Opcode == Instruction::Shr) &&
1369 "Invalid opcode in binary constant expression");
1370 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1371 "Invalid operand types for Shift constant expr!");
1373 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1374 return FC; // Fold a few common cases...
1376 // Look up the constant in the table first to ensure uniqueness
1377 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1378 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1379 return ExprConstants.getOrCreate(ReqTy, Key);
1383 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1384 const std::vector<Value*> &IdxList) {
1385 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1386 "GEP indices invalid!");
1388 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1389 return FC; // Fold a few common cases...
1391 assert(isa<PointerType>(C->getType()) &&
1392 "Non-pointer type for constant GetElementPtr expression");
1393 // Look up the constant in the table first to ensure uniqueness
1394 std::vector<Constant*> ArgVec;
1395 ArgVec.reserve(IdxList.size()+1);
1396 ArgVec.push_back(C);
1397 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1398 ArgVec.push_back(cast<Constant>(IdxList[i]));
1399 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1400 return ExprConstants.getOrCreate(ReqTy, Key);
1403 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1404 const std::vector<Constant*> &IdxList){
1405 // Get the result type of the getelementptr!
1406 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1408 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1410 assert(Ty && "GEP indices invalid!");
1411 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1414 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1415 const std::vector<Value*> &IdxList) {
1416 // Get the result type of the getelementptr!
1417 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1419 assert(Ty && "GEP indices invalid!");
1420 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1423 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1425 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1426 return FC; // Fold a few common cases...
1427 // Look up the constant in the table first to ensure uniqueness
1428 std::vector<Constant*> ArgVec(1, Val);
1429 ArgVec.push_back(Idx);
1430 const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
1431 return ExprConstants.getOrCreate(ReqTy, Key);
1434 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1435 assert(isa<PackedType>(Val->getType()) &&
1436 "Tried to create extractelement operation on non-packed type!");
1437 assert(Idx->getType() == Type::UIntTy &&
1438 "Extractelement index must be uint type!");
1439 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1443 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1444 Constant *Elt, Constant *Idx) {
1445 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1446 return FC; // Fold a few common cases...
1447 // Look up the constant in the table first to ensure uniqueness
1448 std::vector<Constant*> ArgVec(1, Val);
1449 ArgVec.push_back(Elt);
1450 ArgVec.push_back(Idx);
1451 const ExprMapKeyType &Key = std::make_pair(Instruction::InsertElement,ArgVec);
1452 return ExprConstants.getOrCreate(ReqTy, Key);
1455 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1457 assert(isa<PackedType>(Val->getType()) &&
1458 "Tried to create insertelement operation on non-packed type!");
1459 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1460 && "Insertelement types must match!");
1461 assert(Idx->getType() == Type::UIntTy &&
1462 "Insertelement index must be uint type!");
1463 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1467 // destroyConstant - Remove the constant from the constant table...
1469 void ConstantExpr::destroyConstant() {
1470 ExprConstants.remove(this);
1471 destroyConstantImpl();
1474 const char *ConstantExpr::getOpcodeName() const {
1475 return Instruction::getOpcodeName(getOpcode());
1478 //===----------------------------------------------------------------------===//
1479 // replaceUsesOfWithOnConstant implementations
1481 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1483 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1484 Constant *ToC = cast<Constant>(To);
1486 unsigned OperandToUpdate = U-OperandList;
1487 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1489 std::pair<ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1490 Lookup.first.first = getType();
1491 Lookup.second = this;
1493 std::vector<Constant*> &Values = Lookup.first.second;
1494 Values.reserve(getNumOperands()); // Build replacement array.
1496 // Fill values with the modified operands of the constant array. Also,
1497 // compute whether this turns into an all-zeros array.
1498 bool isAllZeros = false;
1499 if (!ToC->isNullValue()) {
1500 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1501 Values.push_back(cast<Constant>(O->get()));
1504 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1505 Constant *Val = cast<Constant>(O->get());
1506 Values.push_back(Val);
1507 if (isAllZeros) isAllZeros = Val->isNullValue();
1510 Values[OperandToUpdate] = ToC;
1512 Constant *Replacement = 0;
1514 Replacement = ConstantAggregateZero::get(getType());
1516 // Check to see if we have this array type already.
1518 ArrayConstantsTy::MapIterator I =
1519 ArrayConstants.InsertOrGetItem(Lookup, Exists);
1522 Replacement = I->second;
1524 // Okay, the new shape doesn't exist in the system yet. Instead of
1525 // creating a new constant array, inserting it, replaceallusesof'ing the
1526 // old with the new, then deleting the old... just update the current one
1528 ArrayConstants.MoveConstantToNewSlot(this, I);
1530 // Update to the new value.
1531 setOperand(OperandToUpdate, ToC);
1536 // Otherwise, I do need to replace this with an existing value.
1537 assert(Replacement != this && "I didn't contain From!");
1539 // Everyone using this now uses the replacement.
1540 uncheckedReplaceAllUsesWith(Replacement);
1542 // Delete the old constant!
1546 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1548 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1549 Constant *ToC = cast<Constant>(To);
1551 unsigned OperandToUpdate = U-OperandList;
1552 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1554 std::pair<StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1555 Lookup.first.first = getType();
1556 Lookup.second = this;
1557 std::vector<Constant*> &Values = Lookup.first.second;
1558 Values.reserve(getNumOperands()); // Build replacement struct.
1561 // Fill values with the modified operands of the constant struct. Also,
1562 // compute whether this turns into an all-zeros struct.
1563 bool isAllZeros = false;
1564 if (!ToC->isNullValue()) {
1565 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1566 Values.push_back(cast<Constant>(O->get()));
1569 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1570 Constant *Val = cast<Constant>(O->get());
1571 Values.push_back(Val);
1572 if (isAllZeros) isAllZeros = Val->isNullValue();
1575 Values[OperandToUpdate] = ToC;
1577 Constant *Replacement = 0;
1579 Replacement = ConstantAggregateZero::get(getType());
1581 // Check to see if we have this array type already.
1583 StructConstantsTy::MapIterator I =
1584 StructConstants.InsertOrGetItem(Lookup, Exists);
1587 Replacement = I->second;
1589 // Okay, the new shape doesn't exist in the system yet. Instead of
1590 // creating a new constant struct, inserting it, replaceallusesof'ing the
1591 // old with the new, then deleting the old... just update the current one
1593 StructConstants.MoveConstantToNewSlot(this, I);
1595 // Update to the new value.
1596 setOperand(OperandToUpdate, ToC);
1601 assert(Replacement != this && "I didn't contain From!");
1603 // Everyone using this now uses the replacement.
1604 uncheckedReplaceAllUsesWith(Replacement);
1606 // Delete the old constant!
1610 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1612 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1614 std::vector<Constant*> Values;
1615 Values.reserve(getNumOperands()); // Build replacement array...
1616 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1617 Constant *Val = getOperand(i);
1618 if (Val == From) Val = cast<Constant>(To);
1619 Values.push_back(Val);
1622 Constant *Replacement = ConstantPacked::get(getType(), Values);
1623 assert(Replacement != this && "I didn't contain From!");
1625 // Everyone using this now uses the replacement.
1626 uncheckedReplaceAllUsesWith(Replacement);
1628 // Delete the old constant!
1632 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1634 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1635 Constant *To = cast<Constant>(ToV);
1637 Constant *Replacement = 0;
1638 if (getOpcode() == Instruction::GetElementPtr) {
1639 std::vector<Constant*> Indices;
1640 Constant *Pointer = getOperand(0);
1641 Indices.reserve(getNumOperands()-1);
1642 if (Pointer == From) Pointer = To;
1644 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1645 Constant *Val = getOperand(i);
1646 if (Val == From) Val = To;
1647 Indices.push_back(Val);
1649 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1650 } else if (getOpcode() == Instruction::Cast) {
1651 assert(getOperand(0) == From && "Cast only has one use!");
1652 Replacement = ConstantExpr::getCast(To, getType());
1653 } else if (getOpcode() == Instruction::Select) {
1654 Constant *C1 = getOperand(0);
1655 Constant *C2 = getOperand(1);
1656 Constant *C3 = getOperand(2);
1657 if (C1 == From) C1 = To;
1658 if (C2 == From) C2 = To;
1659 if (C3 == From) C3 = To;
1660 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1661 } else if (getOpcode() == Instruction::ExtractElement) {
1662 Constant *C1 = getOperand(0);
1663 Constant *C2 = getOperand(1);
1664 if (C1 == From) C1 = To;
1665 if (C2 == From) C2 = To;
1666 Replacement = ConstantExpr::getExtractElement(C1, C2);
1667 } else if (getNumOperands() == 2) {
1668 Constant *C1 = getOperand(0);
1669 Constant *C2 = getOperand(1);
1670 if (C1 == From) C1 = To;
1671 if (C2 == From) C2 = To;
1672 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1674 assert(0 && "Unknown ConstantExpr type!");
1678 assert(Replacement != this && "I didn't contain From!");
1680 // Everyone using this now uses the replacement.
1681 uncheckedReplaceAllUsesWith(Replacement);
1683 // Delete the old constant!
1689 /// clearAllValueMaps - This method frees all internal memory used by the
1690 /// constant subsystem, which can be used in environments where this memory
1691 /// is otherwise reported as a leak.
1692 void Constant::clearAllValueMaps() {
1693 std::vector<Constant *> Constants;
1695 DoubleConstants.clear(Constants);
1696 FloatConstants.clear(Constants);
1697 SIntConstants.clear(Constants);
1698 UIntConstants.clear(Constants);
1699 AggZeroConstants.clear(Constants);
1700 ArrayConstants.clear(Constants);
1701 StructConstants.clear(Constants);
1702 PackedConstants.clear(Constants);
1703 NullPtrConstants.clear(Constants);
1704 UndefValueConstants.clear(Constants);
1705 ExprConstants.clear(Constants);
1707 for (std::vector<Constant *>::iterator I = Constants.begin(),
1708 E = Constants.end(); I != E; ++I)
1709 (*I)->dropAllReferences();
1710 for (std::vector<Constant *>::iterator I = Constants.begin(),
1711 E = Constants.end(); I != E; ++I)
1712 (*I)->destroyConstantImpl();