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"
26 ConstantBool *ConstantBool::True = new ConstantBool(true);
27 ConstantBool *ConstantBool::False = new ConstantBool(false);
30 //===----------------------------------------------------------------------===//
32 //===----------------------------------------------------------------------===//
34 // Specialize setName to take care of symbol table majik
35 void Constant::setName(const std::string &Name, SymbolTable *ST) {
36 assert(ST && "Type::setName - Must provide symbol table argument!");
38 if (Name.size()) ST->insert(Name, this);
41 void Constant::destroyConstantImpl() {
42 // When a Constant is destroyed, there may be lingering
43 // references to the constant by other constants in the constant pool. These
44 // constants are implicitly dependent on the module that is being deleted,
45 // but they don't know that. Because we only find out when the CPV is
46 // deleted, we must now notify all of our users (that should only be
47 // Constants) that they are, in fact, invalid now and should be deleted.
49 while (!use_empty()) {
50 Value *V = use_back();
51 #ifndef NDEBUG // Only in -g mode...
52 if (!isa<Constant>(V))
53 std::cerr << "While deleting: " << *this
54 << "\n\nUse still stuck around after Def is destroyed: "
57 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
58 Constant *CV = cast<Constant>(V);
59 CV->destroyConstant();
61 // The constant should remove itself from our use list...
62 assert((use_empty() || use_back() != V) && "Constant not removed!");
65 // Value has no outstanding references it is safe to delete it now...
69 // Static constructor to create a '0' constant of arbitrary type...
70 Constant *Constant::getNullValue(const Type *Ty) {
71 switch (Ty->getTypeID()) {
72 case Type::BoolTyID: {
73 static Constant *NullBool = ConstantBool::get(false);
76 case Type::SByteTyID: {
77 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
80 case Type::UByteTyID: {
81 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
84 case Type::ShortTyID: {
85 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
88 case Type::UShortTyID: {
89 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
93 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
96 case Type::UIntTyID: {
97 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
100 case Type::LongTyID: {
101 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
104 case Type::ULongTyID: {
105 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
109 case Type::FloatTyID: {
110 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
113 case Type::DoubleTyID: {
114 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
118 case Type::PointerTyID:
119 return ConstantPointerNull::get(cast<PointerType>(Ty));
121 case Type::StructTyID:
122 case Type::ArrayTyID:
123 case Type::PackedTyID:
124 return ConstantAggregateZero::get(Ty);
126 // Function, Label, or Opaque type?
127 assert(!"Cannot create a null constant of that type!");
132 // Static constructor to create the maximum constant of an integral type...
133 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
134 switch (Ty->getTypeID()) {
135 case Type::BoolTyID: return ConstantBool::True;
136 case Type::SByteTyID:
137 case Type::ShortTyID:
139 case Type::LongTyID: {
140 // Calculate 011111111111111...
141 unsigned TypeBits = Ty->getPrimitiveSize()*8;
142 int64_t Val = INT64_MAX; // All ones
143 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
144 return ConstantSInt::get(Ty, Val);
147 case Type::UByteTyID:
148 case Type::UShortTyID:
150 case Type::ULongTyID: return getAllOnesValue(Ty);
156 // Static constructor to create the minimum constant for an integral type...
157 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
158 switch (Ty->getTypeID()) {
159 case Type::BoolTyID: return ConstantBool::False;
160 case Type::SByteTyID:
161 case Type::ShortTyID:
163 case Type::LongTyID: {
164 // Calculate 1111111111000000000000
165 unsigned TypeBits = Ty->getPrimitiveSize()*8;
166 int64_t Val = -1; // All ones
167 Val <<= TypeBits-1; // Shift over to the right spot
168 return ConstantSInt::get(Ty, Val);
171 case Type::UByteTyID:
172 case Type::UShortTyID:
174 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
180 // Static constructor to create an integral constant with all bits set
181 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
182 switch (Ty->getTypeID()) {
183 case Type::BoolTyID: return ConstantBool::True;
184 case Type::SByteTyID:
185 case Type::ShortTyID:
187 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
189 case Type::UByteTyID:
190 case Type::UShortTyID:
192 case Type::ULongTyID: {
193 // Calculate ~0 of the right type...
194 unsigned TypeBits = Ty->getPrimitiveSize()*8;
195 uint64_t Val = ~0ULL; // All ones
196 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
197 return ConstantUInt::get(Ty, Val);
203 bool ConstantUInt::isAllOnesValue() const {
204 unsigned TypeBits = getType()->getPrimitiveSize()*8;
205 uint64_t Val = ~0ULL; // All ones
206 Val >>= 64-TypeBits; // Shift out inappropriate bits
207 return getValue() == Val;
211 //===----------------------------------------------------------------------===//
212 // ConstantXXX Classes
213 //===----------------------------------------------------------------------===//
215 //===----------------------------------------------------------------------===//
216 // Normal Constructors
218 ConstantIntegral::ConstantIntegral(const Type *Ty, uint64_t V)
223 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy, V) {
226 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty, V) {
229 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
230 assert(Ty->isInteger() && Ty->isSigned() &&
231 "Illegal type for unsigned integer constant!");
232 assert(isValueValidForType(Ty, V) && "Value too large for type!");
235 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
236 assert(Ty->isInteger() && Ty->isUnsigned() &&
237 "Illegal type for unsigned integer constant!");
238 assert(isValueValidForType(Ty, V) && "Value too large for type!");
241 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
242 assert(isValueValidForType(Ty, V) && "Value too large for type!");
246 ConstantArray::ConstantArray(const ArrayType *T,
247 const std::vector<Constant*> &V) : Constant(T) {
248 Operands.reserve(V.size());
249 for (unsigned i = 0, e = V.size(); i != e; ++i) {
250 assert((V[i]->getType() == T->getElementType() ||
252 V[i]->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
253 "Initializer for array element doesn't match array element type!");
254 Operands.push_back(Use(V[i], this));
258 ConstantStruct::ConstantStruct(const StructType *T,
259 const std::vector<Constant*> &V) : Constant(T) {
260 assert(V.size() == T->getNumElements() &&
261 "Invalid initializer vector for constant structure");
262 Operands.reserve(V.size());
263 for (unsigned i = 0, e = V.size(); i != e; ++i) {
264 assert((V[i]->getType() == T->getElementType(i) ||
265 ((T->getElementType(i)->isAbstract() ||
266 V[i]->getType()->isAbstract()) &&
267 T->getElementType(i)->getTypeID() == V[i]->getType()->getTypeID())) &&
268 "Initializer for struct element doesn't match struct element type!");
269 Operands.push_back(Use(V[i], this));
273 ConstantPacked::ConstantPacked(const PackedType *T,
274 const std::vector<Constant*> &V) : Constant(T) {
275 Operands.reserve(V.size());
276 for (unsigned i = 0, e = V.size(); i != e; ++i) {
277 assert((V[i]->getType() == T->getElementType() ||
279 V[i]->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
280 "Initializer for packed element doesn't match packed element type!");
281 Operands.push_back(Use(V[i], this));
285 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
286 : Constant(Ty, ConstantExprVal), iType(Opcode) {
288 Operands.push_back(Use(C, this));
291 // Select instruction creation ctor
292 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
293 : Constant(V1->getType(), ConstantExprVal), iType(Instruction::Select) {
295 Operands.push_back(Use(C, this));
296 Operands.push_back(Use(V1, this));
297 Operands.push_back(Use(V2, this));
301 static bool isSetCC(unsigned Opcode) {
302 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
303 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
304 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
307 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
308 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType(), ConstantExprVal),
311 Operands.push_back(Use(C1, this));
312 Operands.push_back(Use(C2, this));
315 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
317 : Constant(DestTy, ConstantExprVal), iType(Instruction::GetElementPtr) {
318 Operands.reserve(1+IdxList.size());
319 Operands.push_back(Use(C, this));
320 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
321 Operands.push_back(Use(IdxList[i], this));
324 /// ConstantExpr::get* - Return some common constants without having to
325 /// specify the full Instruction::OPCODE identifier.
327 Constant *ConstantExpr::getNeg(Constant *C) {
328 if (!C->getType()->isFloatingPoint())
329 return get(Instruction::Sub, getNullValue(C->getType()), C);
331 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
333 Constant *ConstantExpr::getNot(Constant *C) {
334 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
335 return get(Instruction::Xor, C,
336 ConstantIntegral::getAllOnesValue(C->getType()));
338 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
339 return get(Instruction::Add, C1, C2);
341 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
342 return get(Instruction::Sub, C1, C2);
344 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
345 return get(Instruction::Mul, C1, C2);
347 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
348 return get(Instruction::Div, C1, C2);
350 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
351 return get(Instruction::Rem, C1, C2);
353 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
354 return get(Instruction::And, C1, C2);
356 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
357 return get(Instruction::Or, C1, C2);
359 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
360 return get(Instruction::Xor, C1, C2);
362 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
363 return get(Instruction::SetEQ, C1, C2);
365 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
366 return get(Instruction::SetNE, C1, C2);
368 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
369 return get(Instruction::SetLT, C1, C2);
371 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
372 return get(Instruction::SetGT, C1, C2);
374 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
375 return get(Instruction::SetLE, C1, C2);
377 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
378 return get(Instruction::SetGE, C1, C2);
380 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
381 return get(Instruction::Shl, C1, C2);
383 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
384 return get(Instruction::Shr, C1, C2);
387 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
388 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
389 return getCast(getShr(getCast(C1,
390 C1->getType()->getUnsignedVersion()), C2), C1->getType());
393 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
394 if (C1->getType()->isSigned()) return getShr(C1, C2);
395 return getCast(getShr(getCast(C1,
396 C1->getType()->getSignedVersion()), C2), C1->getType());
400 //===----------------------------------------------------------------------===//
401 // isValueValidForType implementations
403 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
404 switch (Ty->getTypeID()) {
406 return false; // These can't be represented as integers!!!
408 case Type::SByteTyID:
409 return (Val <= INT8_MAX && Val >= INT8_MIN);
410 case Type::ShortTyID:
411 return (Val <= INT16_MAX && Val >= INT16_MIN);
413 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
415 return true; // This is the largest type...
419 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
420 switch (Ty->getTypeID()) {
422 return false; // These can't be represented as integers!!!
425 case Type::UByteTyID:
426 return (Val <= UINT8_MAX);
427 case Type::UShortTyID:
428 return (Val <= UINT16_MAX);
430 return (Val <= UINT32_MAX);
431 case Type::ULongTyID:
432 return true; // This is the largest type...
436 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
437 switch (Ty->getTypeID()) {
439 return false; // These can't be represented as floating point!
441 // TODO: Figure out how to test if a double can be cast to a float!
442 case Type::FloatTyID:
443 case Type::DoubleTyID:
444 return true; // This is the largest type...
448 //===----------------------------------------------------------------------===//
449 // replaceUsesOfWithOnConstant implementations
451 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
452 bool DisableChecking) {
453 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
455 std::vector<Constant*> Values;
456 Values.reserve(getNumOperands()); // Build replacement array...
457 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
458 Constant *Val = getOperand(i);
459 if (Val == From) Val = cast<Constant>(To);
460 Values.push_back(Val);
463 Constant *Replacement = ConstantArray::get(getType(), Values);
464 assert(Replacement != this && "I didn't contain From!");
466 // Everyone using this now uses the replacement...
468 uncheckedReplaceAllUsesWith(Replacement);
470 replaceAllUsesWith(Replacement);
472 // Delete the old constant!
476 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
477 bool DisableChecking) {
478 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
480 std::vector<Constant*> Values;
481 Values.reserve(getNumOperands()); // Build replacement array...
482 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
483 Constant *Val = getOperand(i);
484 if (Val == From) Val = cast<Constant>(To);
485 Values.push_back(Val);
488 Constant *Replacement = ConstantStruct::get(getType(), Values);
489 assert(Replacement != this && "I didn't contain From!");
491 // Everyone using this now uses the replacement...
493 uncheckedReplaceAllUsesWith(Replacement);
495 replaceAllUsesWith(Replacement);
497 // Delete the old constant!
501 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
502 bool DisableChecking) {
503 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
505 std::vector<Constant*> Values;
506 Values.reserve(getNumOperands()); // Build replacement array...
507 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
508 Constant *Val = getOperand(i);
509 if (Val == From) Val = cast<Constant>(To);
510 Values.push_back(Val);
513 Constant *Replacement = ConstantPacked::get(getType(), Values);
514 assert(Replacement != this && "I didn't contain From!");
516 // Everyone using this now uses the replacement...
518 uncheckedReplaceAllUsesWith(Replacement);
520 replaceAllUsesWith(Replacement);
522 // Delete the old constant!
526 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
527 bool DisableChecking) {
528 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
529 Constant *To = cast<Constant>(ToV);
531 Constant *Replacement = 0;
532 if (getOpcode() == Instruction::GetElementPtr) {
533 std::vector<Constant*> Indices;
534 Constant *Pointer = getOperand(0);
535 Indices.reserve(getNumOperands()-1);
536 if (Pointer == From) Pointer = To;
538 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
539 Constant *Val = getOperand(i);
540 if (Val == From) Val = To;
541 Indices.push_back(Val);
543 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
544 } else if (getOpcode() == Instruction::Cast) {
545 assert(getOperand(0) == From && "Cast only has one use!");
546 Replacement = ConstantExpr::getCast(To, getType());
547 } else if (getOpcode() == Instruction::Select) {
548 Constant *C1 = getOperand(0);
549 Constant *C2 = getOperand(1);
550 Constant *C3 = getOperand(2);
551 if (C1 == From) C1 = To;
552 if (C2 == From) C2 = To;
553 if (C3 == From) C3 = To;
554 Replacement = ConstantExpr::getSelect(C1, C2, C3);
555 } else if (getNumOperands() == 2) {
556 Constant *C1 = getOperand(0);
557 Constant *C2 = getOperand(1);
558 if (C1 == From) C1 = To;
559 if (C2 == From) C2 = To;
560 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
562 assert(0 && "Unknown ConstantExpr type!");
566 assert(Replacement != this && "I didn't contain From!");
568 // Everyone using this now uses the replacement...
570 uncheckedReplaceAllUsesWith(Replacement);
572 replaceAllUsesWith(Replacement);
574 // Delete the old constant!
578 //===----------------------------------------------------------------------===//
579 // Factory Function Implementation
581 // ConstantCreator - A class that is used to create constants by
582 // ValueMap*. This class should be partially specialized if there is
583 // something strange that needs to be done to interface to the ctor for the
587 template<class ConstantClass, class TypeClass, class ValType>
588 struct ConstantCreator {
589 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
590 return new ConstantClass(Ty, V);
594 template<class ConstantClass, class TypeClass>
595 struct ConvertConstantType {
596 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
597 assert(0 && "This type cannot be converted!\n");
604 template<class ValType, class TypeClass, class ConstantClass>
605 class ValueMap : public AbstractTypeUser {
606 typedef std::pair<const TypeClass*, ValType> MapKey;
607 typedef std::map<MapKey, ConstantClass *> MapTy;
608 typedef typename MapTy::iterator MapIterator;
611 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
612 AbstractTypeMapTy AbstractTypeMap;
614 // getOrCreate - Return the specified constant from the map, creating it if
616 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
617 MapKey Lookup(Ty, V);
618 MapIterator I = Map.lower_bound(Lookup);
619 if (I != Map.end() && I->first == Lookup)
620 return I->second; // Is it in the map?
622 // If no preexisting value, create one now...
623 ConstantClass *Result =
624 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 the type of the constant is abstract, make sure that an entry exists
632 // for it in the AbstractTypeMap.
633 if (Ty->isAbstract()) {
634 typename AbstractTypeMapTy::iterator TI =
635 AbstractTypeMap.lower_bound(Ty);
637 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
638 // Add ourselves to the ATU list of the type.
639 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
641 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
647 void remove(ConstantClass *CP) {
648 MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
650 if (I == Map.end() || I->second != CP) {
651 // FIXME: This should not use a linear scan. If this gets to be a
652 // performance problem, someone should look at this.
653 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
657 assert(I != Map.end() && "Constant not found in constant table!");
658 assert(I->second == CP && "Didn't find correct element?");
660 // Now that we found the entry, make sure this isn't the entry that
661 // the AbstractTypeMap points to.
662 const TypeClass *Ty = I->first.first;
663 if (Ty->isAbstract()) {
664 assert(AbstractTypeMap.count(Ty) &&
665 "Abstract type not in AbstractTypeMap?");
666 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
667 if (ATMEntryIt == I) {
668 // Yes, we are removing the representative entry for this type.
669 // See if there are any other entries of the same type.
670 MapIterator TmpIt = ATMEntryIt;
672 // First check the entry before this one...
673 if (TmpIt != Map.begin()) {
675 if (TmpIt->first.first != Ty) // Not the same type, move back...
679 // If we didn't find the same type, try to move forward...
680 if (TmpIt == ATMEntryIt) {
682 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
683 --TmpIt; // No entry afterwards with the same type
686 // If there is another entry in the map of the same abstract type,
687 // update the AbstractTypeMap entry now.
688 if (TmpIt != ATMEntryIt) {
691 // Otherwise, we are removing the last instance of this type
692 // from the table. Remove from the ATM, and from user list.
693 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
694 AbstractTypeMap.erase(Ty);
702 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
703 typename AbstractTypeMapTy::iterator I =
704 AbstractTypeMap.find(cast<TypeClass>(OldTy));
706 assert(I != AbstractTypeMap.end() &&
707 "Abstract type not in AbstractTypeMap?");
709 // Convert a constant at a time until the last one is gone. The last one
710 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
711 // eliminated eventually.
713 ConvertConstantType<ConstantClass,
714 TypeClass>::convert(I->second->second,
715 cast<TypeClass>(NewTy));
717 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
718 } while (I != AbstractTypeMap.end());
721 // If the type became concrete without being refined to any other existing
722 // type, we just remove ourselves from the ATU list.
723 void typeBecameConcrete(const DerivedType *AbsTy) {
724 AbsTy->removeAbstractTypeUser(this);
728 std::cerr << "Constant.cpp: ValueMap\n";
733 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
735 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
736 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
738 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
739 return SIntConstants.getOrCreate(Ty, V);
742 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
743 return UIntConstants.getOrCreate(Ty, V);
746 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
747 assert(V <= 127 && "Can only be used with very small positive constants!");
748 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
749 return ConstantUInt::get(Ty, V);
752 //---- ConstantFP::get() implementation...
756 struct ConstantCreator<ConstantFP, Type, uint64_t> {
757 static ConstantFP *create(const Type *Ty, uint64_t V) {
758 assert(Ty == Type::DoubleTy);
764 return new ConstantFP(Ty, T.F);
768 struct ConstantCreator<ConstantFP, Type, uint32_t> {
769 static ConstantFP *create(const Type *Ty, uint32_t V) {
770 assert(Ty == Type::FloatTy);
776 return new ConstantFP(Ty, T.F);
781 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
782 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
784 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
785 if (Ty == Type::FloatTy) {
786 // Force the value through memory to normalize it.
792 return FloatConstants.getOrCreate(Ty, T.I);
794 assert(Ty == Type::DoubleTy);
800 return DoubleConstants.getOrCreate(Ty, T.I);
804 //---- ConstantAggregateZero::get() implementation...
807 // ConstantAggregateZero does not take extra "value" argument...
808 template<class ValType>
809 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
810 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
811 return new ConstantAggregateZero(Ty);
816 struct ConvertConstantType<ConstantAggregateZero, Type> {
817 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
818 // Make everyone now use a constant of the new type...
819 Constant *New = ConstantAggregateZero::get(NewTy);
820 assert(New != OldC && "Didn't replace constant??");
821 OldC->uncheckedReplaceAllUsesWith(New);
822 OldC->destroyConstant(); // This constant is now dead, destroy it.
827 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
829 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
831 Constant *ConstantAggregateZero::get(const Type *Ty) {
832 return AggZeroConstants.getOrCreate(Ty, 0);
835 // destroyConstant - Remove the constant from the constant table...
837 void ConstantAggregateZero::destroyConstant() {
838 AggZeroConstants.remove(this);
839 destroyConstantImpl();
842 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
843 bool DisableChecking) {
844 assert(0 && "No uses!");
850 //---- ConstantArray::get() implementation...
854 struct ConvertConstantType<ConstantArray, ArrayType> {
855 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
856 // Make everyone now use a constant of the new type...
857 std::vector<Constant*> C;
858 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
859 C.push_back(cast<Constant>(OldC->getOperand(i)));
860 Constant *New = ConstantArray::get(NewTy, C);
861 assert(New != OldC && "Didn't replace constant??");
862 OldC->uncheckedReplaceAllUsesWith(New);
863 OldC->destroyConstant(); // This constant is now dead, destroy it.
868 static std::vector<Constant*> getValType(ConstantArray *CA) {
869 std::vector<Constant*> Elements;
870 Elements.reserve(CA->getNumOperands());
871 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
872 Elements.push_back(cast<Constant>(CA->getOperand(i)));
876 static ValueMap<std::vector<Constant*>, ArrayType,
877 ConstantArray> ArrayConstants;
879 Constant *ConstantArray::get(const ArrayType *Ty,
880 const std::vector<Constant*> &V) {
881 // If this is an all-zero array, return a ConstantAggregateZero object
884 if (!C->isNullValue())
885 return ArrayConstants.getOrCreate(Ty, V);
886 for (unsigned i = 1, e = V.size(); i != e; ++i)
888 return ArrayConstants.getOrCreate(Ty, V);
890 return ConstantAggregateZero::get(Ty);
893 // destroyConstant - Remove the constant from the constant table...
895 void ConstantArray::destroyConstant() {
896 ArrayConstants.remove(this);
897 destroyConstantImpl();
900 // ConstantArray::get(const string&) - Return an array that is initialized to
901 // contain the specified string. A null terminator is added to the specified
902 // string so that it may be used in a natural way...
904 Constant *ConstantArray::get(const std::string &Str) {
905 std::vector<Constant*> ElementVals;
907 for (unsigned i = 0; i < Str.length(); ++i)
908 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
910 // Add a null terminator to the string...
911 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
913 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
914 return ConstantArray::get(ATy, ElementVals);
917 /// isString - This method returns true if the array is an array of sbyte or
918 /// ubyte, and if the elements of the array are all ConstantInt's.
919 bool ConstantArray::isString() const {
920 // Check the element type for sbyte or ubyte...
921 if (getType()->getElementType() != Type::UByteTy &&
922 getType()->getElementType() != Type::SByteTy)
924 // Check the elements to make sure they are all integers, not constant
926 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
927 if (!isa<ConstantInt>(getOperand(i)))
932 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
933 // then this method converts the array to an std::string and returns it.
934 // Otherwise, it asserts out.
936 std::string ConstantArray::getAsString() const {
937 assert(isString() && "Not a string!");
939 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
940 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
945 //---- ConstantStruct::get() implementation...
950 struct ConvertConstantType<ConstantStruct, StructType> {
951 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
952 // Make everyone now use a constant of the new type...
953 std::vector<Constant*> C;
954 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
955 C.push_back(cast<Constant>(OldC->getOperand(i)));
956 Constant *New = ConstantStruct::get(NewTy, C);
957 assert(New != OldC && "Didn't replace constant??");
959 OldC->uncheckedReplaceAllUsesWith(New);
960 OldC->destroyConstant(); // This constant is now dead, destroy it.
965 static ValueMap<std::vector<Constant*>, StructType,
966 ConstantStruct> StructConstants;
968 static std::vector<Constant*> getValType(ConstantStruct *CS) {
969 std::vector<Constant*> Elements;
970 Elements.reserve(CS->getNumOperands());
971 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
972 Elements.push_back(cast<Constant>(CS->getOperand(i)));
976 Constant *ConstantStruct::get(const StructType *Ty,
977 const std::vector<Constant*> &V) {
978 // Create a ConstantAggregateZero value if all elements are zeros...
979 for (unsigned i = 0, e = V.size(); i != e; ++i)
980 if (!V[i]->isNullValue())
981 return StructConstants.getOrCreate(Ty, V);
983 return ConstantAggregateZero::get(Ty);
986 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
987 std::vector<const Type*> StructEls;
988 StructEls.reserve(V.size());
989 for (unsigned i = 0, e = V.size(); i != e; ++i)
990 StructEls.push_back(V[i]->getType());
991 return get(StructType::get(StructEls), V);
994 // destroyConstant - Remove the constant from the constant table...
996 void ConstantStruct::destroyConstant() {
997 StructConstants.remove(this);
998 destroyConstantImpl();
1001 //---- ConstantPacked::get() implementation...
1005 struct ConvertConstantType<ConstantPacked, PackedType> {
1006 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1007 // Make everyone now use a constant of the new type...
1008 std::vector<Constant*> C;
1009 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1010 C.push_back(cast<Constant>(OldC->getOperand(i)));
1011 Constant *New = ConstantPacked::get(NewTy, C);
1012 assert(New != OldC && "Didn't replace constant??");
1013 OldC->uncheckedReplaceAllUsesWith(New);
1014 OldC->destroyConstant(); // This constant is now dead, destroy it.
1019 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1020 std::vector<Constant*> Elements;
1021 Elements.reserve(CP->getNumOperands());
1022 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1023 Elements.push_back(CP->getOperand(i));
1027 static ValueMap<std::vector<Constant*>, PackedType,
1028 ConstantPacked> PackedConstants;
1030 Constant *ConstantPacked::get(const PackedType *Ty,
1031 const std::vector<Constant*> &V) {
1032 // If this is an all-zero packed, return a ConstantAggregateZero object
1035 if (!C->isNullValue())
1036 return PackedConstants.getOrCreate(Ty, V);
1037 for (unsigned i = 1, e = V.size(); i != e; ++i)
1039 return PackedConstants.getOrCreate(Ty, V);
1041 return ConstantAggregateZero::get(Ty);
1044 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1045 assert(!V.empty() && "Cannot infer type if V is empty");
1046 return get(PackedType::get(V.front()->getType(),V.size()), V);
1049 // destroyConstant - Remove the constant from the constant table...
1051 void ConstantPacked::destroyConstant() {
1052 PackedConstants.remove(this);
1053 destroyConstantImpl();
1056 //---- ConstantPointerNull::get() implementation...
1060 // ConstantPointerNull does not take extra "value" argument...
1061 template<class ValType>
1062 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1063 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1064 return new ConstantPointerNull(Ty);
1069 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1070 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1071 // Make everyone now use a constant of the new type...
1072 Constant *New = ConstantPointerNull::get(NewTy);
1073 assert(New != OldC && "Didn't replace constant??");
1074 OldC->uncheckedReplaceAllUsesWith(New);
1075 OldC->destroyConstant(); // This constant is now dead, destroy it.
1080 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1082 static char getValType(ConstantPointerNull *) {
1087 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1088 return NullPtrConstants.getOrCreate(Ty, 0);
1091 // destroyConstant - Remove the constant from the constant table...
1093 void ConstantPointerNull::destroyConstant() {
1094 NullPtrConstants.remove(this);
1095 destroyConstantImpl();
1099 //---- ConstantExpr::get() implementations...
1101 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1105 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1106 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1107 if (V.first == Instruction::Cast)
1108 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
1109 if ((V.first >= Instruction::BinaryOpsBegin &&
1110 V.first < Instruction::BinaryOpsEnd) ||
1111 V.first == Instruction::Shl || V.first == Instruction::Shr)
1112 return new ConstantExpr(V.first, V.second[0], V.second[1]);
1113 if (V.first == Instruction::Select)
1114 return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
1116 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1118 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1119 return new ConstantExpr(V.second[0], IdxList, Ty);
1124 struct ConvertConstantType<ConstantExpr, Type> {
1125 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1127 switch (OldC->getOpcode()) {
1128 case Instruction::Cast:
1129 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1131 case Instruction::Select:
1132 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1133 OldC->getOperand(1),
1134 OldC->getOperand(2));
1136 case Instruction::Shl:
1137 case Instruction::Shr:
1138 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1139 OldC->getOperand(0), OldC->getOperand(1));
1142 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1143 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1144 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1145 OldC->getOperand(1));
1147 case Instruction::GetElementPtr:
1148 // Make everyone now use a constant of the new type...
1149 std::vector<Constant*> C;
1150 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1151 C.push_back(cast<Constant>(OldC->getOperand(i)));
1152 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1156 assert(New != OldC && "Didn't replace constant??");
1157 OldC->uncheckedReplaceAllUsesWith(New);
1158 OldC->destroyConstant(); // This constant is now dead, destroy it.
1161 } // end namespace llvm
1164 static ExprMapKeyType getValType(ConstantExpr *CE) {
1165 std::vector<Constant*> Operands;
1166 Operands.reserve(CE->getNumOperands());
1167 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1168 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1169 return ExprMapKeyType(CE->getOpcode(), Operands);
1172 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1174 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1175 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1177 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1178 return FC; // Fold a few common cases...
1180 // Look up the constant in the table first to ensure uniqueness
1181 std::vector<Constant*> argVec(1, C);
1182 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1183 return ExprConstants.getOrCreate(Ty, Key);
1186 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1187 assert(C->getType()->isInteger() && Ty->isInteger() &&
1188 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1189 "This is an illegal sign extension!");
1190 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1191 return ConstantExpr::getCast(C, Ty);
1194 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1195 assert(C->getType()->isInteger() && Ty->isInteger() &&
1196 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1197 "This is an illegal zero extension!");
1198 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1199 return ConstantExpr::getCast(C, Ty);
1202 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1203 Constant *C1, Constant *C2) {
1204 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1205 return getShiftTy(ReqTy, Opcode, C1, C2);
1206 // Check the operands for consistency first
1207 assert((Opcode >= Instruction::BinaryOpsBegin &&
1208 Opcode < Instruction::BinaryOpsEnd) &&
1209 "Invalid opcode in binary constant expression");
1210 assert(C1->getType() == C2->getType() &&
1211 "Operand types in binary constant expression should match");
1213 if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1214 ReqTy == Type::BoolTy))
1215 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1216 return FC; // Fold a few common cases...
1218 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1219 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1220 return ExprConstants.getOrCreate(ReqTy, Key);
1223 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1226 case Instruction::Add: case Instruction::Sub:
1227 case Instruction::Mul: case Instruction::Div:
1228 case Instruction::Rem:
1229 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1230 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) &&
1231 "Tried to create an arithmetic operation on a non-arithmetic type!");
1233 case Instruction::And:
1234 case Instruction::Or:
1235 case Instruction::Xor:
1236 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1237 assert(C1->getType()->isIntegral() &&
1238 "Tried to create an logical operation on a non-integral type!");
1240 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1241 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1242 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1244 case Instruction::Shl:
1245 case Instruction::Shr:
1246 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1247 assert(C1->getType()->isInteger() &&
1248 "Tried to create a shift operation on a non-integer type!");
1255 if (Instruction::isRelational(Opcode))
1256 return getTy(Type::BoolTy, Opcode, C1, C2);
1258 return getTy(C1->getType(), Opcode, C1, C2);
1261 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1262 Constant *V1, Constant *V2) {
1263 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1264 assert(V1->getType() == V2->getType() && "Select value types must match!");
1265 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1267 if (ReqTy == V1->getType())
1268 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1269 return SC; // Fold common cases
1271 std::vector<Constant*> argVec(3, C);
1274 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1275 return ExprConstants.getOrCreate(ReqTy, Key);
1278 /// getShiftTy - Return a shift left or shift right constant expr
1279 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1280 Constant *C1, Constant *C2) {
1281 // Check the operands for consistency first
1282 assert((Opcode == Instruction::Shl ||
1283 Opcode == Instruction::Shr) &&
1284 "Invalid opcode in binary constant expression");
1285 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1286 "Invalid operand types for Shift constant expr!");
1288 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1289 return FC; // Fold a few common cases...
1291 // Look up the constant in the table first to ensure uniqueness
1292 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1293 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1294 return ExprConstants.getOrCreate(ReqTy, Key);
1298 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1299 const std::vector<Constant*> &IdxList) {
1300 assert(GetElementPtrInst::getIndexedType(C->getType(),
1301 std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1302 "GEP indices invalid!");
1304 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1305 return FC; // Fold a few common cases...
1307 assert(isa<PointerType>(C->getType()) &&
1308 "Non-pointer type for constant GetElementPtr expression");
1309 // Look up the constant in the table first to ensure uniqueness
1310 std::vector<Constant*> argVec(1, C);
1311 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1312 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1313 return ExprConstants.getOrCreate(ReqTy, Key);
1316 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1317 const std::vector<Constant*> &IdxList){
1318 // Get the result type of the getelementptr!
1319 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1321 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1323 assert(Ty && "GEP indices invalid!");
1324 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1328 // destroyConstant - Remove the constant from the constant table...
1330 void ConstantExpr::destroyConstant() {
1331 ExprConstants.remove(this);
1332 destroyConstantImpl();
1335 const char *ConstantExpr::getOpcodeName() const {
1336 return Instruction::getOpcodeName(getOpcode());