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((E->getType() == T->getElementType() ||
256 E->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((E->getType() == T->getElementType(I-V.begin()) ||
276 ((T->getElementType(I-V.begin())->isAbstract() ||
277 E->getType()->isAbstract()) &&
278 T->getElementType(I-V.begin())->getTypeID() ==
279 E->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((E->getType() == T->getElementType() ||
299 E->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 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
351 /// used behind the scenes to implement getelementpr constant exprs.
352 struct GetElementPtrConstantExpr : public ConstantExpr {
353 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
355 : ConstantExpr(DestTy, Instruction::GetElementPtr,
356 new Use[IdxList.size()+1], IdxList.size()+1) {
357 OperandList[0].init(C, this);
358 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
359 OperandList[i+1].init(IdxList[i], this);
361 ~GetElementPtrConstantExpr() {
362 delete [] OperandList;
366 /// ConstantExpr::get* - Return some common constants without having to
367 /// specify the full Instruction::OPCODE identifier.
369 Constant *ConstantExpr::getNeg(Constant *C) {
370 if (!C->getType()->isFloatingPoint())
371 return get(Instruction::Sub, getNullValue(C->getType()), C);
373 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
375 Constant *ConstantExpr::getNot(Constant *C) {
376 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
377 return get(Instruction::Xor, C,
378 ConstantIntegral::getAllOnesValue(C->getType()));
380 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
381 return get(Instruction::Add, C1, C2);
383 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
384 return get(Instruction::Sub, C1, C2);
386 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
387 return get(Instruction::Mul, C1, C2);
389 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
390 return get(Instruction::Div, C1, C2);
392 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
393 return get(Instruction::Rem, C1, C2);
395 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
396 return get(Instruction::And, C1, C2);
398 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
399 return get(Instruction::Or, C1, C2);
401 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
402 return get(Instruction::Xor, C1, C2);
404 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
405 return get(Instruction::SetEQ, C1, C2);
407 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
408 return get(Instruction::SetNE, C1, C2);
410 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
411 return get(Instruction::SetLT, C1, C2);
413 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
414 return get(Instruction::SetGT, C1, C2);
416 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
417 return get(Instruction::SetLE, C1, C2);
419 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
420 return get(Instruction::SetGE, C1, C2);
422 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
423 return get(Instruction::Shl, C1, C2);
425 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
426 return get(Instruction::Shr, C1, C2);
429 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
430 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
431 return getCast(getShr(getCast(C1,
432 C1->getType()->getUnsignedVersion()), C2), C1->getType());
435 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
436 if (C1->getType()->isSigned()) return getShr(C1, C2);
437 return getCast(getShr(getCast(C1,
438 C1->getType()->getSignedVersion()), C2), C1->getType());
442 //===----------------------------------------------------------------------===//
443 // isValueValidForType implementations
445 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
446 switch (Ty->getTypeID()) {
448 return false; // These can't be represented as integers!!!
450 case Type::SByteTyID:
451 return (Val <= INT8_MAX && Val >= INT8_MIN);
452 case Type::ShortTyID:
453 return (Val <= INT16_MAX && Val >= INT16_MIN);
455 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
457 return true; // This is the largest type...
461 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
462 switch (Ty->getTypeID()) {
464 return false; // These can't be represented as integers!!!
467 case Type::UByteTyID:
468 return (Val <= UINT8_MAX);
469 case Type::UShortTyID:
470 return (Val <= UINT16_MAX);
472 return (Val <= UINT32_MAX);
473 case Type::ULongTyID:
474 return true; // This is the largest type...
478 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
479 switch (Ty->getTypeID()) {
481 return false; // These can't be represented as floating point!
483 // TODO: Figure out how to test if a double can be cast to a float!
484 case Type::FloatTyID:
485 case Type::DoubleTyID:
486 return true; // This is the largest type...
490 //===----------------------------------------------------------------------===//
491 // Factory Function Implementation
493 // ConstantCreator - A class that is used to create constants by
494 // ValueMap*. This class should be partially specialized if there is
495 // something strange that needs to be done to interface to the ctor for the
499 template<class ConstantClass, class TypeClass, class ValType>
500 struct ConstantCreator {
501 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
502 return new ConstantClass(Ty, V);
506 template<class ConstantClass, class TypeClass>
507 struct ConvertConstantType {
508 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
509 assert(0 && "This type cannot be converted!\n");
516 template<class ValType, class TypeClass, class ConstantClass>
517 class ValueMap : public AbstractTypeUser {
519 typedef std::pair<const TypeClass*, ValType> MapKey;
520 typedef std::map<MapKey, ConstantClass *> MapTy;
521 typedef typename MapTy::iterator MapIterator;
523 /// Map - This is the main map from the element descriptor to the Constants.
524 /// This is the primary way we avoid creating two of the same shape
528 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
529 AbstractTypeMapTy AbstractTypeMap;
531 friend void Constant::clearAllValueMaps();
533 void clear(std::vector<Constant *> &Constants) {
534 for(MapIterator I = Map.begin(); I != Map.end(); ++I)
535 Constants.push_back(I->second);
537 AbstractTypeMap.clear();
541 MapIterator map_end() { return Map.end(); }
543 /// InsertOrGetItem - Return an iterator for the specified element.
544 /// If the element exists in the map, the returned iterator points to the
545 /// entry and Exists=true. If not, the iterator points to the newly
546 /// inserted entry and returns Exists=false. Newly inserted entries have
547 /// I->second == 0, and should be filled in.
548 MapIterator InsertOrGetItem(std::pair<MapKey, ConstantClass *> &InsertVal,
550 std::pair<MapIterator, bool> IP = Map.insert(InsertVal);
555 /// SimpleRemove - This method removes the specified constant from the map,
556 /// without updating type information. This should only be used when we're
557 /// changing an element in the map, making this the second half of a 'move'
559 void SimpleRemove(ConstantClass *CP) {
560 MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
562 if (I == Map.end() || I->second != CP) {
563 // FIXME: This should not use a linear scan. If this gets to be a
564 // performance problem, someone should look at this.
565 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
568 assert(I != Map.end() && "Constant not found in constant table!");
569 assert(I->second == CP && "Didn't find correct element?");
573 /// getOrCreate - Return the specified constant from the map, creating it if
575 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
576 MapKey Lookup(Ty, V);
577 MapIterator I = Map.lower_bound(Lookup);
578 if (I != Map.end() && I->first == Lookup)
579 return I->second; // Is it in the map?
581 // If no preexisting value, create one now...
582 ConstantClass *Result =
583 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
585 /// FIXME: why does this assert fail when loading 176.gcc?
586 //assert(Result->getType() == Ty && "Type specified is not correct!");
587 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
589 // If the type of the constant is abstract, make sure that an entry exists
590 // for it in the AbstractTypeMap.
591 if (Ty->isAbstract()) {
592 typename AbstractTypeMapTy::iterator TI =
593 AbstractTypeMap.lower_bound(Ty);
595 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
596 // Add ourselves to the ATU list of the type.
597 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
599 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
605 void remove(ConstantClass *CP) {
606 MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
608 if (I == Map.end() || I->second != CP) {
609 // FIXME: This should not use a linear scan. If this gets to be a
610 // performance problem, someone should look at this.
611 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
615 assert(I != Map.end() && "Constant not found in constant table!");
616 assert(I->second == CP && "Didn't find correct element?");
618 // Now that we found the entry, make sure this isn't the entry that
619 // the AbstractTypeMap points to.
620 const TypeClass *Ty = I->first.first;
621 if (Ty->isAbstract()) {
622 assert(AbstractTypeMap.count(Ty) &&
623 "Abstract type not in AbstractTypeMap?");
624 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
625 if (ATMEntryIt == I) {
626 // Yes, we are removing the representative entry for this type.
627 // See if there are any other entries of the same type.
628 MapIterator TmpIt = ATMEntryIt;
630 // First check the entry before this one...
631 if (TmpIt != Map.begin()) {
633 if (TmpIt->first.first != Ty) // Not the same type, move back...
637 // If we didn't find the same type, try to move forward...
638 if (TmpIt == ATMEntryIt) {
640 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
641 --TmpIt; // No entry afterwards with the same type
644 // If there is another entry in the map of the same abstract type,
645 // update the AbstractTypeMap entry now.
646 if (TmpIt != ATMEntryIt) {
649 // Otherwise, we are removing the last instance of this type
650 // from the table. Remove from the ATM, and from user list.
651 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
652 AbstractTypeMap.erase(Ty);
660 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
661 typename AbstractTypeMapTy::iterator I =
662 AbstractTypeMap.find(cast<TypeClass>(OldTy));
664 assert(I != AbstractTypeMap.end() &&
665 "Abstract type not in AbstractTypeMap?");
667 // Convert a constant at a time until the last one is gone. The last one
668 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
669 // eliminated eventually.
671 ConvertConstantType<ConstantClass,
672 TypeClass>::convert(I->second->second,
673 cast<TypeClass>(NewTy));
675 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
676 } while (I != AbstractTypeMap.end());
679 // If the type became concrete without being refined to any other existing
680 // type, we just remove ourselves from the ATU list.
681 void typeBecameConcrete(const DerivedType *AbsTy) {
682 AbsTy->removeAbstractTypeUser(this);
686 std::cerr << "Constant.cpp: ValueMap\n";
691 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
693 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
694 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
696 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
697 return SIntConstants.getOrCreate(Ty, V);
700 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
701 return UIntConstants.getOrCreate(Ty, V);
704 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
705 assert(V <= 127 && "Can only be used with very small positive constants!");
706 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
707 return ConstantUInt::get(Ty, V);
710 //---- ConstantFP::get() implementation...
714 struct ConstantCreator<ConstantFP, Type, uint64_t> {
715 static ConstantFP *create(const Type *Ty, uint64_t V) {
716 assert(Ty == Type::DoubleTy);
717 return new ConstantFP(Ty, BitsToDouble(V));
721 struct ConstantCreator<ConstantFP, Type, uint32_t> {
722 static ConstantFP *create(const Type *Ty, uint32_t V) {
723 assert(Ty == Type::FloatTy);
724 return new ConstantFP(Ty, BitsToFloat(V));
729 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
730 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
732 bool ConstantFP::isNullValue() const {
733 return DoubleToBits(Val) == 0;
736 bool ConstantFP::isExactlyValue(double V) const {
737 return DoubleToBits(V) == DoubleToBits(Val);
741 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
742 if (Ty == Type::FloatTy) {
743 // Force the value through memory to normalize it.
744 return FloatConstants.getOrCreate(Ty, FloatToBits(V));
746 assert(Ty == Type::DoubleTy);
747 return DoubleConstants.getOrCreate(Ty, DoubleToBits(V));
751 //---- ConstantAggregateZero::get() implementation...
754 // ConstantAggregateZero does not take extra "value" argument...
755 template<class ValType>
756 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
757 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
758 return new ConstantAggregateZero(Ty);
763 struct ConvertConstantType<ConstantAggregateZero, Type> {
764 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
765 // Make everyone now use a constant of the new type...
766 Constant *New = ConstantAggregateZero::get(NewTy);
767 assert(New != OldC && "Didn't replace constant??");
768 OldC->uncheckedReplaceAllUsesWith(New);
769 OldC->destroyConstant(); // This constant is now dead, destroy it.
774 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
776 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
778 Constant *ConstantAggregateZero::get(const Type *Ty) {
779 return AggZeroConstants.getOrCreate(Ty, 0);
782 // destroyConstant - Remove the constant from the constant table...
784 void ConstantAggregateZero::destroyConstant() {
785 AggZeroConstants.remove(this);
786 destroyConstantImpl();
789 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
790 bool DisableChecking) {
791 assert(0 && "No uses!");
797 //---- ConstantArray::get() implementation...
801 struct ConvertConstantType<ConstantArray, ArrayType> {
802 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
803 // Make everyone now use a constant of the new type...
804 std::vector<Constant*> C;
805 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
806 C.push_back(cast<Constant>(OldC->getOperand(i)));
807 Constant *New = ConstantArray::get(NewTy, C);
808 assert(New != OldC && "Didn't replace constant??");
809 OldC->uncheckedReplaceAllUsesWith(New);
810 OldC->destroyConstant(); // This constant is now dead, destroy it.
815 static std::vector<Constant*> getValType(ConstantArray *CA) {
816 std::vector<Constant*> Elements;
817 Elements.reserve(CA->getNumOperands());
818 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
819 Elements.push_back(cast<Constant>(CA->getOperand(i)));
823 typedef ValueMap<std::vector<Constant*>, ArrayType,
824 ConstantArray> ArrayConstantsTy;
825 static ArrayConstantsTy ArrayConstants;
827 Constant *ConstantArray::get(const ArrayType *Ty,
828 const std::vector<Constant*> &V) {
829 // If this is an all-zero array, return a ConstantAggregateZero object
832 if (!C->isNullValue())
833 return ArrayConstants.getOrCreate(Ty, V);
834 for (unsigned i = 1, e = V.size(); i != e; ++i)
836 return ArrayConstants.getOrCreate(Ty, V);
838 return ConstantAggregateZero::get(Ty);
841 // destroyConstant - Remove the constant from the constant table...
843 void ConstantArray::destroyConstant() {
844 ArrayConstants.remove(this);
845 destroyConstantImpl();
848 // ConstantArray::get(const string&) - Return an array that is initialized to
849 // contain the specified string. A null terminator is added to the specified
850 // string so that it may be used in a natural way...
852 Constant *ConstantArray::get(const std::string &Str) {
853 std::vector<Constant*> ElementVals;
855 for (unsigned i = 0; i < Str.length(); ++i)
856 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
858 // Add a null terminator to the string...
859 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
861 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
862 return ConstantArray::get(ATy, ElementVals);
865 /// isString - This method returns true if the array is an array of sbyte or
866 /// ubyte, and if the elements of the array are all ConstantInt's.
867 bool ConstantArray::isString() const {
868 // Check the element type for sbyte or ubyte...
869 if (getType()->getElementType() != Type::UByteTy &&
870 getType()->getElementType() != Type::SByteTy)
872 // Check the elements to make sure they are all integers, not constant
874 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
875 if (!isa<ConstantInt>(getOperand(i)))
880 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
881 // then this method converts the array to an std::string and returns it.
882 // Otherwise, it asserts out.
884 std::string ConstantArray::getAsString() const {
885 assert(isString() && "Not a string!");
887 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
888 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
893 //---- ConstantStruct::get() implementation...
898 struct ConvertConstantType<ConstantStruct, StructType> {
899 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
900 // Make everyone now use a constant of the new type...
901 std::vector<Constant*> C;
902 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
903 C.push_back(cast<Constant>(OldC->getOperand(i)));
904 Constant *New = ConstantStruct::get(NewTy, C);
905 assert(New != OldC && "Didn't replace constant??");
907 OldC->uncheckedReplaceAllUsesWith(New);
908 OldC->destroyConstant(); // This constant is now dead, destroy it.
913 typedef ValueMap<std::vector<Constant*>, StructType,
914 ConstantStruct> StructConstantsTy;
915 static StructConstantsTy StructConstants;
917 static std::vector<Constant*> getValType(ConstantStruct *CS) {
918 std::vector<Constant*> Elements;
919 Elements.reserve(CS->getNumOperands());
920 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
921 Elements.push_back(cast<Constant>(CS->getOperand(i)));
925 Constant *ConstantStruct::get(const StructType *Ty,
926 const std::vector<Constant*> &V) {
927 // Create a ConstantAggregateZero value if all elements are zeros...
928 for (unsigned i = 0, e = V.size(); i != e; ++i)
929 if (!V[i]->isNullValue())
930 return StructConstants.getOrCreate(Ty, V);
932 return ConstantAggregateZero::get(Ty);
935 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
936 std::vector<const Type*> StructEls;
937 StructEls.reserve(V.size());
938 for (unsigned i = 0, e = V.size(); i != e; ++i)
939 StructEls.push_back(V[i]->getType());
940 return get(StructType::get(StructEls), V);
943 // destroyConstant - Remove the constant from the constant table...
945 void ConstantStruct::destroyConstant() {
946 StructConstants.remove(this);
947 destroyConstantImpl();
950 //---- ConstantPacked::get() implementation...
954 struct ConvertConstantType<ConstantPacked, PackedType> {
955 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
956 // Make everyone now use a constant of the new type...
957 std::vector<Constant*> C;
958 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
959 C.push_back(cast<Constant>(OldC->getOperand(i)));
960 Constant *New = ConstantPacked::get(NewTy, C);
961 assert(New != OldC && "Didn't replace constant??");
962 OldC->uncheckedReplaceAllUsesWith(New);
963 OldC->destroyConstant(); // This constant is now dead, destroy it.
968 static std::vector<Constant*> getValType(ConstantPacked *CP) {
969 std::vector<Constant*> Elements;
970 Elements.reserve(CP->getNumOperands());
971 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
972 Elements.push_back(CP->getOperand(i));
976 static ValueMap<std::vector<Constant*>, PackedType,
977 ConstantPacked> PackedConstants;
979 Constant *ConstantPacked::get(const PackedType *Ty,
980 const std::vector<Constant*> &V) {
981 // If this is an all-zero packed, return a ConstantAggregateZero object
984 if (!C->isNullValue())
985 return PackedConstants.getOrCreate(Ty, V);
986 for (unsigned i = 1, e = V.size(); i != e; ++i)
988 return PackedConstants.getOrCreate(Ty, V);
990 return ConstantAggregateZero::get(Ty);
993 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
994 assert(!V.empty() && "Cannot infer type if V is empty");
995 return get(PackedType::get(V.front()->getType(),V.size()), V);
998 // destroyConstant - Remove the constant from the constant table...
1000 void ConstantPacked::destroyConstant() {
1001 PackedConstants.remove(this);
1002 destroyConstantImpl();
1005 //---- ConstantPointerNull::get() implementation...
1009 // ConstantPointerNull does not take extra "value" argument...
1010 template<class ValType>
1011 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1012 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1013 return new ConstantPointerNull(Ty);
1018 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1019 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1020 // Make everyone now use a constant of the new type...
1021 Constant *New = ConstantPointerNull::get(NewTy);
1022 assert(New != OldC && "Didn't replace constant??");
1023 OldC->uncheckedReplaceAllUsesWith(New);
1024 OldC->destroyConstant(); // This constant is now dead, destroy it.
1029 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1031 static char getValType(ConstantPointerNull *) {
1036 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1037 return NullPtrConstants.getOrCreate(Ty, 0);
1040 // destroyConstant - Remove the constant from the constant table...
1042 void ConstantPointerNull::destroyConstant() {
1043 NullPtrConstants.remove(this);
1044 destroyConstantImpl();
1048 //---- UndefValue::get() implementation...
1052 // UndefValue does not take extra "value" argument...
1053 template<class ValType>
1054 struct ConstantCreator<UndefValue, Type, ValType> {
1055 static UndefValue *create(const Type *Ty, const ValType &V) {
1056 return new UndefValue(Ty);
1061 struct ConvertConstantType<UndefValue, Type> {
1062 static void convert(UndefValue *OldC, const Type *NewTy) {
1063 // Make everyone now use a constant of the new type.
1064 Constant *New = UndefValue::get(NewTy);
1065 assert(New != OldC && "Didn't replace constant??");
1066 OldC->uncheckedReplaceAllUsesWith(New);
1067 OldC->destroyConstant(); // This constant is now dead, destroy it.
1072 static ValueMap<char, Type, UndefValue> UndefValueConstants;
1074 static char getValType(UndefValue *) {
1079 UndefValue *UndefValue::get(const Type *Ty) {
1080 return UndefValueConstants.getOrCreate(Ty, 0);
1083 // destroyConstant - Remove the constant from the constant table.
1085 void UndefValue::destroyConstant() {
1086 UndefValueConstants.remove(this);
1087 destroyConstantImpl();
1093 //---- ConstantExpr::get() implementations...
1095 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1099 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1100 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1101 if (V.first == Instruction::Cast)
1102 return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1103 if ((V.first >= Instruction::BinaryOpsBegin &&
1104 V.first < Instruction::BinaryOpsEnd) ||
1105 V.first == Instruction::Shl || V.first == Instruction::Shr)
1106 return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1107 if (V.first == Instruction::Select)
1108 return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1110 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1112 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1113 return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1118 struct ConvertConstantType<ConstantExpr, Type> {
1119 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1121 switch (OldC->getOpcode()) {
1122 case Instruction::Cast:
1123 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1125 case Instruction::Select:
1126 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1127 OldC->getOperand(1),
1128 OldC->getOperand(2));
1130 case Instruction::Shl:
1131 case Instruction::Shr:
1132 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1133 OldC->getOperand(0), OldC->getOperand(1));
1136 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1137 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1138 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1139 OldC->getOperand(1));
1141 case Instruction::GetElementPtr:
1142 // Make everyone now use a constant of the new type...
1143 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1144 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1148 assert(New != OldC && "Didn't replace constant??");
1149 OldC->uncheckedReplaceAllUsesWith(New);
1150 OldC->destroyConstant(); // This constant is now dead, destroy it.
1153 } // end namespace llvm
1156 static ExprMapKeyType getValType(ConstantExpr *CE) {
1157 std::vector<Constant*> Operands;
1158 Operands.reserve(CE->getNumOperands());
1159 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1160 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1161 return ExprMapKeyType(CE->getOpcode(), Operands);
1164 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1166 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1167 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1169 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1170 return FC; // Fold a few common cases...
1172 // Look up the constant in the table first to ensure uniqueness
1173 std::vector<Constant*> argVec(1, C);
1174 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1175 return ExprConstants.getOrCreate(Ty, Key);
1178 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1179 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1180 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1181 "This is an illegal sign extension!");
1182 if (C->getType() != Type::BoolTy) {
1183 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1184 return ConstantExpr::getCast(C, Ty);
1186 if (C == ConstantBool::True)
1187 return ConstantIntegral::getAllOnesValue(Ty);
1189 return ConstantIntegral::getNullValue(Ty);
1193 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1194 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1195 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1196 "This is an illegal zero extension!");
1197 if (C->getType() != Type::BoolTy)
1198 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1199 return ConstantExpr::getCast(C, Ty);
1202 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1203 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1205 getGetElementPtr(getNullValue(PointerType::get(Ty)),
1206 std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1210 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1211 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1212 static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1214 return ConstantExpr::getGetElementPtr(C, Indices);
1217 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1218 Constant *C1, Constant *C2) {
1219 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1220 return getShiftTy(ReqTy, Opcode, C1, C2);
1221 // Check the operands for consistency first
1222 assert((Opcode >= Instruction::BinaryOpsBegin &&
1223 Opcode < Instruction::BinaryOpsEnd) &&
1224 "Invalid opcode in binary constant expression");
1225 assert(C1->getType() == C2->getType() &&
1226 "Operand types in binary constant expression should match");
1228 if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1229 ReqTy == Type::BoolTy))
1230 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1231 return FC; // Fold a few common cases...
1233 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1234 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1235 return ExprConstants.getOrCreate(ReqTy, Key);
1238 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1241 case Instruction::Add: case Instruction::Sub:
1242 case Instruction::Mul: case Instruction::Div:
1243 case Instruction::Rem:
1244 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1245 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) &&
1246 "Tried to create an arithmetic operation on a non-arithmetic type!");
1248 case Instruction::And:
1249 case Instruction::Or:
1250 case Instruction::Xor:
1251 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1252 assert(C1->getType()->isIntegral() &&
1253 "Tried to create a logical operation on a non-integral type!");
1255 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1256 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1257 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1259 case Instruction::Shl:
1260 case Instruction::Shr:
1261 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1262 assert(C1->getType()->isInteger() &&
1263 "Tried to create a shift operation on a non-integer type!");
1270 if (Instruction::isRelational(Opcode))
1271 return getTy(Type::BoolTy, Opcode, C1, C2);
1273 return getTy(C1->getType(), Opcode, C1, C2);
1276 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1277 Constant *V1, Constant *V2) {
1278 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1279 assert(V1->getType() == V2->getType() && "Select value types must match!");
1280 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1282 if (ReqTy == V1->getType())
1283 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1284 return SC; // Fold common cases
1286 std::vector<Constant*> argVec(3, C);
1289 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1290 return ExprConstants.getOrCreate(ReqTy, Key);
1293 /// getShiftTy - Return a shift left or shift right constant expr
1294 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1295 Constant *C1, Constant *C2) {
1296 // Check the operands for consistency first
1297 assert((Opcode == Instruction::Shl ||
1298 Opcode == Instruction::Shr) &&
1299 "Invalid opcode in binary constant expression");
1300 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1301 "Invalid operand types for Shift constant expr!");
1303 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1304 return FC; // Fold a few common cases...
1306 // Look up the constant in the table first to ensure uniqueness
1307 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1308 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1309 return ExprConstants.getOrCreate(ReqTy, Key);
1313 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1314 const std::vector<Value*> &IdxList) {
1315 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1316 "GEP indices invalid!");
1318 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1319 return FC; // Fold a few common cases...
1321 assert(isa<PointerType>(C->getType()) &&
1322 "Non-pointer type for constant GetElementPtr expression");
1323 // Look up the constant in the table first to ensure uniqueness
1324 std::vector<Constant*> ArgVec;
1325 ArgVec.reserve(IdxList.size()+1);
1326 ArgVec.push_back(C);
1327 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1328 ArgVec.push_back(cast<Constant>(IdxList[i]));
1329 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1330 return ExprConstants.getOrCreate(ReqTy, Key);
1333 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1334 const std::vector<Constant*> &IdxList){
1335 // Get the result type of the getelementptr!
1336 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1338 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1340 assert(Ty && "GEP indices invalid!");
1341 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1344 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1345 const std::vector<Value*> &IdxList) {
1346 // Get the result type of the getelementptr!
1347 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1349 assert(Ty && "GEP indices invalid!");
1350 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1354 // destroyConstant - Remove the constant from the constant table...
1356 void ConstantExpr::destroyConstant() {
1357 ExprConstants.remove(this);
1358 destroyConstantImpl();
1361 const char *ConstantExpr::getOpcodeName() const {
1362 return Instruction::getOpcodeName(getOpcode());
1365 //===----------------------------------------------------------------------===//
1366 // replaceUsesOfWithOnConstant implementations
1368 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1369 bool DisableChecking) {
1370 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1371 Constant *ToC = cast<Constant>(To);
1373 std::pair<ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1374 Lookup.first.first = getType();
1375 Lookup.second = this;
1376 std::vector<Constant*> &Values = Lookup.first.second;
1377 Values.reserve(getNumOperands()); // Build replacement array.
1379 // Fill values with the modified operands of the constant array. Also,
1380 // compute whether this turns into an all-zeros array.
1381 bool isAllZeros = ToC->isNullValue();
1382 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1383 Constant *Val = getOperand(i);
1384 if (Val == From) Val = ToC;
1385 Values.push_back(Val);
1386 if (isAllZeros) isAllZeros = Val->isNullValue();
1389 Constant *Replacement = 0;
1391 Replacement = ConstantAggregateZero::get(getType());
1393 // Check to see if we have this array type already.
1395 ArrayConstantsTy::MapIterator I =
1396 ArrayConstants.InsertOrGetItem(Lookup, Exists);
1399 Replacement = I->second;
1401 // Okay, the new shape doesn't exist in the system yet. Instead of
1402 // creating a new constant array, inserting it, replaceallusesof'ing the
1403 // old with the new, then deleting the old... just update the current one
1405 if (I != ArrayConstants.map_end() && I->second == this)
1406 ++I; // Do not invalidate iterator!
1407 ArrayConstants.SimpleRemove(this); // Remove old shape from the map.
1409 // Update to the new values.
1410 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1411 if (getOperand(i) == From)
1417 // Otherwise, I do need to replace this with an existing value.
1418 assert(Replacement != this && "I didn't contain From!");
1420 // Everyone using this now uses the replacement...
1421 if (DisableChecking)
1422 uncheckedReplaceAllUsesWith(Replacement);
1424 replaceAllUsesWith(Replacement);
1426 // Delete the old constant!
1430 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1431 bool DisableChecking) {
1432 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1433 Constant *ToC = cast<Constant>(To);
1435 std::pair<StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1436 Lookup.first.first = getType();
1437 Lookup.second = this;
1438 std::vector<Constant*> &Values = Lookup.first.second;
1439 Values.reserve(getNumOperands()); // Build replacement struct.
1441 // Fill values with the modified operands of the constant struct. Also,
1442 // compute whether this turns into an all-zeros struct.
1443 bool isAllZeros = ToC->isNullValue();
1444 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1445 Constant *Val = getOperand(i);
1446 if (Val == From) Val = ToC;
1447 Values.push_back(Val);
1448 if (isAllZeros) isAllZeros = Val->isNullValue();
1451 Constant *Replacement = 0;
1453 Replacement = ConstantAggregateZero::get(getType());
1455 // Check to see if we have this array type already.
1457 StructConstantsTy::MapIterator I =
1458 StructConstants.InsertOrGetItem(Lookup, Exists);
1461 Replacement = I->second;
1463 // Okay, the new shape doesn't exist in the system yet. Instead of
1464 // creating a new constant struct, inserting it, replaceallusesof'ing the
1465 // old with the new, then deleting the old... just update the current one
1467 if (I != StructConstants.map_end() && I->second == this)
1468 ++I; // Do not invalidate iterator!
1469 StructConstants.SimpleRemove(this); // Remove old shape from the map.
1471 // Update to the new values.
1472 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1473 if (getOperand(i) == From)
1479 assert(Replacement != this && "I didn't contain From!");
1481 // Everyone using this now uses the replacement...
1482 if (DisableChecking)
1483 uncheckedReplaceAllUsesWith(Replacement);
1485 replaceAllUsesWith(Replacement);
1487 // Delete the old constant!
1491 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1492 bool DisableChecking) {
1493 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1495 std::vector<Constant*> Values;
1496 Values.reserve(getNumOperands()); // Build replacement array...
1497 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1498 Constant *Val = getOperand(i);
1499 if (Val == From) Val = cast<Constant>(To);
1500 Values.push_back(Val);
1503 Constant *Replacement = ConstantPacked::get(getType(), Values);
1504 assert(Replacement != this && "I didn't contain From!");
1506 // Everyone using this now uses the replacement...
1507 if (DisableChecking)
1508 uncheckedReplaceAllUsesWith(Replacement);
1510 replaceAllUsesWith(Replacement);
1512 // Delete the old constant!
1516 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1517 bool DisableChecking) {
1518 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1519 Constant *To = cast<Constant>(ToV);
1521 Constant *Replacement = 0;
1522 if (getOpcode() == Instruction::GetElementPtr) {
1523 std::vector<Constant*> Indices;
1524 Constant *Pointer = getOperand(0);
1525 Indices.reserve(getNumOperands()-1);
1526 if (Pointer == From) Pointer = To;
1528 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1529 Constant *Val = getOperand(i);
1530 if (Val == From) Val = To;
1531 Indices.push_back(Val);
1533 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1534 } else if (getOpcode() == Instruction::Cast) {
1535 assert(getOperand(0) == From && "Cast only has one use!");
1536 Replacement = ConstantExpr::getCast(To, getType());
1537 } else if (getOpcode() == Instruction::Select) {
1538 Constant *C1 = getOperand(0);
1539 Constant *C2 = getOperand(1);
1540 Constant *C3 = getOperand(2);
1541 if (C1 == From) C1 = To;
1542 if (C2 == From) C2 = To;
1543 if (C3 == From) C3 = To;
1544 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1545 } else if (getNumOperands() == 2) {
1546 Constant *C1 = getOperand(0);
1547 Constant *C2 = getOperand(1);
1548 if (C1 == From) C1 = To;
1549 if (C2 == From) C2 = To;
1550 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1552 assert(0 && "Unknown ConstantExpr type!");
1556 assert(Replacement != this && "I didn't contain From!");
1558 // Everyone using this now uses the replacement...
1559 if (DisableChecking)
1560 uncheckedReplaceAllUsesWith(Replacement);
1562 replaceAllUsesWith(Replacement);
1564 // Delete the old constant!
1570 /// clearAllValueMaps - This method frees all internal memory used by the
1571 /// constant subsystem, which can be used in environments where this memory
1572 /// is otherwise reported as a leak.
1573 void Constant::clearAllValueMaps() {
1574 std::vector<Constant *> Constants;
1576 DoubleConstants.clear(Constants);
1577 FloatConstants.clear(Constants);
1578 SIntConstants.clear(Constants);
1579 UIntConstants.clear(Constants);
1580 AggZeroConstants.clear(Constants);
1581 ArrayConstants.clear(Constants);
1582 StructConstants.clear(Constants);
1583 PackedConstants.clear(Constants);
1584 NullPtrConstants.clear(Constants);
1585 UndefValueConstants.clear(Constants);
1586 ExprConstants.clear(Constants);
1588 for (std::vector<Constant *>::iterator I = Constants.begin(),
1589 E = Constants.end(); I != E; ++I)
1590 (*I)->dropAllReferences();
1591 for (std::vector<Constant *>::iterator I = Constants.begin(),
1592 E = Constants.end(); I != E; ++I)
1593 (*I)->destroyConstantImpl();