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"
25 ConstantBool *ConstantBool::True = new ConstantBool(true);
26 ConstantBool *ConstantBool::False = new ConstantBool(false);
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 // Specialize setName to take care of symbol table majik
34 void Constant::setName(const std::string &Name, SymbolTable *ST) {
35 assert(ST && "Type::setName - Must provide symbol table argument!");
37 if (Name.size()) ST->insert(Name, this);
40 void Constant::destroyConstantImpl() {
41 // When a Constant is destroyed, there may be lingering
42 // references to the constant by other constants in the constant pool. These
43 // constants are implicitly dependent on the module that is being deleted,
44 // but they don't know that. Because we only find out when the CPV is
45 // deleted, we must now notify all of our users (that should only be
46 // Constants) that they are, in fact, invalid now and should be deleted.
48 while (!use_empty()) {
49 Value *V = use_back();
50 #ifndef NDEBUG // Only in -g mode...
51 if (!isa<Constant>(V))
52 std::cerr << "While deleting: " << *this
53 << "\n\nUse still stuck around after Def is destroyed: "
56 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
57 Constant *CPV = cast<Constant>(V);
58 CPV->destroyConstant();
60 // The constant should remove itself from our use list...
61 assert((use_empty() || use_back() != V) && "Constant not removed!");
64 // Value has no outstanding references it is safe to delete it now...
68 // Static constructor to create a '0' constant of arbitrary type...
69 Constant *Constant::getNullValue(const Type *Ty) {
70 switch (Ty->getTypeID()) {
71 case Type::BoolTyID: {
72 static Constant *NullBool = ConstantBool::get(false);
75 case Type::SByteTyID: {
76 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
79 case Type::UByteTyID: {
80 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
83 case Type::ShortTyID: {
84 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
87 case Type::UShortTyID: {
88 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
92 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
95 case Type::UIntTyID: {
96 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
99 case Type::LongTyID: {
100 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
103 case Type::ULongTyID: {
104 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
108 case Type::FloatTyID: {
109 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
112 case Type::DoubleTyID: {
113 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
117 case Type::PointerTyID:
118 return ConstantPointerNull::get(cast<PointerType>(Ty));
120 case Type::StructTyID:
121 case Type::ArrayTyID:
122 return ConstantAggregateZero::get(Ty);
124 // Function, Label, or Opaque type?
125 assert(!"Cannot create a null constant of that type!");
130 // Static constructor to create the maximum constant of an integral type...
131 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
132 switch (Ty->getTypeID()) {
133 case Type::BoolTyID: return ConstantBool::True;
134 case Type::SByteTyID:
135 case Type::ShortTyID:
137 case Type::LongTyID: {
138 // Calculate 011111111111111...
139 unsigned TypeBits = Ty->getPrimitiveSize()*8;
140 int64_t Val = INT64_MAX; // All ones
141 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
142 return ConstantSInt::get(Ty, Val);
145 case Type::UByteTyID:
146 case Type::UShortTyID:
148 case Type::ULongTyID: return getAllOnesValue(Ty);
154 // Static constructor to create the minimum constant for an integral type...
155 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
156 switch (Ty->getTypeID()) {
157 case Type::BoolTyID: return ConstantBool::False;
158 case Type::SByteTyID:
159 case Type::ShortTyID:
161 case Type::LongTyID: {
162 // Calculate 1111111111000000000000
163 unsigned TypeBits = Ty->getPrimitiveSize()*8;
164 int64_t Val = -1; // All ones
165 Val <<= TypeBits-1; // Shift over to the right spot
166 return ConstantSInt::get(Ty, Val);
169 case Type::UByteTyID:
170 case Type::UShortTyID:
172 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
178 // Static constructor to create an integral constant with all bits set
179 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
180 switch (Ty->getTypeID()) {
181 case Type::BoolTyID: return ConstantBool::True;
182 case Type::SByteTyID:
183 case Type::ShortTyID:
185 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
187 case Type::UByteTyID:
188 case Type::UShortTyID:
190 case Type::ULongTyID: {
191 // Calculate ~0 of the right type...
192 unsigned TypeBits = Ty->getPrimitiveSize()*8;
193 uint64_t Val = ~0ULL; // All ones
194 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
195 return ConstantUInt::get(Ty, Val);
201 bool ConstantUInt::isAllOnesValue() const {
202 unsigned TypeBits = getType()->getPrimitiveSize()*8;
203 uint64_t Val = ~0ULL; // All ones
204 Val >>= 64-TypeBits; // Shift out inappropriate bits
205 return getValue() == Val;
209 //===----------------------------------------------------------------------===//
210 // ConstantXXX Classes
211 //===----------------------------------------------------------------------===//
213 //===----------------------------------------------------------------------===//
214 // Normal Constructors
216 ConstantIntegral::ConstantIntegral(const Type *Ty, uint64_t V)
221 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy, V) {
224 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty, V) {
227 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
228 assert(Ty->isInteger() && Ty->isSigned() &&
229 "Illegal type for unsigned integer constant!");
230 assert(isValueValidForType(Ty, V) && "Value too large for type!");
233 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
234 assert(Ty->isInteger() && Ty->isUnsigned() &&
235 "Illegal type for unsigned integer constant!");
236 assert(isValueValidForType(Ty, V) && "Value too large for type!");
239 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
240 assert(isValueValidForType(Ty, V) && "Value too large for type!");
244 ConstantArray::ConstantArray(const ArrayType *T,
245 const std::vector<Constant*> &V) : Constant(T) {
246 Operands.reserve(V.size());
247 for (unsigned i = 0, e = V.size(); i != e; ++i) {
248 assert(V[i]->getType() == T->getElementType() ||
250 V[i]->getType()->getTypeID() == T->getElementType()->getTypeID()));
251 Operands.push_back(Use(V[i], this));
255 ConstantStruct::ConstantStruct(const StructType *T,
256 const std::vector<Constant*> &V) : Constant(T) {
257 assert(V.size() == T->getNumElements() &&
258 "Invalid initializer vector for constant structure");
259 Operands.reserve(V.size());
260 for (unsigned i = 0, e = V.size(); i != e; ++i) {
261 assert((V[i]->getType() == T->getElementType(i) ||
262 ((T->getElementType(i)->isAbstract() ||
263 V[i]->getType()->isAbstract()) &&
264 T->getElementType(i)->getTypeID() == V[i]->getType()->getTypeID())) &&
265 "Initializer for struct element doesn't match struct element type!");
266 Operands.push_back(Use(V[i], this));
270 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
271 : Constant(GV->getType()) {
273 Operands.push_back(Use(GV, this));
276 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
277 : Constant(Ty), iType(Opcode) {
279 Operands.push_back(Use(C, this));
282 // Select instruction creation ctor
283 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
284 : Constant(V1->getType()), iType(Instruction::Select) {
286 Operands.push_back(Use(C, this));
287 Operands.push_back(Use(V1, this));
288 Operands.push_back(Use(V2, this));
292 static bool isSetCC(unsigned Opcode) {
293 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
294 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
295 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
298 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
299 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
301 Operands.push_back(Use(C1, this));
302 Operands.push_back(Use(C2, this));
305 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
307 : Constant(DestTy), iType(Instruction::GetElementPtr) {
308 Operands.reserve(1+IdxList.size());
309 Operands.push_back(Use(C, this));
310 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
311 Operands.push_back(Use(IdxList[i], this));
314 /// ConstantExpr::get* - Return some common constants without having to
315 /// specify the full Instruction::OPCODE identifier.
317 Constant *ConstantExpr::getNeg(Constant *C) {
318 if (!C->getType()->isFloatingPoint())
319 return get(Instruction::Sub, getNullValue(C->getType()), C);
321 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
323 Constant *ConstantExpr::getNot(Constant *C) {
324 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
325 return get(Instruction::Xor, C,
326 ConstantIntegral::getAllOnesValue(C->getType()));
328 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
329 return get(Instruction::Add, C1, C2);
331 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
332 return get(Instruction::Sub, C1, C2);
334 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
335 return get(Instruction::Mul, C1, C2);
337 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
338 return get(Instruction::Div, C1, C2);
340 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
341 return get(Instruction::Rem, C1, C2);
343 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
344 return get(Instruction::And, C1, C2);
346 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
347 return get(Instruction::Or, C1, C2);
349 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
350 return get(Instruction::Xor, C1, C2);
352 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
353 return get(Instruction::SetEQ, C1, C2);
355 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
356 return get(Instruction::SetNE, C1, C2);
358 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
359 return get(Instruction::SetLT, C1, C2);
361 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
362 return get(Instruction::SetGT, C1, C2);
364 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
365 return get(Instruction::SetLE, C1, C2);
367 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
368 return get(Instruction::SetGE, C1, C2);
370 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
371 return get(Instruction::Shl, C1, C2);
373 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
374 return get(Instruction::Shr, C1, C2);
377 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
378 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
379 return getCast(getShr(getCast(C1,
380 C1->getType()->getUnsignedVersion()), C2), C1->getType());
383 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
384 if (C1->getType()->isSigned()) return getShr(C1, C2);
385 return getCast(getShr(getCast(C1,
386 C1->getType()->getSignedVersion()), C2), C1->getType());
390 //===----------------------------------------------------------------------===//
391 // classof implementations
393 bool ConstantIntegral::classof(const Constant *CPV) {
394 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
397 bool ConstantInt::classof(const Constant *CPV) {
398 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
400 bool ConstantSInt::classof(const Constant *CPV) {
401 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
403 bool ConstantUInt::classof(const Constant *CPV) {
404 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
406 bool ConstantFP::classof(const Constant *CPV) {
407 const Type *Ty = CPV->getType();
408 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
409 !isa<ConstantExpr>(CPV));
411 bool ConstantAggregateZero::classof(const Constant *CPV) {
412 return (isa<ArrayType>(CPV->getType()) || isa<StructType>(CPV->getType())) &&
415 bool ConstantArray::classof(const Constant *CPV) {
416 return isa<ArrayType>(CPV->getType()) && !CPV->isNullValue();
418 bool ConstantStruct::classof(const Constant *CPV) {
419 return isa<StructType>(CPV->getType()) && !CPV->isNullValue();
422 bool ConstantPointerNull::classof(const Constant *CPV) {
423 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
424 CPV->getNumOperands() == 0;
427 bool ConstantPointerRef::classof(const Constant *CPV) {
428 return isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
429 CPV->getNumOperands() == 1;
434 //===----------------------------------------------------------------------===//
435 // isValueValidForType implementations
437 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
438 switch (Ty->getTypeID()) {
440 return false; // These can't be represented as integers!!!
442 case Type::SByteTyID:
443 return (Val <= INT8_MAX && Val >= INT8_MIN);
444 case Type::ShortTyID:
445 return (Val <= INT16_MAX && Val >= INT16_MIN);
447 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
449 return true; // This is the largest type...
453 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
454 switch (Ty->getTypeID()) {
456 return false; // These can't be represented as integers!!!
459 case Type::UByteTyID:
460 return (Val <= UINT8_MAX);
461 case Type::UShortTyID:
462 return (Val <= UINT16_MAX);
464 return (Val <= UINT32_MAX);
465 case Type::ULongTyID:
466 return true; // This is the largest type...
470 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
471 switch (Ty->getTypeID()) {
473 return false; // These can't be represented as floating point!
475 // TODO: Figure out how to test if a double can be cast to a float!
476 case Type::FloatTyID:
477 case Type::DoubleTyID:
478 return true; // This is the largest type...
482 //===----------------------------------------------------------------------===//
483 // replaceUsesOfWithOnConstant implementations
485 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
486 bool DisableChecking) {
487 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
489 std::vector<Constant*> Values;
490 Values.reserve(getValues().size()); // Build replacement array...
491 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
492 Constant *Val = cast<Constant>(getValues()[i]);
493 if (Val == From) Val = cast<Constant>(To);
494 Values.push_back(Val);
497 Constant *Replacement = ConstantArray::get(getType(), Values);
498 assert(Replacement != this && "I didn't contain From!");
500 // Everyone using this now uses the replacement...
502 uncheckedReplaceAllUsesWith(Replacement);
504 replaceAllUsesWith(Replacement);
506 // Delete the old constant!
510 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
511 bool DisableChecking) {
512 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
514 std::vector<Constant*> Values;
515 Values.reserve(getValues().size());
516 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
517 Constant *Val = cast<Constant>(getValues()[i]);
518 if (Val == From) Val = cast<Constant>(To);
519 Values.push_back(Val);
522 Constant *Replacement = ConstantStruct::get(getType(), Values);
523 assert(Replacement != this && "I didn't contain From!");
525 // Everyone using this now uses the replacement...
527 uncheckedReplaceAllUsesWith(Replacement);
529 replaceAllUsesWith(Replacement);
531 // Delete the old constant!
535 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
536 bool DisableChecking) {
537 if (isa<GlobalValue>(To)) {
538 assert(From == getOperand(0) && "Doesn't contain from!");
539 ConstantPointerRef *Replacement =
540 ConstantPointerRef::get(cast<GlobalValue>(To));
542 // Everyone using this now uses the replacement...
544 uncheckedReplaceAllUsesWith(Replacement);
546 replaceAllUsesWith(Replacement);
549 // Just replace ourselves with the To value specified.
551 uncheckedReplaceAllUsesWith(To);
553 replaceAllUsesWith(To);
556 // Delete the old constant!
560 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
561 bool DisableChecking) {
562 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
563 Constant *To = cast<Constant>(ToV);
565 Constant *Replacement = 0;
566 if (getOpcode() == Instruction::GetElementPtr) {
567 std::vector<Constant*> Indices;
568 Constant *Pointer = getOperand(0);
569 Indices.reserve(getNumOperands()-1);
570 if (Pointer == From) Pointer = To;
572 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
573 Constant *Val = getOperand(i);
574 if (Val == From) Val = To;
575 Indices.push_back(Val);
577 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
578 } else if (getOpcode() == Instruction::Cast) {
579 assert(getOperand(0) == From && "Cast only has one use!");
580 Replacement = ConstantExpr::getCast(To, getType());
581 } else if (getOpcode() == Instruction::Select) {
582 Constant *C1 = getOperand(0);
583 Constant *C2 = getOperand(1);
584 Constant *C3 = getOperand(2);
585 if (C1 == From) C1 = To;
586 if (C2 == From) C2 = To;
587 if (C3 == From) C3 = To;
588 Replacement = ConstantExpr::getSelect(C1, C2, C3);
589 } else if (getNumOperands() == 2) {
590 Constant *C1 = getOperand(0);
591 Constant *C2 = getOperand(1);
592 if (C1 == From) C1 = To;
593 if (C2 == From) C2 = To;
594 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
596 assert(0 && "Unknown ConstantExpr type!");
600 assert(Replacement != this && "I didn't contain From!");
602 // Everyone using this now uses the replacement...
604 uncheckedReplaceAllUsesWith(Replacement);
606 replaceAllUsesWith(Replacement);
608 // Delete the old constant!
612 //===----------------------------------------------------------------------===//
613 // Factory Function Implementation
615 // ConstantCreator - A class that is used to create constants by
616 // ValueMap*. This class should be partially specialized if there is
617 // something strange that needs to be done to interface to the ctor for the
621 template<class ConstantClass, class TypeClass, class ValType>
622 struct ConstantCreator {
623 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
624 return new ConstantClass(Ty, V);
628 template<class ConstantClass, class TypeClass>
629 struct ConvertConstantType {
630 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
631 assert(0 && "This type cannot be converted!\n");
638 template<class ValType, class TypeClass, class ConstantClass>
639 class ValueMap : public AbstractTypeUser {
640 typedef std::pair<const TypeClass*, ValType> MapKey;
641 typedef std::map<MapKey, ConstantClass *> MapTy;
642 typedef typename MapTy::iterator MapIterator;
645 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
646 AbstractTypeMapTy AbstractTypeMap;
648 // getOrCreate - Return the specified constant from the map, creating it if
650 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
651 MapKey Lookup(Ty, V);
652 MapIterator I = Map.lower_bound(Lookup);
653 if (I != Map.end() && I->first == Lookup)
654 return I->second; // Is it in the map?
656 // If no preexisting value, create one now...
657 ConstantClass *Result =
658 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
661 /// FIXME: why does this assert fail when loading 176.gcc?
662 //assert(Result->getType() == Ty && "Type specified is not correct!");
663 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
665 // If the type of the constant is abstract, make sure that an entry exists
666 // for it in the AbstractTypeMap.
667 if (Ty->isAbstract()) {
668 typename AbstractTypeMapTy::iterator TI =
669 AbstractTypeMap.lower_bound(Ty);
671 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
672 // Add ourselves to the ATU list of the type.
673 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
675 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
681 void remove(ConstantClass *CP) {
682 // FIXME: This should not use a linear scan. If this gets to be a
683 // performance problem, someone should look at this.
684 MapIterator I = Map.begin();
685 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
688 assert(I != Map.end() && "Constant not found in constant table!");
690 // Now that we found the entry, make sure this isn't the entry that
691 // the AbstractTypeMap points to.
692 const TypeClass *Ty = I->first.first;
693 if (Ty->isAbstract()) {
694 assert(AbstractTypeMap.count(Ty) &&
695 "Abstract type not in AbstractTypeMap?");
696 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
697 if (ATMEntryIt == I) {
698 // Yes, we are removing the representative entry for this type.
699 // See if there are any other entries of the same type.
700 MapIterator TmpIt = ATMEntryIt;
702 // First check the entry before this one...
703 if (TmpIt != Map.begin()) {
705 if (TmpIt->first.first != Ty) // Not the same type, move back...
709 // If we didn't find the same type, try to move forward...
710 if (TmpIt == ATMEntryIt) {
712 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
713 --TmpIt; // No entry afterwards with the same type
716 // If there is another entry in the map of the same abstract type,
717 // update the AbstractTypeMap entry now.
718 if (TmpIt != ATMEntryIt) {
721 // Otherwise, we are removing the last instance of this type
722 // from the table. Remove from the ATM, and from user list.
723 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
724 AbstractTypeMap.erase(Ty);
732 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
733 typename AbstractTypeMapTy::iterator I =
734 AbstractTypeMap.find(cast<TypeClass>(OldTy));
736 assert(I != AbstractTypeMap.end() &&
737 "Abstract type not in AbstractTypeMap?");
739 // Convert a constant at a time until the last one is gone. The last one
740 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
741 // eliminated eventually.
743 ConvertConstantType<ConstantClass,
744 TypeClass>::convert(I->second->second,
745 cast<TypeClass>(NewTy));
747 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
748 } while (I != AbstractTypeMap.end());
751 // If the type became concrete without being refined to any other existing
752 // type, we just remove ourselves from the ATU list.
753 void typeBecameConcrete(const DerivedType *AbsTy) {
754 AbsTy->removeAbstractTypeUser(this);
758 std::cerr << "Constant.cpp: ValueMap\n";
765 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
767 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
768 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
770 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
771 return SIntConstants.getOrCreate(Ty, V);
774 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
775 return UIntConstants.getOrCreate(Ty, V);
778 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
779 assert(V <= 127 && "Can only be used with very small positive constants!");
780 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
781 return ConstantUInt::get(Ty, V);
784 //---- ConstantFP::get() implementation...
788 struct ConstantCreator<ConstantFP, Type, uint64_t> {
789 static ConstantFP *create(const Type *Ty, uint64_t V) {
790 assert(Ty == Type::DoubleTy);
796 return new ConstantFP(Ty, T.F);
800 struct ConstantCreator<ConstantFP, Type, uint32_t> {
801 static ConstantFP *create(const Type *Ty, uint32_t V) {
802 assert(Ty == Type::FloatTy);
808 return new ConstantFP(Ty, T.F);
813 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
814 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
816 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
817 if (Ty == Type::FloatTy) {
818 // Force the value through memory to normalize it.
824 return FloatConstants.getOrCreate(Ty, T.I);
826 assert(Ty == Type::DoubleTy);
832 return DoubleConstants.getOrCreate(Ty, T.I);
836 //---- ConstantAggregateZero::get() implementation...
839 // ConstantAggregateZero does not take extra "value" argument...
840 template<class ValType>
841 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
842 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
843 return new ConstantAggregateZero(Ty);
848 struct ConvertConstantType<ConstantAggregateZero, Type> {
849 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
850 // Make everyone now use a constant of the new type...
851 Constant *New = ConstantAggregateZero::get(NewTy);
852 assert(New != OldC && "Didn't replace constant??");
853 OldC->uncheckedReplaceAllUsesWith(New);
854 OldC->destroyConstant(); // This constant is now dead, destroy it.
859 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
861 Constant *ConstantAggregateZero::get(const Type *Ty) {
862 return AggZeroConstants.getOrCreate(Ty, 0);
865 // destroyConstant - Remove the constant from the constant table...
867 void ConstantAggregateZero::destroyConstant() {
868 AggZeroConstants.remove(this);
869 destroyConstantImpl();
872 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
873 bool DisableChecking) {
874 assert(0 && "No uses!");
880 //---- ConstantArray::get() implementation...
884 struct ConvertConstantType<ConstantArray, ArrayType> {
885 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
886 // Make everyone now use a constant of the new type...
887 std::vector<Constant*> C;
888 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
889 C.push_back(cast<Constant>(OldC->getOperand(i)));
890 Constant *New = ConstantArray::get(NewTy, C);
891 assert(New != OldC && "Didn't replace constant??");
892 OldC->uncheckedReplaceAllUsesWith(New);
893 OldC->destroyConstant(); // This constant is now dead, destroy it.
898 static ValueMap<std::vector<Constant*>, ArrayType,
899 ConstantArray> ArrayConstants;
901 Constant *ConstantArray::get(const ArrayType *Ty,
902 const std::vector<Constant*> &V) {
903 // If this is an all-zero array, return a ConstantAggregateZero object
906 if (!C->isNullValue())
907 return ArrayConstants.getOrCreate(Ty, V);
908 for (unsigned i = 1, e = V.size(); i != e; ++i)
910 return ArrayConstants.getOrCreate(Ty, V);
912 return ConstantAggregateZero::get(Ty);
915 // destroyConstant - Remove the constant from the constant table...
917 void ConstantArray::destroyConstant() {
918 ArrayConstants.remove(this);
919 destroyConstantImpl();
922 // ConstantArray::get(const string&) - Return an array that is initialized to
923 // contain the specified string. A null terminator is added to the specified
924 // string so that it may be used in a natural way...
926 Constant *ConstantArray::get(const std::string &Str) {
927 std::vector<Constant*> ElementVals;
929 for (unsigned i = 0; i < Str.length(); ++i)
930 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
932 // Add a null terminator to the string...
933 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
935 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
936 return ConstantArray::get(ATy, ElementVals);
939 /// isString - This method returns true if the array is an array of sbyte or
940 /// ubyte, and if the elements of the array are all ConstantInt's.
941 bool ConstantArray::isString() const {
942 // Check the element type for sbyte or ubyte...
943 if (getType()->getElementType() != Type::UByteTy &&
944 getType()->getElementType() != Type::SByteTy)
946 // Check the elements to make sure they are all integers, not constant
948 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
949 if (!isa<ConstantInt>(getOperand(i)))
954 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
955 // then this method converts the array to an std::string and returns it.
956 // Otherwise, it asserts out.
958 std::string ConstantArray::getAsString() const {
959 assert(isString() && "Not a string!");
961 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
962 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
967 //---- ConstantStruct::get() implementation...
972 struct ConvertConstantType<ConstantStruct, StructType> {
973 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
974 // Make everyone now use a constant of the new type...
975 std::vector<Constant*> C;
976 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
977 C.push_back(cast<Constant>(OldC->getOperand(i)));
978 Constant *New = ConstantStruct::get(NewTy, C);
979 assert(New != OldC && "Didn't replace constant??");
981 OldC->uncheckedReplaceAllUsesWith(New);
982 OldC->destroyConstant(); // This constant is now dead, destroy it.
987 static ValueMap<std::vector<Constant*>, StructType,
988 ConstantStruct> StructConstants;
990 Constant *ConstantStruct::get(const StructType *Ty,
991 const std::vector<Constant*> &V) {
992 // Create a ConstantAggregateZero value if all elements are zeros...
993 for (unsigned i = 0, e = V.size(); i != e; ++i)
994 if (!V[i]->isNullValue())
995 return StructConstants.getOrCreate(Ty, V);
997 return ConstantAggregateZero::get(Ty);
1000 // destroyConstant - Remove the constant from the constant table...
1002 void ConstantStruct::destroyConstant() {
1003 StructConstants.remove(this);
1004 destroyConstantImpl();
1007 //---- ConstantPointerNull::get() implementation...
1011 // ConstantPointerNull does not take extra "value" argument...
1012 template<class ValType>
1013 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1014 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1015 return new ConstantPointerNull(Ty);
1020 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1021 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1022 // Make everyone now use a constant of the new type...
1023 Constant *New = ConstantPointerNull::get(NewTy);
1024 assert(New != OldC && "Didn't replace constant??");
1025 OldC->uncheckedReplaceAllUsesWith(New);
1026 OldC->destroyConstant(); // This constant is now dead, destroy it.
1031 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1033 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1034 return NullPtrConstants.getOrCreate(Ty, 0);
1037 // destroyConstant - Remove the constant from the constant table...
1039 void ConstantPointerNull::destroyConstant() {
1040 NullPtrConstants.remove(this);
1041 destroyConstantImpl();
1045 //---- ConstantPointerRef::get() implementation...
1047 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
1048 assert(GV->getParent() && "Global Value must be attached to a module!");
1050 // The Module handles the pointer reference sharing...
1051 return GV->getParent()->getConstantPointerRef(GV);
1054 // destroyConstant - Remove the constant from the constant table...
1056 void ConstantPointerRef::destroyConstant() {
1057 getValue()->getParent()->destroyConstantPointerRef(this);
1058 destroyConstantImpl();
1062 //---- ConstantExpr::get() implementations...
1064 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1068 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1069 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1070 if (V.first == Instruction::Cast)
1071 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
1072 if ((V.first >= Instruction::BinaryOpsBegin &&
1073 V.first < Instruction::BinaryOpsEnd) ||
1074 V.first == Instruction::Shl || V.first == Instruction::Shr)
1075 return new ConstantExpr(V.first, V.second[0], V.second[1]);
1076 if (V.first == Instruction::Select)
1077 return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
1079 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1081 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1082 return new ConstantExpr(V.second[0], IdxList, Ty);
1087 struct ConvertConstantType<ConstantExpr, Type> {
1088 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1090 switch (OldC->getOpcode()) {
1091 case Instruction::Cast:
1092 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1094 case Instruction::Select:
1095 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1096 OldC->getOperand(1),
1097 OldC->getOperand(2));
1099 case Instruction::Shl:
1100 case Instruction::Shr:
1101 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1102 OldC->getOperand(0), OldC->getOperand(1));
1105 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1106 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1107 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1108 OldC->getOperand(1));
1110 case Instruction::GetElementPtr:
1111 // Make everyone now use a constant of the new type...
1112 std::vector<Constant*> C;
1113 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1114 C.push_back(cast<Constant>(OldC->getOperand(i)));
1115 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1119 assert(New != OldC && "Didn't replace constant??");
1120 OldC->uncheckedReplaceAllUsesWith(New);
1121 OldC->destroyConstant(); // This constant is now dead, destroy it.
1124 } // end namespace llvm
1127 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1129 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1130 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1132 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1133 return FC; // Fold a few common cases...
1135 // Look up the constant in the table first to ensure uniqueness
1136 std::vector<Constant*> argVec(1, C);
1137 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1138 return ExprConstants.getOrCreate(Ty, Key);
1141 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1142 assert(C->getType()->isInteger() && Ty->isInteger() &&
1143 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1144 "This is an illegal sign extension!");
1145 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1146 return ConstantExpr::getCast(C, Ty);
1149 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1150 assert(C->getType()->isInteger() && Ty->isInteger() &&
1151 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1152 "This is an illegal zero extension!");
1153 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1154 return ConstantExpr::getCast(C, Ty);
1157 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1158 Constant *C1, Constant *C2) {
1159 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1160 return getShiftTy(ReqTy, Opcode, C1, C2);
1161 // Check the operands for consistency first
1162 assert((Opcode >= Instruction::BinaryOpsBegin &&
1163 Opcode < Instruction::BinaryOpsEnd) &&
1164 "Invalid opcode in binary constant expression");
1165 assert(C1->getType() == C2->getType() &&
1166 "Operand types in binary constant expression should match");
1168 if (ReqTy == C1->getType())
1169 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1170 return FC; // Fold a few common cases...
1172 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1173 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1174 return ExprConstants.getOrCreate(ReqTy, Key);
1177 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1178 Constant *V1, Constant *V2) {
1179 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1180 assert(V1->getType() == V2->getType() && "Select value types must match!");
1181 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1183 if (ReqTy == V1->getType())
1184 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1185 return SC; // Fold common cases
1187 std::vector<Constant*> argVec(3, C);
1190 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1191 return ExprConstants.getOrCreate(ReqTy, Key);
1194 /// getShiftTy - Return a shift left or shift right constant expr
1195 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1196 Constant *C1, Constant *C2) {
1197 // Check the operands for consistency first
1198 assert((Opcode == Instruction::Shl ||
1199 Opcode == Instruction::Shr) &&
1200 "Invalid opcode in binary constant expression");
1201 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1202 "Invalid operand types for Shift constant expr!");
1204 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1205 return FC; // Fold a few common cases...
1207 // Look up the constant in the table first to ensure uniqueness
1208 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1209 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1210 return ExprConstants.getOrCreate(ReqTy, Key);
1214 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1215 const std::vector<Constant*> &IdxList) {
1216 assert(GetElementPtrInst::getIndexedType(C->getType(),
1217 std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1218 "GEP indices invalid!");
1220 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1221 return FC; // Fold a few common cases...
1223 assert(isa<PointerType>(C->getType()) &&
1224 "Non-pointer type for constant GetElementPtr expression");
1225 // Look up the constant in the table first to ensure uniqueness
1226 std::vector<Constant*> argVec(1, C);
1227 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1228 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1229 return ExprConstants.getOrCreate(ReqTy, Key);
1232 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1233 const std::vector<Constant*> &IdxList){
1234 // Get the result type of the getelementptr!
1235 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1237 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1239 assert(Ty && "GEP indices invalid!");
1240 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1244 // destroyConstant - Remove the constant from the constant table...
1246 void ConstantExpr::destroyConstant() {
1247 ExprConstants.remove(this);
1248 destroyConstantImpl();
1251 const char *ConstantExpr::getOpcodeName() const {
1252 return Instruction::getOpcodeName(getOpcode());