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->getPrimitiveID()) {
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->getPrimitiveID()) {
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->getPrimitiveID()) {
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->getPrimitiveID()) {
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()->getPrimitiveID() ==
247 T->getElementType()->getPrimitiveID()));
248 Operands.push_back(Use(V[i], this));
252 ConstantStruct::ConstantStruct(const StructType *T,
253 const std::vector<Constant*> &V) : Constant(T) {
254 assert(V.size() == T->getNumElements() &&
255 "Invalid initializer vector for constant structure");
256 Operands.reserve(V.size());
257 for (unsigned i = 0, e = V.size(); i != e; ++i) {
258 assert((V[i]->getType() == T->getElementType(i) ||
259 ((T->getElementType(i)->isAbstract() ||
260 V[i]->getType()->isAbstract()) &&
261 T->getElementType(i)->getPrimitiveID() ==
262 V[i]->getType()->getPrimitiveID())) &&
263 "Initializer for struct element doesn't match struct element type!");
264 Operands.push_back(Use(V[i], this));
268 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
269 : Constant(GV->getType()) {
271 Operands.push_back(Use(GV, this));
274 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
275 : Constant(Ty), iType(Opcode) {
277 Operands.push_back(Use(C, this));
280 // Select instruction creation ctor
281 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
282 : Constant(V1->getType()), iType(Instruction::Select) {
284 Operands.push_back(Use(C, this));
285 Operands.push_back(Use(V1, this));
286 Operands.push_back(Use(V2, this));
290 static bool isSetCC(unsigned Opcode) {
291 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
292 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
293 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
296 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
297 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
299 Operands.push_back(Use(C1, this));
300 Operands.push_back(Use(C2, this));
303 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
305 : Constant(DestTy), iType(Instruction::GetElementPtr) {
306 Operands.reserve(1+IdxList.size());
307 Operands.push_back(Use(C, this));
308 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
309 Operands.push_back(Use(IdxList[i], this));
312 /// ConstantExpr::get* - Return some common constants without having to
313 /// specify the full Instruction::OPCODE identifier.
315 Constant *ConstantExpr::getNeg(Constant *C) {
316 if (!C->getType()->isFloatingPoint())
317 return get(Instruction::Sub, getNullValue(C->getType()), C);
319 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
321 Constant *ConstantExpr::getNot(Constant *C) {
322 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
323 return get(Instruction::Xor, C,
324 ConstantIntegral::getAllOnesValue(C->getType()));
326 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
327 return get(Instruction::Add, C1, C2);
329 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
330 return get(Instruction::Sub, C1, C2);
332 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
333 return get(Instruction::Mul, C1, C2);
335 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
336 return get(Instruction::Div, C1, C2);
338 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
339 return get(Instruction::Rem, C1, C2);
341 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
342 return get(Instruction::And, C1, C2);
344 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
345 return get(Instruction::Or, C1, C2);
347 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
348 return get(Instruction::Xor, C1, C2);
350 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
351 return get(Instruction::SetEQ, C1, C2);
353 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
354 return get(Instruction::SetNE, C1, C2);
356 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
357 return get(Instruction::SetLT, C1, C2);
359 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
360 return get(Instruction::SetGT, C1, C2);
362 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
363 return get(Instruction::SetLE, C1, C2);
365 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
366 return get(Instruction::SetGE, C1, C2);
368 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
369 return get(Instruction::Shl, C1, C2);
371 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
372 return get(Instruction::Shr, C1, C2);
375 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
376 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
377 return getCast(getShr(getCast(C1,
378 C1->getType()->getUnsignedVersion()), C2), C1->getType());
381 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
382 if (C1->getType()->isSigned()) return getShr(C1, C2);
383 return getCast(getShr(getCast(C1,
384 C1->getType()->getSignedVersion()), C2), C1->getType());
388 //===----------------------------------------------------------------------===//
389 // classof implementations
391 bool ConstantIntegral::classof(const Constant *CPV) {
392 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
395 bool ConstantInt::classof(const Constant *CPV) {
396 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
398 bool ConstantSInt::classof(const Constant *CPV) {
399 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
401 bool ConstantUInt::classof(const Constant *CPV) {
402 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
404 bool ConstantFP::classof(const Constant *CPV) {
405 const Type *Ty = CPV->getType();
406 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
407 !isa<ConstantExpr>(CPV));
409 bool ConstantAggregateZero::classof(const Constant *CPV) {
410 return (isa<ArrayType>(CPV->getType()) || isa<StructType>(CPV->getType())) &&
413 bool ConstantArray::classof(const Constant *CPV) {
414 return isa<ArrayType>(CPV->getType()) && !CPV->isNullValue();
416 bool ConstantStruct::classof(const Constant *CPV) {
417 return isa<StructType>(CPV->getType()) && !CPV->isNullValue();
420 bool ConstantPointerNull::classof(const Constant *CPV) {
421 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
422 CPV->getNumOperands() == 0;
425 bool ConstantPointerRef::classof(const Constant *CPV) {
426 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
427 CPV->getNumOperands() == 1;
432 //===----------------------------------------------------------------------===//
433 // isValueValidForType implementations
435 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
436 switch (Ty->getPrimitiveID()) {
438 return false; // These can't be represented as integers!!!
441 case Type::SByteTyID:
442 return (Val <= INT8_MAX && Val >= INT8_MIN);
443 case Type::ShortTyID:
444 return (Val <= INT16_MAX && Val >= INT16_MIN);
446 return (Val <= INT32_MAX && Val >= INT32_MIN);
448 return true; // This is the largest type...
454 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
455 switch (Ty->getPrimitiveID()) {
457 return false; // These can't be represented as integers!!!
460 case Type::UByteTyID:
461 return (Val <= UINT8_MAX);
462 case Type::UShortTyID:
463 return (Val <= UINT16_MAX);
465 return (Val <= UINT32_MAX);
466 case Type::ULongTyID:
467 return true; // This is the largest type...
473 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
474 switch (Ty->getPrimitiveID()) {
476 return false; // These can't be represented as floating point!
478 // TODO: Figure out how to test if a double can be cast to a float!
479 case Type::FloatTyID:
480 case Type::DoubleTyID:
481 return true; // This is the largest type...
485 //===----------------------------------------------------------------------===//
486 // replaceUsesOfWithOnConstant implementations
488 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
489 bool DisableChecking) {
490 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
492 std::vector<Constant*> Values;
493 Values.reserve(getValues().size()); // Build replacement array...
494 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
495 Constant *Val = cast<Constant>(getValues()[i]);
496 if (Val == From) Val = cast<Constant>(To);
497 Values.push_back(Val);
500 Constant *Replacement = ConstantArray::get(getType(), Values);
501 assert(Replacement != this && "I didn't contain From!");
503 // Everyone using this now uses the replacement...
505 uncheckedReplaceAllUsesWith(Replacement);
507 replaceAllUsesWith(Replacement);
509 // Delete the old constant!
513 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
514 bool DisableChecking) {
515 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
517 std::vector<Constant*> Values;
518 Values.reserve(getValues().size());
519 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
520 Constant *Val = cast<Constant>(getValues()[i]);
521 if (Val == From) Val = cast<Constant>(To);
522 Values.push_back(Val);
525 Constant *Replacement = ConstantStruct::get(getType(), Values);
526 assert(Replacement != this && "I didn't contain From!");
528 // Everyone using this now uses the replacement...
530 uncheckedReplaceAllUsesWith(Replacement);
532 replaceAllUsesWith(Replacement);
534 // Delete the old constant!
538 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
539 bool DisableChecking) {
540 if (isa<GlobalValue>(To)) {
541 assert(From == getOperand(0) && "Doesn't contain from!");
542 ConstantPointerRef *Replacement =
543 ConstantPointerRef::get(cast<GlobalValue>(To));
545 // Everyone using this now uses the replacement...
547 uncheckedReplaceAllUsesWith(Replacement);
549 replaceAllUsesWith(Replacement);
552 // Just replace ourselves with the To value specified.
554 uncheckedReplaceAllUsesWith(To);
556 replaceAllUsesWith(To);
559 // Delete the old constant!
563 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
564 bool DisableChecking) {
565 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
566 Constant *To = cast<Constant>(ToV);
568 Constant *Replacement = 0;
569 if (getOpcode() == Instruction::GetElementPtr) {
570 std::vector<Constant*> Indices;
571 Constant *Pointer = getOperand(0);
572 Indices.reserve(getNumOperands()-1);
573 if (Pointer == From) Pointer = To;
575 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
576 Constant *Val = getOperand(i);
577 if (Val == From) Val = To;
578 Indices.push_back(Val);
580 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
581 } else if (getOpcode() == Instruction::Cast) {
582 assert(getOperand(0) == From && "Cast only has one use!");
583 Replacement = ConstantExpr::getCast(To, getType());
584 } else if (getOpcode() == Instruction::Select) {
585 Constant *C1 = getOperand(0);
586 Constant *C2 = getOperand(1);
587 Constant *C3 = getOperand(2);
588 if (C1 == From) C1 = To;
589 if (C2 == From) C2 = To;
590 if (C3 == From) C3 = To;
591 Replacement = ConstantExpr::getSelect(C1, C2, C3);
592 } else if (getNumOperands() == 2) {
593 Constant *C1 = getOperand(0);
594 Constant *C2 = getOperand(1);
595 if (C1 == From) C1 = To;
596 if (C2 == From) C2 = To;
597 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
599 assert(0 && "Unknown ConstantExpr type!");
603 assert(Replacement != this && "I didn't contain From!");
605 // Everyone using this now uses the replacement...
607 uncheckedReplaceAllUsesWith(Replacement);
609 replaceAllUsesWith(Replacement);
611 // Delete the old constant!
615 //===----------------------------------------------------------------------===//
616 // Factory Function Implementation
618 // ConstantCreator - A class that is used to create constants by
619 // ValueMap*. This class should be partially specialized if there is
620 // something strange that needs to be done to interface to the ctor for the
624 template<class ConstantClass, class TypeClass, class ValType>
625 struct ConstantCreator {
626 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
627 return new ConstantClass(Ty, V);
631 template<class ConstantClass, class TypeClass>
632 struct ConvertConstantType {
633 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
634 assert(0 && "This type cannot be converted!\n");
641 template<class ValType, class TypeClass, class ConstantClass>
642 class ValueMap : public AbstractTypeUser {
643 typedef std::pair<const TypeClass*, ValType> MapKey;
644 typedef std::map<MapKey, ConstantClass *> MapTy;
645 typedef typename MapTy::iterator MapIterator;
648 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
649 AbstractTypeMapTy AbstractTypeMap;
651 // getOrCreate - Return the specified constant from the map, creating it if
653 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
654 MapKey Lookup(Ty, V);
655 MapIterator I = Map.lower_bound(Lookup);
656 if (I != Map.end() && I->first == Lookup)
657 return I->second; // Is it in the map?
659 // If no preexisting value, create one now...
660 ConstantClass *Result =
661 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
664 /// FIXME: why does this assert fail when loading 176.gcc?
665 //assert(Result->getType() == Ty && "Type specified is not correct!");
666 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
668 // If the type of the constant is abstract, make sure that an entry exists
669 // for it in the AbstractTypeMap.
670 if (Ty->isAbstract()) {
671 typename AbstractTypeMapTy::iterator TI =
672 AbstractTypeMap.lower_bound(Ty);
674 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
675 // Add ourselves to the ATU list of the type.
676 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
678 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
684 void remove(ConstantClass *CP) {
685 // FIXME: This should not use a linear scan. If this gets to be a
686 // performance problem, someone should look at this.
687 MapIterator I = Map.begin();
688 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
691 assert(I != Map.end() && "Constant not found in constant table!");
693 // Now that we found the entry, make sure this isn't the entry that
694 // the AbstractTypeMap points to.
695 const TypeClass *Ty = I->first.first;
696 if (Ty->isAbstract()) {
697 assert(AbstractTypeMap.count(Ty) &&
698 "Abstract type not in AbstractTypeMap?");
699 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
700 if (ATMEntryIt == I) {
701 // Yes, we are removing the representative entry for this type.
702 // See if there are any other entries of the same type.
703 MapIterator TmpIt = ATMEntryIt;
705 // First check the entry before this one...
706 if (TmpIt != Map.begin()) {
708 if (TmpIt->first.first != Ty) // Not the same type, move back...
712 // If we didn't find the same type, try to move forward...
713 if (TmpIt == ATMEntryIt) {
715 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
716 --TmpIt; // No entry afterwards with the same type
719 // If there is another entry in the map of the same abstract type,
720 // update the AbstractTypeMap entry now.
721 if (TmpIt != ATMEntryIt) {
724 // Otherwise, we are removing the last instance of this type
725 // from the table. Remove from the ATM, and from user list.
726 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
727 AbstractTypeMap.erase(Ty);
735 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
736 typename AbstractTypeMapTy::iterator I =
737 AbstractTypeMap.find(cast<TypeClass>(OldTy));
739 assert(I != AbstractTypeMap.end() &&
740 "Abstract type not in AbstractTypeMap?");
742 // Convert a constant at a time until the last one is gone. The last one
743 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
744 // eliminated eventually.
746 ConvertConstantType<ConstantClass,
747 TypeClass>::convert(I->second->second,
748 cast<TypeClass>(NewTy));
750 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
751 } while (I != AbstractTypeMap.end());
754 // If the type became concrete without being refined to any other existing
755 // type, we just remove ourselves from the ATU list.
756 void typeBecameConcrete(const DerivedType *AbsTy) {
757 AbsTy->removeAbstractTypeUser(this);
761 std::cerr << "Constant.cpp: ValueMap\n";
768 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
770 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
771 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
773 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
774 return SIntConstants.getOrCreate(Ty, V);
777 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
778 return UIntConstants.getOrCreate(Ty, V);
781 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
782 assert(V <= 127 && "Can only be used with very small positive constants!");
783 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
784 return ConstantUInt::get(Ty, V);
787 //---- ConstantFP::get() implementation...
791 struct ConstantCreator<ConstantFP, Type, uint64_t> {
792 static ConstantFP *create(const Type *Ty, uint64_t V) {
793 assert(Ty == Type::DoubleTy);
799 return new ConstantFP(Ty, T.F);
803 struct ConstantCreator<ConstantFP, Type, uint32_t> {
804 static ConstantFP *create(const Type *Ty, uint32_t V) {
805 assert(Ty == Type::FloatTy);
811 return new ConstantFP(Ty, T.F);
816 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
817 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
819 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
820 if (Ty == Type::FloatTy) {
821 // Force the value through memory to normalize it.
827 return FloatConstants.getOrCreate(Ty, T.I);
829 assert(Ty == Type::DoubleTy);
835 return DoubleConstants.getOrCreate(Ty, T.I);
839 //---- ConstantAggregateZero::get() implementation...
842 // ConstantAggregateZero does not take extra "value" argument...
843 template<class ValType>
844 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
845 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
846 return new ConstantAggregateZero(Ty);
851 struct ConvertConstantType<ConstantAggregateZero, Type> {
852 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
853 // Make everyone now use a constant of the new type...
854 Constant *New = ConstantAggregateZero::get(NewTy);
855 assert(New != OldC && "Didn't replace constant??");
856 OldC->uncheckedReplaceAllUsesWith(New);
857 OldC->destroyConstant(); // This constant is now dead, destroy it.
862 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
864 Constant *ConstantAggregateZero::get(const Type *Ty) {
865 return AggZeroConstants.getOrCreate(Ty, 0);
868 // destroyConstant - Remove the constant from the constant table...
870 void ConstantAggregateZero::destroyConstant() {
871 AggZeroConstants.remove(this);
872 destroyConstantImpl();
875 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
876 bool DisableChecking) {
877 assert(0 && "No uses!");
883 //---- ConstantArray::get() implementation...
887 struct ConvertConstantType<ConstantArray, ArrayType> {
888 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
889 // Make everyone now use a constant of the new type...
890 std::vector<Constant*> C;
891 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
892 C.push_back(cast<Constant>(OldC->getOperand(i)));
893 Constant *New = ConstantArray::get(NewTy, C);
894 assert(New != OldC && "Didn't replace constant??");
895 OldC->uncheckedReplaceAllUsesWith(New);
896 OldC->destroyConstant(); // This constant is now dead, destroy it.
901 static ValueMap<std::vector<Constant*>, ArrayType,
902 ConstantArray> ArrayConstants;
904 Constant *ConstantArray::get(const ArrayType *Ty,
905 const std::vector<Constant*> &V) {
906 // If this is an all-zero array, return a ConstantAggregateZero object
909 if (!C->isNullValue())
910 return ArrayConstants.getOrCreate(Ty, V);
911 for (unsigned i = 1, e = V.size(); i != e; ++i)
913 return ArrayConstants.getOrCreate(Ty, V);
915 return ConstantAggregateZero::get(Ty);
918 // destroyConstant - Remove the constant from the constant table...
920 void ConstantArray::destroyConstant() {
921 ArrayConstants.remove(this);
922 destroyConstantImpl();
925 // ConstantArray::get(const string&) - Return an array that is initialized to
926 // contain the specified string. A null terminator is added to the specified
927 // string so that it may be used in a natural way...
929 Constant *ConstantArray::get(const std::string &Str) {
930 std::vector<Constant*> ElementVals;
932 for (unsigned i = 0; i < Str.length(); ++i)
933 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
935 // Add a null terminator to the string...
936 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
938 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
939 return ConstantArray::get(ATy, ElementVals);
942 /// isString - This method returns true if the array is an array of sbyte or
943 /// ubyte, and if the elements of the array are all ConstantInt's.
944 bool ConstantArray::isString() const {
945 // Check the element type for sbyte or ubyte...
946 if (getType()->getElementType() != Type::UByteTy &&
947 getType()->getElementType() != Type::SByteTy)
949 // Check the elements to make sure they are all integers, not constant
951 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
952 if (!isa<ConstantInt>(getOperand(i)))
957 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
958 // then this method converts the array to an std::string and returns it.
959 // Otherwise, it asserts out.
961 std::string ConstantArray::getAsString() const {
962 assert(isString() && "Not a string!");
964 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
965 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
970 //---- ConstantStruct::get() implementation...
975 struct ConvertConstantType<ConstantStruct, StructType> {
976 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
977 // Make everyone now use a constant of the new type...
978 std::vector<Constant*> C;
979 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
980 C.push_back(cast<Constant>(OldC->getOperand(i)));
981 Constant *New = ConstantStruct::get(NewTy, C);
982 assert(New != OldC && "Didn't replace constant??");
984 OldC->uncheckedReplaceAllUsesWith(New);
985 OldC->destroyConstant(); // This constant is now dead, destroy it.
990 static ValueMap<std::vector<Constant*>, StructType,
991 ConstantStruct> StructConstants;
993 Constant *ConstantStruct::get(const StructType *Ty,
994 const std::vector<Constant*> &V) {
995 // Create a ConstantAggregateZero value if all elements are zeros...
996 for (unsigned i = 0, e = V.size(); i != e; ++i)
997 if (!V[i]->isNullValue())
998 return StructConstants.getOrCreate(Ty, V);
1000 return ConstantAggregateZero::get(Ty);
1003 // destroyConstant - Remove the constant from the constant table...
1005 void ConstantStruct::destroyConstant() {
1006 StructConstants.remove(this);
1007 destroyConstantImpl();
1010 //---- ConstantPointerNull::get() implementation...
1014 // ConstantPointerNull does not take extra "value" argument...
1015 template<class ValType>
1016 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1017 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1018 return new ConstantPointerNull(Ty);
1023 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1024 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1025 // Make everyone now use a constant of the new type...
1026 Constant *New = ConstantPointerNull::get(NewTy);
1027 assert(New != OldC && "Didn't replace constant??");
1028 OldC->uncheckedReplaceAllUsesWith(New);
1029 OldC->destroyConstant(); // This constant is now dead, destroy it.
1034 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
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 //---- ConstantPointerRef::get() implementation...
1050 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
1051 assert(GV->getParent() && "Global Value must be attached to a module!");
1053 // The Module handles the pointer reference sharing...
1054 return GV->getParent()->getConstantPointerRef(GV);
1057 // destroyConstant - Remove the constant from the constant table...
1059 void ConstantPointerRef::destroyConstant() {
1060 getValue()->getParent()->destroyConstantPointerRef(this);
1061 destroyConstantImpl();
1065 //---- ConstantExpr::get() implementations...
1067 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1071 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1072 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1073 if (V.first == Instruction::Cast)
1074 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
1075 if ((V.first >= Instruction::BinaryOpsBegin &&
1076 V.first < Instruction::BinaryOpsEnd) ||
1077 V.first == Instruction::Shl || V.first == Instruction::Shr)
1078 return new ConstantExpr(V.first, V.second[0], V.second[1]);
1079 if (V.first == Instruction::Select)
1080 return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
1082 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1084 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1085 return new ConstantExpr(V.second[0], IdxList, Ty);
1090 struct ConvertConstantType<ConstantExpr, Type> {
1091 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1093 switch (OldC->getOpcode()) {
1094 case Instruction::Cast:
1095 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1097 case Instruction::Select:
1098 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1099 OldC->getOperand(1),
1100 OldC->getOperand(2));
1102 case Instruction::Shl:
1103 case Instruction::Shr:
1104 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1105 OldC->getOperand(0), OldC->getOperand(1));
1108 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1109 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1110 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1111 OldC->getOperand(1));
1113 case Instruction::GetElementPtr:
1114 // Make everyone now use a constant of the new type...
1115 std::vector<Constant*> C;
1116 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1117 C.push_back(cast<Constant>(OldC->getOperand(i)));
1118 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1122 assert(New != OldC && "Didn't replace constant??");
1123 OldC->uncheckedReplaceAllUsesWith(New);
1124 OldC->destroyConstant(); // This constant is now dead, destroy it.
1127 } // end namespace llvm
1130 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1132 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1133 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1135 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1136 return FC; // Fold a few common cases...
1138 // Look up the constant in the table first to ensure uniqueness
1139 std::vector<Constant*> argVec(1, C);
1140 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1141 return ExprConstants.getOrCreate(Ty, Key);
1144 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1145 assert(C->getType()->isInteger() && Ty->isInteger() &&
1146 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1147 "This is an illegal sign extension!");
1148 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1149 return ConstantExpr::getCast(C, Ty);
1152 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1153 assert(C->getType()->isInteger() && Ty->isInteger() &&
1154 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1155 "This is an illegal zero extension!");
1156 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1157 return ConstantExpr::getCast(C, Ty);
1160 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1161 Constant *C1, Constant *C2) {
1162 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1163 return getShiftTy(ReqTy, Opcode, C1, C2);
1164 // Check the operands for consistency first
1165 assert((Opcode >= Instruction::BinaryOpsBegin &&
1166 Opcode < Instruction::BinaryOpsEnd) &&
1167 "Invalid opcode in binary constant expression");
1168 assert(C1->getType() == C2->getType() &&
1169 "Operand types in binary constant expression should match");
1171 if (ReqTy == C1->getType())
1172 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1173 return FC; // Fold a few common cases...
1175 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1176 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1177 return ExprConstants.getOrCreate(ReqTy, Key);
1180 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1181 Constant *V1, Constant *V2) {
1182 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1183 assert(V1->getType() == V2->getType() && "Select value types must match!");
1184 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1186 if (ReqTy == V1->getType())
1187 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1188 return SC; // Fold common cases
1190 std::vector<Constant*> argVec(3, C);
1193 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1194 return ExprConstants.getOrCreate(ReqTy, Key);
1197 /// getShiftTy - Return a shift left or shift right constant expr
1198 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1199 Constant *C1, Constant *C2) {
1200 // Check the operands for consistency first
1201 assert((Opcode == Instruction::Shl ||
1202 Opcode == Instruction::Shr) &&
1203 "Invalid opcode in binary constant expression");
1204 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1205 "Invalid operand types for Shift constant expr!");
1207 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1208 return FC; // Fold a few common cases...
1210 // Look up the constant in the table first to ensure uniqueness
1211 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1212 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1213 return ExprConstants.getOrCreate(ReqTy, Key);
1217 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1218 const std::vector<Constant*> &IdxList) {
1219 assert(GetElementPtrInst::getIndexedType(C->getType(),
1220 std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1221 "GEP indices invalid!");
1223 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1224 return FC; // Fold a few common cases...
1226 assert(isa<PointerType>(C->getType()) &&
1227 "Non-pointer type for constant GetElementPtr expression");
1228 // Look up the constant in the table first to ensure uniqueness
1229 std::vector<Constant*> argVec(1, C);
1230 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1231 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1232 return ExprConstants.getOrCreate(ReqTy, Key);
1235 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1236 const std::vector<Constant*> &IdxList){
1237 // Get the result type of the getelementptr!
1238 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1240 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1242 assert(Ty && "GEP indices invalid!");
1243 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1247 // destroyConstant - Remove the constant from the constant table...
1249 void ConstantExpr::destroyConstant() {
1250 ExprConstants.remove(this);
1251 destroyConstantImpl();
1254 const char *ConstantExpr::getOpcodeName() const {
1255 return Instruction::getOpcodeName(getOpcode());