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/iMemory.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "Support/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 return ConstantAggregateZero::get(Ty);
125 // Function, Label, or Opaque type?
126 assert(!"Cannot create a null constant of that type!");
131 // Static constructor to create the maximum constant of an integral type...
132 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
133 switch (Ty->getTypeID()) {
134 case Type::BoolTyID: return ConstantBool::True;
135 case Type::SByteTyID:
136 case Type::ShortTyID:
138 case Type::LongTyID: {
139 // Calculate 011111111111111...
140 unsigned TypeBits = Ty->getPrimitiveSize()*8;
141 int64_t Val = INT64_MAX; // All ones
142 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
143 return ConstantSInt::get(Ty, Val);
146 case Type::UByteTyID:
147 case Type::UShortTyID:
149 case Type::ULongTyID: return getAllOnesValue(Ty);
155 // Static constructor to create the minimum constant for an integral type...
156 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
157 switch (Ty->getTypeID()) {
158 case Type::BoolTyID: return ConstantBool::False;
159 case Type::SByteTyID:
160 case Type::ShortTyID:
162 case Type::LongTyID: {
163 // Calculate 1111111111000000000000
164 unsigned TypeBits = Ty->getPrimitiveSize()*8;
165 int64_t Val = -1; // All ones
166 Val <<= TypeBits-1; // Shift over to the right spot
167 return ConstantSInt::get(Ty, Val);
170 case Type::UByteTyID:
171 case Type::UShortTyID:
173 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
179 // Static constructor to create an integral constant with all bits set
180 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
181 switch (Ty->getTypeID()) {
182 case Type::BoolTyID: return ConstantBool::True;
183 case Type::SByteTyID:
184 case Type::ShortTyID:
186 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
188 case Type::UByteTyID:
189 case Type::UShortTyID:
191 case Type::ULongTyID: {
192 // Calculate ~0 of the right type...
193 unsigned TypeBits = Ty->getPrimitiveSize()*8;
194 uint64_t Val = ~0ULL; // All ones
195 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
196 return ConstantUInt::get(Ty, Val);
202 bool ConstantUInt::isAllOnesValue() const {
203 unsigned TypeBits = getType()->getPrimitiveSize()*8;
204 uint64_t Val = ~0ULL; // All ones
205 Val >>= 64-TypeBits; // Shift out inappropriate bits
206 return getValue() == Val;
210 //===----------------------------------------------------------------------===//
211 // ConstantXXX Classes
212 //===----------------------------------------------------------------------===//
214 //===----------------------------------------------------------------------===//
215 // Normal Constructors
217 ConstantIntegral::ConstantIntegral(const Type *Ty, uint64_t V)
222 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy, V) {
225 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty, V) {
228 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
229 assert(Ty->isInteger() && Ty->isSigned() &&
230 "Illegal type for unsigned integer constant!");
231 assert(isValueValidForType(Ty, V) && "Value too large for type!");
234 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
235 assert(Ty->isInteger() && Ty->isUnsigned() &&
236 "Illegal type for unsigned integer constant!");
237 assert(isValueValidForType(Ty, V) && "Value too large for type!");
240 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
241 assert(isValueValidForType(Ty, V) && "Value too large for type!");
245 ConstantArray::ConstantArray(const ArrayType *T,
246 const std::vector<Constant*> &V) : Constant(T) {
247 Operands.reserve(V.size());
248 for (unsigned i = 0, e = V.size(); i != e; ++i) {
249 assert(V[i]->getType() == T->getElementType() ||
251 V[i]->getType()->getTypeID() == T->getElementType()->getTypeID()));
252 Operands.push_back(Use(V[i], this));
256 ConstantStruct::ConstantStruct(const StructType *T,
257 const std::vector<Constant*> &V) : Constant(T) {
258 assert(V.size() == T->getNumElements() &&
259 "Invalid initializer vector for constant structure");
260 Operands.reserve(V.size());
261 for (unsigned i = 0, e = V.size(); i != e; ++i) {
262 assert((V[i]->getType() == T->getElementType(i) ||
263 ((T->getElementType(i)->isAbstract() ||
264 V[i]->getType()->isAbstract()) &&
265 T->getElementType(i)->getTypeID() == V[i]->getType()->getTypeID())) &&
266 "Initializer for struct element doesn't match struct element type!");
267 Operands.push_back(Use(V[i], this));
271 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
272 : Constant(Ty), iType(Opcode) {
274 Operands.push_back(Use(C, this));
277 // Select instruction creation ctor
278 ConstantExpr::ConstantExpr(Constant *C, Constant *V1, Constant *V2)
279 : Constant(V1->getType()), iType(Instruction::Select) {
281 Operands.push_back(Use(C, this));
282 Operands.push_back(Use(V1, this));
283 Operands.push_back(Use(V2, this));
287 static bool isSetCC(unsigned Opcode) {
288 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
289 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
290 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
293 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
294 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
296 Operands.push_back(Use(C1, this));
297 Operands.push_back(Use(C2, this));
300 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
302 : Constant(DestTy), iType(Instruction::GetElementPtr) {
303 Operands.reserve(1+IdxList.size());
304 Operands.push_back(Use(C, this));
305 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
306 Operands.push_back(Use(IdxList[i], this));
309 /// ConstantExpr::get* - Return some common constants without having to
310 /// specify the full Instruction::OPCODE identifier.
312 Constant *ConstantExpr::getNeg(Constant *C) {
313 if (!C->getType()->isFloatingPoint())
314 return get(Instruction::Sub, getNullValue(C->getType()), C);
316 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
318 Constant *ConstantExpr::getNot(Constant *C) {
319 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
320 return get(Instruction::Xor, C,
321 ConstantIntegral::getAllOnesValue(C->getType()));
323 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
324 return get(Instruction::Add, C1, C2);
326 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
327 return get(Instruction::Sub, C1, C2);
329 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
330 return get(Instruction::Mul, C1, C2);
332 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
333 return get(Instruction::Div, C1, C2);
335 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
336 return get(Instruction::Rem, C1, C2);
338 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
339 return get(Instruction::And, C1, C2);
341 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
342 return get(Instruction::Or, C1, C2);
344 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
345 return get(Instruction::Xor, C1, C2);
347 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
348 return get(Instruction::SetEQ, C1, C2);
350 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
351 return get(Instruction::SetNE, C1, C2);
353 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
354 return get(Instruction::SetLT, C1, C2);
356 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
357 return get(Instruction::SetGT, C1, C2);
359 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
360 return get(Instruction::SetLE, C1, C2);
362 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
363 return get(Instruction::SetGE, C1, C2);
365 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
366 return get(Instruction::Shl, C1, C2);
368 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
369 return get(Instruction::Shr, C1, C2);
372 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
373 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
374 return getCast(getShr(getCast(C1,
375 C1->getType()->getUnsignedVersion()), C2), C1->getType());
378 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
379 if (C1->getType()->isSigned()) return getShr(C1, C2);
380 return getCast(getShr(getCast(C1,
381 C1->getType()->getSignedVersion()), C2), C1->getType());
385 //===----------------------------------------------------------------------===//
386 // classof implementations
388 bool ConstantIntegral::classof(const Constant *CPV) {
389 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
392 bool ConstantInt::classof(const Constant *CPV) {
393 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
395 bool ConstantSInt::classof(const Constant *CPV) {
396 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
398 bool ConstantUInt::classof(const Constant *CPV) {
399 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
401 bool ConstantFP::classof(const Constant *CPV) {
402 const Type *Ty = CPV->getType();
403 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
404 !isa<ConstantExpr>(CPV));
406 bool ConstantAggregateZero::classof(const Constant *CPV) {
407 return (isa<ArrayType>(CPV->getType()) || isa<StructType>(CPV->getType())) &&
410 bool ConstantArray::classof(const Constant *CPV) {
411 return isa<ArrayType>(CPV->getType()) && !CPV->isNullValue();
413 bool ConstantStruct::classof(const Constant *CPV) {
414 return isa<StructType>(CPV->getType()) && !CPV->isNullValue();
417 bool ConstantPointerNull::classof(const Constant *CPV) {
418 return !isa<GlobalValue>(CPV) && isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV) &&
419 CPV->getNumOperands() == 0;
423 //===----------------------------------------------------------------------===//
424 // isValueValidForType implementations
426 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
427 switch (Ty->getTypeID()) {
429 return false; // These can't be represented as integers!!!
431 case Type::SByteTyID:
432 return (Val <= INT8_MAX && Val >= INT8_MIN);
433 case Type::ShortTyID:
434 return (Val <= INT16_MAX && Val >= INT16_MIN);
436 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
438 return true; // This is the largest type...
442 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
443 switch (Ty->getTypeID()) {
445 return false; // These can't be represented as integers!!!
448 case Type::UByteTyID:
449 return (Val <= UINT8_MAX);
450 case Type::UShortTyID:
451 return (Val <= UINT16_MAX);
453 return (Val <= UINT32_MAX);
454 case Type::ULongTyID:
455 return true; // This is the largest type...
459 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
460 switch (Ty->getTypeID()) {
462 return false; // These can't be represented as floating point!
464 // TODO: Figure out how to test if a double can be cast to a float!
465 case Type::FloatTyID:
466 case Type::DoubleTyID:
467 return true; // This is the largest type...
471 //===----------------------------------------------------------------------===//
472 // replaceUsesOfWithOnConstant implementations
474 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
475 bool DisableChecking) {
476 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
478 std::vector<Constant*> Values;
479 Values.reserve(getValues().size()); // Build replacement array...
480 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
481 Constant *Val = cast<Constant>(getValues()[i]);
482 if (Val == From) Val = cast<Constant>(To);
483 Values.push_back(Val);
486 Constant *Replacement = ConstantArray::get(getType(), Values);
487 assert(Replacement != this && "I didn't contain From!");
489 // Everyone using this now uses the replacement...
491 uncheckedReplaceAllUsesWith(Replacement);
493 replaceAllUsesWith(Replacement);
495 // Delete the old constant!
499 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
500 bool DisableChecking) {
501 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
503 std::vector<Constant*> Values;
504 Values.reserve(getValues().size());
505 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
506 Constant *Val = cast<Constant>(getValues()[i]);
507 if (Val == From) Val = cast<Constant>(To);
508 Values.push_back(Val);
511 Constant *Replacement = ConstantStruct::get(getType(), Values);
512 assert(Replacement != this && "I didn't contain From!");
514 // Everyone using this now uses the replacement...
516 uncheckedReplaceAllUsesWith(Replacement);
518 replaceAllUsesWith(Replacement);
520 // Delete the old constant!
524 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
525 bool DisableChecking) {
526 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
527 Constant *To = cast<Constant>(ToV);
529 Constant *Replacement = 0;
530 if (getOpcode() == Instruction::GetElementPtr) {
531 std::vector<Constant*> Indices;
532 Constant *Pointer = getOperand(0);
533 Indices.reserve(getNumOperands()-1);
534 if (Pointer == From) Pointer = To;
536 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
537 Constant *Val = getOperand(i);
538 if (Val == From) Val = To;
539 Indices.push_back(Val);
541 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
542 } else if (getOpcode() == Instruction::Cast) {
543 assert(getOperand(0) == From && "Cast only has one use!");
544 Replacement = ConstantExpr::getCast(To, getType());
545 } else if (getOpcode() == Instruction::Select) {
546 Constant *C1 = getOperand(0);
547 Constant *C2 = getOperand(1);
548 Constant *C3 = getOperand(2);
549 if (C1 == From) C1 = To;
550 if (C2 == From) C2 = To;
551 if (C3 == From) C3 = To;
552 Replacement = ConstantExpr::getSelect(C1, C2, C3);
553 } else if (getNumOperands() == 2) {
554 Constant *C1 = getOperand(0);
555 Constant *C2 = getOperand(1);
556 if (C1 == From) C1 = To;
557 if (C2 == From) C2 = To;
558 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
560 assert(0 && "Unknown ConstantExpr type!");
564 assert(Replacement != this && "I didn't contain From!");
566 // Everyone using this now uses the replacement...
568 uncheckedReplaceAllUsesWith(Replacement);
570 replaceAllUsesWith(Replacement);
572 // Delete the old constant!
576 //===----------------------------------------------------------------------===//
577 // Factory Function Implementation
579 // ConstantCreator - A class that is used to create constants by
580 // ValueMap*. This class should be partially specialized if there is
581 // something strange that needs to be done to interface to the ctor for the
585 template<class ConstantClass, class TypeClass, class ValType>
586 struct ConstantCreator {
587 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
588 return new ConstantClass(Ty, V);
592 template<class ConstantClass, class TypeClass>
593 struct ConvertConstantType {
594 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
595 assert(0 && "This type cannot be converted!\n");
602 template<class ValType, class TypeClass, class ConstantClass>
603 class ValueMap : public AbstractTypeUser {
604 typedef std::pair<const TypeClass*, ValType> MapKey;
605 typedef std::map<MapKey, ConstantClass *> MapTy;
606 typedef typename MapTy::iterator MapIterator;
609 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
610 AbstractTypeMapTy AbstractTypeMap;
612 // getOrCreate - Return the specified constant from the map, creating it if
614 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
615 MapKey Lookup(Ty, V);
616 MapIterator I = Map.lower_bound(Lookup);
617 if (I != Map.end() && I->first == Lookup)
618 return I->second; // Is it in the map?
620 // If no preexisting value, create one now...
621 ConstantClass *Result =
622 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
625 /// FIXME: why does this assert fail when loading 176.gcc?
626 //assert(Result->getType() == Ty && "Type specified is not correct!");
627 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
629 // If the type of the constant is abstract, make sure that an entry exists
630 // for it in the AbstractTypeMap.
631 if (Ty->isAbstract()) {
632 typename AbstractTypeMapTy::iterator TI =
633 AbstractTypeMap.lower_bound(Ty);
635 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
636 // Add ourselves to the ATU list of the type.
637 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
639 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
645 void remove(ConstantClass *CP) {
646 // FIXME: This should not use a linear scan. If this gets to be a
647 // performance problem, someone should look at this.
648 MapIterator I = Map.begin();
649 for (MapIterator E = Map.end(); I != E && I->second != CP; ++I)
652 assert(I != Map.end() && "Constant not found in constant table!");
654 // Now that we found the entry, make sure this isn't the entry that
655 // the AbstractTypeMap points to.
656 const TypeClass *Ty = I->first.first;
657 if (Ty->isAbstract()) {
658 assert(AbstractTypeMap.count(Ty) &&
659 "Abstract type not in AbstractTypeMap?");
660 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
661 if (ATMEntryIt == I) {
662 // Yes, we are removing the representative entry for this type.
663 // See if there are any other entries of the same type.
664 MapIterator TmpIt = ATMEntryIt;
666 // First check the entry before this one...
667 if (TmpIt != Map.begin()) {
669 if (TmpIt->first.first != Ty) // Not the same type, move back...
673 // If we didn't find the same type, try to move forward...
674 if (TmpIt == ATMEntryIt) {
676 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
677 --TmpIt; // No entry afterwards with the same type
680 // If there is another entry in the map of the same abstract type,
681 // update the AbstractTypeMap entry now.
682 if (TmpIt != ATMEntryIt) {
685 // Otherwise, we are removing the last instance of this type
686 // from the table. Remove from the ATM, and from user list.
687 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
688 AbstractTypeMap.erase(Ty);
696 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
697 typename AbstractTypeMapTy::iterator I =
698 AbstractTypeMap.find(cast<TypeClass>(OldTy));
700 assert(I != AbstractTypeMap.end() &&
701 "Abstract type not in AbstractTypeMap?");
703 // Convert a constant at a time until the last one is gone. The last one
704 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
705 // eliminated eventually.
707 ConvertConstantType<ConstantClass,
708 TypeClass>::convert(I->second->second,
709 cast<TypeClass>(NewTy));
711 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
712 } while (I != AbstractTypeMap.end());
715 // If the type became concrete without being refined to any other existing
716 // type, we just remove ourselves from the ATU list.
717 void typeBecameConcrete(const DerivedType *AbsTy) {
718 AbsTy->removeAbstractTypeUser(this);
722 std::cerr << "Constant.cpp: ValueMap\n";
729 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
731 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
732 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
734 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
735 return SIntConstants.getOrCreate(Ty, V);
738 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
739 return UIntConstants.getOrCreate(Ty, V);
742 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
743 assert(V <= 127 && "Can only be used with very small positive constants!");
744 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
745 return ConstantUInt::get(Ty, V);
748 //---- ConstantFP::get() implementation...
752 struct ConstantCreator<ConstantFP, Type, uint64_t> {
753 static ConstantFP *create(const Type *Ty, uint64_t V) {
754 assert(Ty == Type::DoubleTy);
760 return new ConstantFP(Ty, T.F);
764 struct ConstantCreator<ConstantFP, Type, uint32_t> {
765 static ConstantFP *create(const Type *Ty, uint32_t V) {
766 assert(Ty == Type::FloatTy);
772 return new ConstantFP(Ty, T.F);
777 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
778 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
780 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
781 if (Ty == Type::FloatTy) {
782 // Force the value through memory to normalize it.
788 return FloatConstants.getOrCreate(Ty, T.I);
790 assert(Ty == Type::DoubleTy);
796 return DoubleConstants.getOrCreate(Ty, T.I);
800 //---- ConstantAggregateZero::get() implementation...
803 // ConstantAggregateZero does not take extra "value" argument...
804 template<class ValType>
805 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
806 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
807 return new ConstantAggregateZero(Ty);
812 struct ConvertConstantType<ConstantAggregateZero, Type> {
813 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
814 // Make everyone now use a constant of the new type...
815 Constant *New = ConstantAggregateZero::get(NewTy);
816 assert(New != OldC && "Didn't replace constant??");
817 OldC->uncheckedReplaceAllUsesWith(New);
818 OldC->destroyConstant(); // This constant is now dead, destroy it.
823 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
825 Constant *ConstantAggregateZero::get(const Type *Ty) {
826 return AggZeroConstants.getOrCreate(Ty, 0);
829 // destroyConstant - Remove the constant from the constant table...
831 void ConstantAggregateZero::destroyConstant() {
832 AggZeroConstants.remove(this);
833 destroyConstantImpl();
836 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
837 bool DisableChecking) {
838 assert(0 && "No uses!");
844 //---- ConstantArray::get() implementation...
848 struct ConvertConstantType<ConstantArray, ArrayType> {
849 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
850 // Make everyone now use a constant of the new type...
851 std::vector<Constant*> C;
852 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
853 C.push_back(cast<Constant>(OldC->getOperand(i)));
854 Constant *New = ConstantArray::get(NewTy, C);
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<std::vector<Constant*>, ArrayType,
863 ConstantArray> ArrayConstants;
865 Constant *ConstantArray::get(const ArrayType *Ty,
866 const std::vector<Constant*> &V) {
867 // If this is an all-zero array, return a ConstantAggregateZero object
870 if (!C->isNullValue())
871 return ArrayConstants.getOrCreate(Ty, V);
872 for (unsigned i = 1, e = V.size(); i != e; ++i)
874 return ArrayConstants.getOrCreate(Ty, V);
876 return ConstantAggregateZero::get(Ty);
879 // destroyConstant - Remove the constant from the constant table...
881 void ConstantArray::destroyConstant() {
882 ArrayConstants.remove(this);
883 destroyConstantImpl();
886 // ConstantArray::get(const string&) - Return an array that is initialized to
887 // contain the specified string. A null terminator is added to the specified
888 // string so that it may be used in a natural way...
890 Constant *ConstantArray::get(const std::string &Str) {
891 std::vector<Constant*> ElementVals;
893 for (unsigned i = 0; i < Str.length(); ++i)
894 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
896 // Add a null terminator to the string...
897 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
899 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
900 return ConstantArray::get(ATy, ElementVals);
903 /// isString - This method returns true if the array is an array of sbyte or
904 /// ubyte, and if the elements of the array are all ConstantInt's.
905 bool ConstantArray::isString() const {
906 // Check the element type for sbyte or ubyte...
907 if (getType()->getElementType() != Type::UByteTy &&
908 getType()->getElementType() != Type::SByteTy)
910 // Check the elements to make sure they are all integers, not constant
912 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
913 if (!isa<ConstantInt>(getOperand(i)))
918 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
919 // then this method converts the array to an std::string and returns it.
920 // Otherwise, it asserts out.
922 std::string ConstantArray::getAsString() const {
923 assert(isString() && "Not a string!");
925 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
926 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
931 //---- ConstantStruct::get() implementation...
936 struct ConvertConstantType<ConstantStruct, StructType> {
937 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
938 // Make everyone now use a constant of the new type...
939 std::vector<Constant*> C;
940 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
941 C.push_back(cast<Constant>(OldC->getOperand(i)));
942 Constant *New = ConstantStruct::get(NewTy, C);
943 assert(New != OldC && "Didn't replace constant??");
945 OldC->uncheckedReplaceAllUsesWith(New);
946 OldC->destroyConstant(); // This constant is now dead, destroy it.
951 static ValueMap<std::vector<Constant*>, StructType,
952 ConstantStruct> StructConstants;
954 Constant *ConstantStruct::get(const StructType *Ty,
955 const std::vector<Constant*> &V) {
956 // Create a ConstantAggregateZero value if all elements are zeros...
957 for (unsigned i = 0, e = V.size(); i != e; ++i)
958 if (!V[i]->isNullValue())
959 return StructConstants.getOrCreate(Ty, V);
961 return ConstantAggregateZero::get(Ty);
964 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
965 std::vector<const Type*> StructEls;
966 StructEls.reserve(V.size());
967 for (unsigned i = 0, e = V.size(); i != e; ++i)
968 StructEls.push_back(V[i]->getType());
969 return get(StructType::get(StructEls), V);
972 // destroyConstant - Remove the constant from the constant table...
974 void ConstantStruct::destroyConstant() {
975 StructConstants.remove(this);
976 destroyConstantImpl();
979 //---- ConstantPointerNull::get() implementation...
983 // ConstantPointerNull does not take extra "value" argument...
984 template<class ValType>
985 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
986 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
987 return new ConstantPointerNull(Ty);
992 struct ConvertConstantType<ConstantPointerNull, PointerType> {
993 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
994 // Make everyone now use a constant of the new type...
995 Constant *New = ConstantPointerNull::get(NewTy);
996 assert(New != OldC && "Didn't replace constant??");
997 OldC->uncheckedReplaceAllUsesWith(New);
998 OldC->destroyConstant(); // This constant is now dead, destroy it.
1003 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
1005 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1006 return NullPtrConstants.getOrCreate(Ty, 0);
1009 // destroyConstant - Remove the constant from the constant table...
1011 void ConstantPointerNull::destroyConstant() {
1012 NullPtrConstants.remove(this);
1013 destroyConstantImpl();
1017 //---- ConstantExpr::get() implementations...
1019 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1023 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1024 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1025 if (V.first == Instruction::Cast)
1026 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
1027 if ((V.first >= Instruction::BinaryOpsBegin &&
1028 V.first < Instruction::BinaryOpsEnd) ||
1029 V.first == Instruction::Shl || V.first == Instruction::Shr)
1030 return new ConstantExpr(V.first, V.second[0], V.second[1]);
1031 if (V.first == Instruction::Select)
1032 return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
1034 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1036 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1037 return new ConstantExpr(V.second[0], IdxList, Ty);
1042 struct ConvertConstantType<ConstantExpr, Type> {
1043 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1045 switch (OldC->getOpcode()) {
1046 case Instruction::Cast:
1047 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1049 case Instruction::Select:
1050 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1051 OldC->getOperand(1),
1052 OldC->getOperand(2));
1054 case Instruction::Shl:
1055 case Instruction::Shr:
1056 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1057 OldC->getOperand(0), OldC->getOperand(1));
1060 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1061 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1062 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1063 OldC->getOperand(1));
1065 case Instruction::GetElementPtr:
1066 // Make everyone now use a constant of the new type...
1067 std::vector<Constant*> C;
1068 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1069 C.push_back(cast<Constant>(OldC->getOperand(i)));
1070 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1074 assert(New != OldC && "Didn't replace constant??");
1075 OldC->uncheckedReplaceAllUsesWith(New);
1076 OldC->destroyConstant(); // This constant is now dead, destroy it.
1079 } // end namespace llvm
1082 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1084 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1085 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1087 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1088 return FC; // Fold a few common cases...
1090 // Look up the constant in the table first to ensure uniqueness
1091 std::vector<Constant*> argVec(1, C);
1092 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1093 return ExprConstants.getOrCreate(Ty, Key);
1096 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1097 assert(C->getType()->isInteger() && Ty->isInteger() &&
1098 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1099 "This is an illegal sign extension!");
1100 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1101 return ConstantExpr::getCast(C, Ty);
1104 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1105 assert(C->getType()->isInteger() && Ty->isInteger() &&
1106 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1107 "This is an illegal zero extension!");
1108 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1109 return ConstantExpr::getCast(C, Ty);
1112 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1113 Constant *C1, Constant *C2) {
1114 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1115 return getShiftTy(ReqTy, Opcode, C1, C2);
1116 // Check the operands for consistency first
1117 assert((Opcode >= Instruction::BinaryOpsBegin &&
1118 Opcode < Instruction::BinaryOpsEnd) &&
1119 "Invalid opcode in binary constant expression");
1120 assert(C1->getType() == C2->getType() &&
1121 "Operand types in binary constant expression should match");
1123 if (ReqTy == C1->getType())
1124 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1125 return FC; // Fold a few common cases...
1127 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1128 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1129 return ExprConstants.getOrCreate(ReqTy, Key);
1132 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1133 Constant *V1, Constant *V2) {
1134 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1135 assert(V1->getType() == V2->getType() && "Select value types must match!");
1136 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1138 if (ReqTy == V1->getType())
1139 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1140 return SC; // Fold common cases
1142 std::vector<Constant*> argVec(3, C);
1145 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1146 return ExprConstants.getOrCreate(ReqTy, Key);
1149 /// getShiftTy - Return a shift left or shift right constant expr
1150 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1151 Constant *C1, Constant *C2) {
1152 // Check the operands for consistency first
1153 assert((Opcode == Instruction::Shl ||
1154 Opcode == Instruction::Shr) &&
1155 "Invalid opcode in binary constant expression");
1156 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1157 "Invalid operand types for Shift constant expr!");
1159 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1160 return FC; // Fold a few common cases...
1162 // Look up the constant in the table first to ensure uniqueness
1163 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1164 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1165 return ExprConstants.getOrCreate(ReqTy, Key);
1169 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1170 const std::vector<Constant*> &IdxList) {
1171 assert(GetElementPtrInst::getIndexedType(C->getType(),
1172 std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1173 "GEP indices invalid!");
1175 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1176 return FC; // Fold a few common cases...
1178 assert(isa<PointerType>(C->getType()) &&
1179 "Non-pointer type for constant GetElementPtr expression");
1180 // Look up the constant in the table first to ensure uniqueness
1181 std::vector<Constant*> argVec(1, C);
1182 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1183 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1184 return ExprConstants.getOrCreate(ReqTy, Key);
1187 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1188 const std::vector<Constant*> &IdxList){
1189 // Get the result type of the getelementptr!
1190 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1192 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1194 assert(Ty && "GEP indices invalid!");
1195 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1199 // destroyConstant - Remove the constant from the constant table...
1201 void ConstantExpr::destroyConstant() {
1202 ExprConstants.remove(this);
1203 destroyConstantImpl();
1206 const char *ConstantExpr::getOpcodeName() const {
1207 return Instruction::getOpcodeName(getOpcode());