1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/SymbolTable.h"
19 #include "llvm/Module.h"
20 #include "Support/StringExtras.h"
24 ConstantBool *ConstantBool::True = new ConstantBool(true);
25 ConstantBool *ConstantBool::False = new ConstantBool(false);
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 // Specialize setName to take care of symbol table majik
33 void Constant::setName(const std::string &Name, SymbolTable *ST) {
34 assert(ST && "Type::setName - Must provide symbol table argument!");
36 if (Name.size()) ST->insert(Name, this);
39 void Constant::destroyConstantImpl() {
40 // When a Constant is destroyed, there may be lingering
41 // references to the constant by other constants in the constant pool. These
42 // constants are implicitly dependent on the module that is being deleted,
43 // but they don't know that. Because we only find out when the CPV is
44 // deleted, we must now notify all of our users (that should only be
45 // Constants) that they are, in fact, invalid now and should be deleted.
47 while (!use_empty()) {
48 Value *V = use_back();
49 #ifndef NDEBUG // Only in -g mode...
50 if (!isa<Constant>(V))
51 std::cerr << "While deleting: " << *this
52 << "\n\nUse still stuck around after Def is destroyed: "
55 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
56 Constant *CPV = cast<Constant>(V);
57 CPV->destroyConstant();
59 // The constant should remove itself from our use list...
60 assert((use_empty() || use_back() != V) && "Constant not removed!");
63 // Value has no outstanding references it is safe to delete it now...
67 // Static constructor to create a '0' constant of arbitrary type...
68 Constant *Constant::getNullValue(const Type *Ty) {
69 switch (Ty->getTypeID()) {
70 case Type::BoolTyID: {
71 static Constant *NullBool = ConstantBool::get(false);
74 case Type::SByteTyID: {
75 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
78 case Type::UByteTyID: {
79 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
82 case Type::ShortTyID: {
83 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
86 case Type::UShortTyID: {
87 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
91 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
94 case Type::UIntTyID: {
95 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
98 case Type::LongTyID: {
99 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
102 case Type::ULongTyID: {
103 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
107 case Type::FloatTyID: {
108 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
111 case Type::DoubleTyID: {
112 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
116 case Type::PointerTyID:
117 return ConstantPointerNull::get(cast<PointerType>(Ty));
119 case Type::StructTyID:
120 case Type::ArrayTyID:
121 return ConstantAggregateZero::get(Ty);
123 // Function, Type, Label, or Opaque type?
124 assert(0 && "Cannot create a null constant of that type!");
129 // Static constructor to create the maximum constant of an integral type...
130 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
131 switch (Ty->getTypeID()) {
132 case Type::BoolTyID: return ConstantBool::True;
133 case Type::SByteTyID:
134 case Type::ShortTyID:
136 case Type::LongTyID: {
137 // Calculate 011111111111111...
138 unsigned TypeBits = Ty->getPrimitiveSize()*8;
139 int64_t Val = INT64_MAX; // All ones
140 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
141 return ConstantSInt::get(Ty, Val);
144 case Type::UByteTyID:
145 case Type::UShortTyID:
147 case Type::ULongTyID: return getAllOnesValue(Ty);
153 // Static constructor to create the minimum constant for an integral type...
154 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
155 switch (Ty->getTypeID()) {
156 case Type::BoolTyID: return ConstantBool::False;
157 case Type::SByteTyID:
158 case Type::ShortTyID:
160 case Type::LongTyID: {
161 // Calculate 1111111111000000000000
162 unsigned TypeBits = Ty->getPrimitiveSize()*8;
163 int64_t Val = -1; // All ones
164 Val <<= TypeBits-1; // Shift over to the right spot
165 return ConstantSInt::get(Ty, Val);
168 case Type::UByteTyID:
169 case Type::UShortTyID:
171 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
177 // Static constructor to create an integral constant with all bits set
178 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
179 switch (Ty->getTypeID()) {
180 case Type::BoolTyID: return ConstantBool::True;
181 case Type::SByteTyID:
182 case Type::ShortTyID:
184 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
186 case Type::UByteTyID:
187 case Type::UShortTyID:
189 case Type::ULongTyID: {
190 // Calculate ~0 of the right type...
191 unsigned TypeBits = Ty->getPrimitiveSize()*8;
192 uint64_t Val = ~0ULL; // All ones
193 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
194 return ConstantUInt::get(Ty, Val);
200 bool ConstantUInt::isAllOnesValue() const {
201 unsigned TypeBits = getType()->getPrimitiveSize()*8;
202 uint64_t Val = ~0ULL; // All ones
203 Val >>= 64-TypeBits; // Shift out inappropriate bits
204 return getValue() == Val;
208 //===----------------------------------------------------------------------===//
209 // ConstantXXX Classes
210 //===----------------------------------------------------------------------===//
212 //===----------------------------------------------------------------------===//
213 // Normal Constructors
215 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
219 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
223 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
224 assert(Ty->isInteger() && Ty->isSigned() &&
225 "Illegal type for unsigned integer constant!");
226 assert(isValueValidForType(Ty, V) && "Value too large for type!");
229 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
230 assert(Ty->isInteger() && Ty->isUnsigned() &&
231 "Illegal type for unsigned integer constant!");
232 assert(isValueValidForType(Ty, V) && "Value too large for type!");
235 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
236 assert(isValueValidForType(Ty, V) && "Value too large for type!");
240 ConstantArray::ConstantArray(const ArrayType *T,
241 const std::vector<Constant*> &V) : Constant(T) {
242 Operands.reserve(V.size());
243 for (unsigned i = 0, e = V.size(); i != e; ++i) {
244 assert(V[i]->getType() == T->getElementType() ||
246 V[i]->getType()->getTypeID() == T->getElementType()->getTypeID()));
247 Operands.push_back(Use(V[i], this));
251 ConstantStruct::ConstantStruct(const StructType *T,
252 const std::vector<Constant*> &V) : Constant(T) {
253 assert(V.size() == T->getNumElements() &&
254 "Invalid initializer vector for constant structure");
255 Operands.reserve(V.size());
256 for (unsigned i = 0, e = V.size(); i != e; ++i) {
257 assert((V[i]->getType() == T->getElementType(i) ||
258 ((T->getElementType(i)->isAbstract() ||
259 V[i]->getType()->isAbstract()) &&
260 T->getElementType(i)->getTypeID() == V[i]->getType()->getTypeID())) &&
261 "Initializer for struct element doesn't match struct element type!");
262 Operands.push_back(Use(V[i], this));
266 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
267 : Constant(GV->getType()) {
269 Operands.push_back(Use(GV, this));
272 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
273 : Constant(Ty), iType(Opcode) {
275 Operands.push_back(Use(C, this));
278 // Select instruction creation ctor
279 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
280 : Constant(V1->getType()), iType(Instruction::Select) {
282 Operands.push_back(Use(C, this));
283 Operands.push_back(Use(V1, this));
284 Operands.push_back(Use(V2, this));
288 static bool isSetCC(unsigned Opcode) {
289 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
290 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
291 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
294 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
295 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
297 Operands.push_back(Use(C1, this));
298 Operands.push_back(Use(C2, this));
301 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
303 : Constant(DestTy), iType(Instruction::GetElementPtr) {
304 Operands.reserve(1+IdxList.size());
305 Operands.push_back(Use(C, this));
306 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
307 Operands.push_back(Use(IdxList[i], this));
310 /// ConstantExpr::get* - Return some common constants without having to
311 /// specify the full Instruction::OPCODE identifier.
313 Constant *ConstantExpr::getNeg(Constant *C) {
314 if (!C->getType()->isFloatingPoint())
315 return get(Instruction::Sub, getNullValue(C->getType()), C);
317 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
319 Constant *ConstantExpr::getNot(Constant *C) {
320 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
321 return get(Instruction::Xor, C,
322 ConstantIntegral::getAllOnesValue(C->getType()));
324 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
325 return get(Instruction::Add, C1, C2);
327 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
328 return get(Instruction::Sub, C1, C2);
330 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
331 return get(Instruction::Mul, C1, C2);
333 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
334 return get(Instruction::Div, C1, C2);
336 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
337 return get(Instruction::Rem, C1, C2);
339 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
340 return get(Instruction::And, C1, C2);
342 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
343 return get(Instruction::Or, C1, C2);
345 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
346 return get(Instruction::Xor, C1, C2);
348 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
349 return get(Instruction::SetEQ, C1, C2);
351 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
352 return get(Instruction::SetNE, C1, C2);
354 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
355 return get(Instruction::SetLT, C1, C2);
357 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
358 return get(Instruction::SetGT, C1, C2);
360 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
361 return get(Instruction::SetLE, C1, C2);
363 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
364 return get(Instruction::SetGE, C1, C2);
366 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
367 return get(Instruction::Shl, C1, C2);
369 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
370 return get(Instruction::Shr, C1, C2);
373 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
374 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
375 return getCast(getShr(getCast(C1,
376 C1->getType()->getUnsignedVersion()), C2), C1->getType());
379 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
380 if (C1->getType()->isSigned()) return getShr(C1, C2);
381 return getCast(getShr(getCast(C1,
382 C1->getType()->getSignedVersion()), C2), C1->getType());
386 //===----------------------------------------------------------------------===//
387 // classof implementations
389 bool ConstantIntegral::classof(const Constant *CPV) {
390 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
393 bool ConstantInt::classof(const Constant *CPV) {
394 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
396 bool ConstantSInt::classof(const Constant *CPV) {
397 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
399 bool ConstantUInt::classof(const Constant *CPV) {
400 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
402 bool ConstantFP::classof(const Constant *CPV) {
403 const Type *Ty = CPV->getType();
404 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
405 !isa<ConstantExpr>(CPV));
407 bool ConstantAggregateZero::classof(const Constant *CPV) {
408 return (isa<ArrayType>(CPV->getType()) || isa<StructType>(CPV->getType())) &&
411 bool ConstantArray::classof(const Constant *CPV) {
412 return isa<ArrayType>(CPV->getType()) && !CPV->isNullValue();
414 bool ConstantStruct::classof(const Constant *CPV) {
415 return isa<StructType>(CPV->getType()) && !CPV->isNullValue();
418 bool ConstantPointerNull::classof(const Constant *CPV) {
419 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
420 CPV->getNumOperands() == 0;
423 bool ConstantPointerRef::classof(const Constant *CPV) {
424 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
425 CPV->getNumOperands() == 1;
430 //===----------------------------------------------------------------------===//
431 // isValueValidForType implementations
433 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
434 switch (Ty->getTypeID()) {
436 return false; // These can't be represented as integers!!!
438 case Type::SByteTyID:
439 return (Val <= INT8_MAX && Val >= INT8_MIN);
440 case Type::ShortTyID:
441 return (Val <= INT16_MAX && Val >= INT16_MIN);
443 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
445 return true; // This is the largest type...
449 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
450 switch (Ty->getTypeID()) {
452 return false; // These can't be represented as integers!!!
455 case Type::UByteTyID:
456 return (Val <= UINT8_MAX);
457 case Type::UShortTyID:
458 return (Val <= UINT16_MAX);
460 return (Val <= UINT32_MAX);
461 case Type::ULongTyID:
462 return true; // This is the largest type...
466 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
467 switch (Ty->getTypeID()) {
469 return false; // These can't be represented as floating point!
471 // TODO: Figure out how to test if a double can be cast to a float!
472 case Type::FloatTyID:
473 case Type::DoubleTyID:
474 return true; // This is the largest type...
478 //===----------------------------------------------------------------------===//
479 // replaceUsesOfWithOnConstant implementations
481 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
482 bool DisableChecking) {
483 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
485 std::vector<Constant*> Values;
486 Values.reserve(getValues().size()); // Build replacement array...
487 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
488 Constant *Val = cast<Constant>(getValues()[i]);
489 if (Val == From) Val = cast<Constant>(To);
490 Values.push_back(Val);
493 Constant *Replacement = ConstantArray::get(getType(), Values);
494 assert(Replacement != this && "I didn't contain From!");
496 // Everyone using this now uses the replacement...
498 uncheckedReplaceAllUsesWith(Replacement);
500 replaceAllUsesWith(Replacement);
502 // Delete the old constant!
506 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
507 bool DisableChecking) {
508 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
510 std::vector<Constant*> Values;
511 Values.reserve(getValues().size());
512 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
513 Constant *Val = cast<Constant>(getValues()[i]);
514 if (Val == From) Val = cast<Constant>(To);
515 Values.push_back(Val);
518 Constant *Replacement = ConstantStruct::get(getType(), Values);
519 assert(Replacement != this && "I didn't contain From!");
521 // Everyone using this now uses the replacement...
523 uncheckedReplaceAllUsesWith(Replacement);
525 replaceAllUsesWith(Replacement);
527 // Delete the old constant!
531 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
532 bool DisableChecking) {
533 if (isa<GlobalValue>(To)) {
534 assert(From == getOperand(0) && "Doesn't contain from!");
535 ConstantPointerRef *Replacement =
536 ConstantPointerRef::get(cast<GlobalValue>(To));
538 // Everyone using this now uses the replacement...
540 uncheckedReplaceAllUsesWith(Replacement);
542 replaceAllUsesWith(Replacement);
545 // Just replace ourselves with the To value specified.
547 uncheckedReplaceAllUsesWith(To);
549 replaceAllUsesWith(To);
552 // Delete the old constant!
556 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
557 bool DisableChecking) {
558 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
559 Constant *To = cast<Constant>(ToV);
561 Constant *Replacement = 0;
562 if (getOpcode() == Instruction::GetElementPtr) {
563 std::vector<Constant*> Indices;
564 Constant *Pointer = getOperand(0);
565 Indices.reserve(getNumOperands()-1);
566 if (Pointer == From) Pointer = To;
568 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
569 Constant *Val = getOperand(i);
570 if (Val == From) Val = To;
571 Indices.push_back(Val);
573 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
574 } else if (getOpcode() == Instruction::Cast) {
575 assert(getOperand(0) == From && "Cast only has one use!");
576 Replacement = ConstantExpr::getCast(To, getType());
577 } else if (getOpcode() == Instruction::Select) {
578 Constant *C1 = getOperand(0);
579 Constant *C2 = getOperand(1);
580 Constant *C3 = getOperand(2);
581 if (C1 == From) C1 = To;
582 if (C2 == From) C2 = To;
583 if (C3 == From) C3 = To;
584 Replacement = ConstantExpr::getSelect(C1, C2, C3);
585 } else if (getNumOperands() == 2) {
586 Constant *C1 = getOperand(0);
587 Constant *C2 = getOperand(1);
588 if (C1 == From) C1 = To;
589 if (C2 == From) C2 = To;
590 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
592 assert(0 && "Unknown ConstantExpr type!");
596 assert(Replacement != this && "I didn't contain From!");
598 // Everyone using this now uses the replacement...
600 uncheckedReplaceAllUsesWith(Replacement);
602 replaceAllUsesWith(Replacement);
604 // Delete the old constant!
608 //===----------------------------------------------------------------------===//
609 // Factory Function Implementation
611 // ConstantCreator - A class that is used to create constants by
612 // ValueMap*. This class should be partially specialized if there is
613 // something strange that needs to be done to interface to the ctor for the
617 template<class ConstantClass, class TypeClass, class ValType>
618 struct ConstantCreator {
619 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
620 return new ConstantClass(Ty, V);
624 template<class ConstantClass, class TypeClass>
625 struct ConvertConstantType {
626 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
627 assert(0 && "This type cannot be converted!\n");
634 template<class ValType, class TypeClass, class ConstantClass>
635 class ValueMap : public AbstractTypeUser {
636 typedef std::pair<const TypeClass*, ValType> MapKey;
637 typedef std::map<MapKey, ConstantClass *> MapTy;
638 typedef typename MapTy::iterator MapIterator;
641 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
642 AbstractTypeMapTy AbstractTypeMap;
644 // getOrCreate - Return the specified constant from the map, creating it if
646 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
647 MapKey Lookup(Ty, V);
648 MapIterator I = Map.lower_bound(Lookup);
649 if (I != Map.end() && I->first == Lookup)
650 return I->second; // Is it in the map?
652 // If no preexisting value, create one now...
653 ConstantClass *Result =
654 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
657 /// FIXME: why does this assert fail when loading 176.gcc?
658 //assert(Result->getType() == Ty && "Type specified is not correct!");
659 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
661 // If the type of the constant is abstract, make sure that an entry exists
662 // for it in the AbstractTypeMap.
663 if (Ty->isAbstract()) {
664 typename AbstractTypeMapTy::iterator TI =
665 AbstractTypeMap.lower_bound(Ty);
667 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
668 // Add ourselves to the ATU list of the type.
669 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
671 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
677 void remove(ConstantClass *CP) {
678 // FIXME: This should not use a linear scan. If this gets to be a
679 // performance problem, someone should look at this.
680 MapIterator I = Map.begin();
681 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
684 assert(I != Map.end() && "Constant not found in constant table!");
686 // Now that we found the entry, make sure this isn't the entry that
687 // the AbstractTypeMap points to.
688 const TypeClass *Ty = I->first.first;
689 if (Ty->isAbstract()) {
690 assert(AbstractTypeMap.count(Ty) &&
691 "Abstract type not in AbstractTypeMap?");
692 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
693 if (ATMEntryIt == I) {
694 // Yes, we are removing the representative entry for this type.
695 // See if there are any other entries of the same type.
696 MapIterator TmpIt = ATMEntryIt;
698 // First check the entry before this one...
699 if (TmpIt != Map.begin()) {
701 if (TmpIt->first.first != Ty) // Not the same type, move back...
705 // If we didn't find the same type, try to move forward...
706 if (TmpIt == ATMEntryIt) {
708 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
709 --TmpIt; // No entry afterwards with the same type
712 // If there is another entry in the map of the same abstract type,
713 // update the AbstractTypeMap entry now.
714 if (TmpIt != ATMEntryIt) {
717 // Otherwise, we are removing the last instance of this type
718 // from the table. Remove from the ATM, and from user list.
719 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
720 AbstractTypeMap.erase(Ty);
728 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
729 typename AbstractTypeMapTy::iterator I =
730 AbstractTypeMap.find(cast<TypeClass>(OldTy));
732 assert(I != AbstractTypeMap.end() &&
733 "Abstract type not in AbstractTypeMap?");
735 // Convert a constant at a time until the last one is gone. The last one
736 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
737 // eliminated eventually.
739 ConvertConstantType<ConstantClass,
740 TypeClass>::convert(I->second->second,
741 cast<TypeClass>(NewTy));
743 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
744 } while (I != AbstractTypeMap.end());
747 // If the type became concrete without being refined to any other existing
748 // type, we just remove ourselves from the ATU list.
749 void typeBecameConcrete(const DerivedType *AbsTy) {
750 AbsTy->removeAbstractTypeUser(this);
754 std::cerr << "Constant.cpp: ValueMap\n";
761 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
763 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
764 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
766 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
767 return SIntConstants.getOrCreate(Ty, V);
770 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
771 return UIntConstants.getOrCreate(Ty, V);
774 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
775 assert(V <= 127 && "Can only be used with very small positive constants!");
776 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
777 return ConstantUInt::get(Ty, V);
780 //---- ConstantFP::get() implementation...
784 struct ConstantCreator<ConstantFP, Type, uint64_t> {
785 static ConstantFP *create(const Type *Ty, uint64_t V) {
786 assert(Ty == Type::DoubleTy);
792 return new ConstantFP(Ty, T.F);
796 struct ConstantCreator<ConstantFP, Type, uint32_t> {
797 static ConstantFP *create(const Type *Ty, uint32_t V) {
798 assert(Ty == Type::FloatTy);
804 return new ConstantFP(Ty, T.F);
809 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
810 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
812 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
813 if (Ty == Type::FloatTy) {
814 // Force the value through memory to normalize it.
820 return FloatConstants.getOrCreate(Ty, T.I);
822 assert(Ty == Type::DoubleTy);
828 return DoubleConstants.getOrCreate(Ty, T.I);
832 //---- ConstantAggregateZero::get() implementation...
835 // ConstantAggregateZero does not take extra "value" argument...
836 template<class ValType>
837 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
838 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
839 return new ConstantAggregateZero(Ty);
844 struct ConvertConstantType<ConstantAggregateZero, Type> {
845 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
846 // Make everyone now use a constant of the new type...
847 Constant *New = ConstantAggregateZero::get(NewTy);
848 assert(New != OldC && "Didn't replace constant??");
849 OldC->uncheckedReplaceAllUsesWith(New);
850 OldC->destroyConstant(); // This constant is now dead, destroy it.
855 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
857 Constant *ConstantAggregateZero::get(const Type *Ty) {
858 return AggZeroConstants.getOrCreate(Ty, 0);
861 // destroyConstant - Remove the constant from the constant table...
863 void ConstantAggregateZero::destroyConstant() {
864 AggZeroConstants.remove(this);
865 destroyConstantImpl();
868 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
869 bool DisableChecking) {
870 assert(0 && "No uses!");
876 //---- ConstantArray::get() implementation...
880 struct ConvertConstantType<ConstantArray, ArrayType> {
881 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
882 // Make everyone now use a constant of the new type...
883 std::vector<Constant*> C;
884 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
885 C.push_back(cast<Constant>(OldC->getOperand(i)));
886 Constant *New = ConstantArray::get(NewTy, C);
887 assert(New != OldC && "Didn't replace constant??");
888 OldC->uncheckedReplaceAllUsesWith(New);
889 OldC->destroyConstant(); // This constant is now dead, destroy it.
894 static ValueMap<std::vector<Constant*>, ArrayType,
895 ConstantArray> ArrayConstants;
897 Constant *ConstantArray::get(const ArrayType *Ty,
898 const std::vector<Constant*> &V) {
899 // If this is an all-zero array, return a ConstantAggregateZero object
902 if (!C->isNullValue())
903 return ArrayConstants.getOrCreate(Ty, V);
904 for (unsigned i = 1, e = V.size(); i != e; ++i)
906 return ArrayConstants.getOrCreate(Ty, V);
908 return ConstantAggregateZero::get(Ty);
911 // destroyConstant - Remove the constant from the constant table...
913 void ConstantArray::destroyConstant() {
914 ArrayConstants.remove(this);
915 destroyConstantImpl();
918 // ConstantArray::get(const string&) - Return an array that is initialized to
919 // contain the specified string. A null terminator is added to the specified
920 // string so that it may be used in a natural way...
922 Constant *ConstantArray::get(const std::string &Str) {
923 std::vector<Constant*> ElementVals;
925 for (unsigned i = 0; i < Str.length(); ++i)
926 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
928 // Add a null terminator to the string...
929 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
931 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
932 return ConstantArray::get(ATy, ElementVals);
935 /// isString - This method returns true if the array is an array of sbyte or
936 /// ubyte, and if the elements of the array are all ConstantInt's.
937 bool ConstantArray::isString() const {
938 // Check the element type for sbyte or ubyte...
939 if (getType()->getElementType() != Type::UByteTy &&
940 getType()->getElementType() != Type::SByteTy)
942 // Check the elements to make sure they are all integers, not constant
944 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
945 if (!isa<ConstantInt>(getOperand(i)))
950 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
951 // then this method converts the array to an std::string and returns it.
952 // Otherwise, it asserts out.
954 std::string ConstantArray::getAsString() const {
955 assert(isString() && "Not a string!");
957 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
958 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
963 //---- ConstantStruct::get() implementation...
968 struct ConvertConstantType<ConstantStruct, StructType> {
969 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
970 // Make everyone now use a constant of the new type...
971 std::vector<Constant*> C;
972 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
973 C.push_back(cast<Constant>(OldC->getOperand(i)));
974 Constant *New = ConstantStruct::get(NewTy, C);
975 assert(New != OldC && "Didn't replace constant??");
977 OldC->uncheckedReplaceAllUsesWith(New);
978 OldC->destroyConstant(); // This constant is now dead, destroy it.
983 static ValueMap<std::vector<Constant*>, StructType,
984 ConstantStruct> StructConstants;
986 Constant *ConstantStruct::get(const StructType *Ty,
987 const std::vector<Constant*> &V) {
988 // Create a ConstantAggregateZero value if all elements are zeros...
989 for (unsigned i = 0, e = V.size(); i != e; ++i)
990 if (!V[i]->isNullValue())
991 return StructConstants.getOrCreate(Ty, V);
993 return ConstantAggregateZero::get(Ty);
996 // destroyConstant - Remove the constant from the constant table...
998 void ConstantStruct::destroyConstant() {
999 StructConstants.remove(this);
1000 destroyConstantImpl();
1003 //---- ConstantPointerNull::get() implementation...
1007 // ConstantPointerNull does not take extra "value" argument...
1008 template<class ValType>
1009 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1010 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1011 return new ConstantPointerNull(Ty);
1016 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1017 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1018 // Make everyone now use a constant of the new type...
1019 Constant *New = ConstantPointerNull::get(NewTy);
1020 assert(New != OldC && "Didn't replace constant??");
1021 OldC->uncheckedReplaceAllUsesWith(New);
1022 OldC->destroyConstant(); // This constant is now dead, destroy it.
1027 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1029 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1030 return NullPtrConstants.getOrCreate(Ty, 0);
1033 // destroyConstant - Remove the constant from the constant table...
1035 void ConstantPointerNull::destroyConstant() {
1036 NullPtrConstants.remove(this);
1037 destroyConstantImpl();
1041 //---- ConstantPointerRef::get() implementation...
1043 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
1044 assert(GV->getParent() && "Global Value must be attached to a module!");
1046 // The Module handles the pointer reference sharing...
1047 return GV->getParent()->getConstantPointerRef(GV);
1050 // destroyConstant - Remove the constant from the constant table...
1052 void ConstantPointerRef::destroyConstant() {
1053 getValue()->getParent()->destroyConstantPointerRef(this);
1054 destroyConstantImpl();
1058 //---- ConstantExpr::get() implementations...
1060 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1064 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1065 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1066 if (V.first == Instruction::Cast)
1067 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
1068 if ((V.first >= Instruction::BinaryOpsBegin &&
1069 V.first < Instruction::BinaryOpsEnd) ||
1070 V.first == Instruction::Shl || V.first == Instruction::Shr)
1071 return new ConstantExpr(V.first, V.second[0], V.second[1]);
1072 if (V.first == Instruction::Select)
1073 return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
1075 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1077 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1078 return new ConstantExpr(V.second[0], IdxList, Ty);
1083 struct ConvertConstantType<ConstantExpr, Type> {
1084 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1086 switch (OldC->getOpcode()) {
1087 case Instruction::Cast:
1088 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1090 case Instruction::Select:
1091 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1092 OldC->getOperand(1),
1093 OldC->getOperand(2));
1095 case Instruction::Shl:
1096 case Instruction::Shr:
1097 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1098 OldC->getOperand(0), OldC->getOperand(1));
1101 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1102 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1103 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1104 OldC->getOperand(1));
1106 case Instruction::GetElementPtr:
1107 // Make everyone now use a constant of the new type...
1108 std::vector<Constant*> C;
1109 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1110 C.push_back(cast<Constant>(OldC->getOperand(i)));
1111 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1115 assert(New != OldC && "Didn't replace constant??");
1116 OldC->uncheckedReplaceAllUsesWith(New);
1117 OldC->destroyConstant(); // This constant is now dead, destroy it.
1120 } // end namespace llvm
1123 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1125 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1126 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1128 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1129 return FC; // Fold a few common cases...
1131 // Look up the constant in the table first to ensure uniqueness
1132 std::vector<Constant*> argVec(1, C);
1133 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1134 return ExprConstants.getOrCreate(Ty, Key);
1137 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1138 assert(C->getType()->isInteger() && Ty->isInteger() &&
1139 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1140 "This is an illegal sign extension!");
1141 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1142 return ConstantExpr::getCast(C, Ty);
1145 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1146 assert(C->getType()->isInteger() && Ty->isInteger() &&
1147 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1148 "This is an illegal zero extension!");
1149 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1150 return ConstantExpr::getCast(C, Ty);
1153 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1154 Constant *C1, Constant *C2) {
1155 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1156 return getShiftTy(ReqTy, Opcode, C1, C2);
1157 // Check the operands for consistency first
1158 assert((Opcode >= Instruction::BinaryOpsBegin &&
1159 Opcode < Instruction::BinaryOpsEnd) &&
1160 "Invalid opcode in binary constant expression");
1161 assert(C1->getType() == C2->getType() &&
1162 "Operand types in binary constant expression should match");
1164 if (ReqTy == C1->getType())
1165 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1166 return FC; // Fold a few common cases...
1168 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1169 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1170 return ExprConstants.getOrCreate(ReqTy, Key);
1173 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1174 Constant *V1, Constant *V2) {
1175 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1176 assert(V1->getType() == V2->getType() && "Select value types must match!");
1177 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1179 if (ReqTy == V1->getType())
1180 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1181 return SC; // Fold common cases
1183 std::vector<Constant*> argVec(3, C);
1186 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1187 return ExprConstants.getOrCreate(ReqTy, Key);
1190 /// getShiftTy - Return a shift left or shift right constant expr
1191 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1192 Constant *C1, Constant *C2) {
1193 // Check the operands for consistency first
1194 assert((Opcode == Instruction::Shl ||
1195 Opcode == Instruction::Shr) &&
1196 "Invalid opcode in binary constant expression");
1197 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1198 "Invalid operand types for Shift constant expr!");
1200 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1201 return FC; // Fold a few common cases...
1203 // Look up the constant in the table first to ensure uniqueness
1204 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1205 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1206 return ExprConstants.getOrCreate(ReqTy, Key);
1210 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1211 const std::vector<Constant*> &IdxList) {
1212 assert(GetElementPtrInst::getIndexedType(C->getType(),
1213 std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1214 "GEP indices invalid!");
1216 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1217 return FC; // Fold a few common cases...
1219 assert(isa<PointerType>(C->getType()) &&
1220 "Non-pointer type for constant GetElementPtr expression");
1221 // Look up the constant in the table first to ensure uniqueness
1222 std::vector<Constant*> argVec(1, C);
1223 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1224 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1225 return ExprConstants.getOrCreate(ReqTy, Key);
1228 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1229 const std::vector<Constant*> &IdxList){
1230 // Get the result type of the getelementptr!
1231 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1233 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1235 assert(Ty && "GEP indices invalid!");
1236 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1240 // destroyConstant - Remove the constant from the constant table...
1242 void ConstantExpr::destroyConstant() {
1243 ExprConstants.remove(this);
1244 destroyConstantImpl();
1247 const char *ConstantExpr::getOpcodeName() const {
1248 return Instruction::getOpcodeName(getOpcode());