1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "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, ConstantExprVal), 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(), ConstantExprVal), 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(), ConstantExprVal),
297 Operands.push_back(Use(C1, this));
298 Operands.push_back(Use(C2, this));
301 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
303 : Constant(DestTy, ConstantExprVal), iType(Instruction::GetElementPtr) {
304 Operands.reserve(1+IdxList.size());
305 Operands.push_back(Use(C, this));
306 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
307 Operands.push_back(Use(IdxList[i], this));
310 /// ConstantExpr::get* - Return some common constants without having to
311 /// specify the full Instruction::OPCODE identifier.
313 Constant *ConstantExpr::getNeg(Constant *C) {
314 if (!C->getType()->isFloatingPoint())
315 return get(Instruction::Sub, getNullValue(C->getType()), C);
317 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
319 Constant *ConstantExpr::getNot(Constant *C) {
320 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
321 return get(Instruction::Xor, C,
322 ConstantIntegral::getAllOnesValue(C->getType()));
324 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
325 return get(Instruction::Add, C1, C2);
327 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
328 return get(Instruction::Sub, C1, C2);
330 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
331 return get(Instruction::Mul, C1, C2);
333 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
334 return get(Instruction::Div, C1, C2);
336 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
337 return get(Instruction::Rem, C1, C2);
339 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
340 return get(Instruction::And, C1, C2);
342 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
343 return get(Instruction::Or, C1, C2);
345 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
346 return get(Instruction::Xor, C1, C2);
348 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
349 return get(Instruction::SetEQ, C1, C2);
351 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
352 return get(Instruction::SetNE, C1, C2);
354 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
355 return get(Instruction::SetLT, C1, C2);
357 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
358 return get(Instruction::SetGT, C1, C2);
360 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
361 return get(Instruction::SetLE, C1, C2);
363 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
364 return get(Instruction::SetGE, C1, C2);
366 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
367 return get(Instruction::Shl, C1, C2);
369 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
370 return get(Instruction::Shr, C1, C2);
373 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
374 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
375 return getCast(getShr(getCast(C1,
376 C1->getType()->getUnsignedVersion()), C2), C1->getType());
379 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
380 if (C1->getType()->isSigned()) return getShr(C1, C2);
381 return getCast(getShr(getCast(C1,
382 C1->getType()->getSignedVersion()), C2), C1->getType());
386 //===----------------------------------------------------------------------===//
387 // isValueValidForType implementations
389 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
390 switch (Ty->getTypeID()) {
392 return false; // These can't be represented as integers!!!
394 case Type::SByteTyID:
395 return (Val <= INT8_MAX && Val >= INT8_MIN);
396 case Type::ShortTyID:
397 return (Val <= INT16_MAX && Val >= INT16_MIN);
399 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
401 return true; // This is the largest type...
405 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
406 switch (Ty->getTypeID()) {
408 return false; // These can't be represented as integers!!!
411 case Type::UByteTyID:
412 return (Val <= UINT8_MAX);
413 case Type::UShortTyID:
414 return (Val <= UINT16_MAX);
416 return (Val <= UINT32_MAX);
417 case Type::ULongTyID:
418 return true; // This is the largest type...
422 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
423 switch (Ty->getTypeID()) {
425 return false; // These can't be represented as floating point!
427 // TODO: Figure out how to test if a double can be cast to a float!
428 case Type::FloatTyID:
429 case Type::DoubleTyID:
430 return true; // This is the largest type...
434 //===----------------------------------------------------------------------===//
435 // replaceUsesOfWithOnConstant implementations
437 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
438 bool DisableChecking) {
439 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
441 std::vector<Constant*> Values;
442 Values.reserve(getNumOperands()); // Build replacement array...
443 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
444 Constant *Val = getOperand(i);
445 if (Val == From) Val = cast<Constant>(To);
446 Values.push_back(Val);
449 Constant *Replacement = ConstantArray::get(getType(), Values);
450 assert(Replacement != this && "I didn't contain From!");
452 // Everyone using this now uses the replacement...
454 uncheckedReplaceAllUsesWith(Replacement);
456 replaceAllUsesWith(Replacement);
458 // Delete the old constant!
462 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
463 bool DisableChecking) {
464 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
466 std::vector<Constant*> Values;
467 Values.reserve(getNumOperands()); // Build replacement array...
468 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
469 Constant *Val = getOperand(i);
470 if (Val == From) Val = cast<Constant>(To);
471 Values.push_back(Val);
474 Constant *Replacement = ConstantStruct::get(getType(), Values);
475 assert(Replacement != this && "I didn't contain From!");
477 // Everyone using this now uses the replacement...
479 uncheckedReplaceAllUsesWith(Replacement);
481 replaceAllUsesWith(Replacement);
483 // Delete the old constant!
487 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
488 bool DisableChecking) {
489 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
490 Constant *To = cast<Constant>(ToV);
492 Constant *Replacement = 0;
493 if (getOpcode() == Instruction::GetElementPtr) {
494 std::vector<Constant*> Indices;
495 Constant *Pointer = getOperand(0);
496 Indices.reserve(getNumOperands()-1);
497 if (Pointer == From) Pointer = To;
499 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
500 Constant *Val = getOperand(i);
501 if (Val == From) Val = To;
502 Indices.push_back(Val);
504 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
505 } else if (getOpcode() == Instruction::Cast) {
506 assert(getOperand(0) == From && "Cast only has one use!");
507 Replacement = ConstantExpr::getCast(To, getType());
508 } else if (getOpcode() == Instruction::Select) {
509 Constant *C1 = getOperand(0);
510 Constant *C2 = getOperand(1);
511 Constant *C3 = getOperand(2);
512 if (C1 == From) C1 = To;
513 if (C2 == From) C2 = To;
514 if (C3 == From) C3 = To;
515 Replacement = ConstantExpr::getSelect(C1, C2, C3);
516 } else if (getNumOperands() == 2) {
517 Constant *C1 = getOperand(0);
518 Constant *C2 = getOperand(1);
519 if (C1 == From) C1 = To;
520 if (C2 == From) C2 = To;
521 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
523 assert(0 && "Unknown ConstantExpr type!");
527 assert(Replacement != this && "I didn't contain From!");
529 // Everyone using this now uses the replacement...
531 uncheckedReplaceAllUsesWith(Replacement);
533 replaceAllUsesWith(Replacement);
535 // Delete the old constant!
539 //===----------------------------------------------------------------------===//
540 // Factory Function Implementation
542 // ConstantCreator - A class that is used to create constants by
543 // ValueMap*. This class should be partially specialized if there is
544 // something strange that needs to be done to interface to the ctor for the
548 template<class ConstantClass, class TypeClass, class ValType>
549 struct ConstantCreator {
550 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
551 return new ConstantClass(Ty, V);
555 template<class ConstantClass, class TypeClass>
556 struct ConvertConstantType {
557 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
558 assert(0 && "This type cannot be converted!\n");
565 template<class ValType, class TypeClass, class ConstantClass>
566 class ValueMap : public AbstractTypeUser {
567 typedef std::pair<const TypeClass*, ValType> MapKey;
568 typedef std::map<MapKey, ConstantClass *> MapTy;
569 typedef typename MapTy::iterator MapIterator;
572 typedef std::map<const TypeClass*, MapIterator> AbstractTypeMapTy;
573 AbstractTypeMapTy AbstractTypeMap;
575 // getOrCreate - Return the specified constant from the map, creating it if
577 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
578 MapKey Lookup(Ty, V);
579 MapIterator I = Map.lower_bound(Lookup);
580 if (I != Map.end() && I->first == Lookup)
581 return I->second; // Is it in the map?
583 // If no preexisting value, create one now...
584 ConstantClass *Result =
585 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
588 /// FIXME: why does this assert fail when loading 176.gcc?
589 //assert(Result->getType() == Ty && "Type specified is not correct!");
590 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
592 // If the type of the constant is abstract, make sure that an entry exists
593 // for it in the AbstractTypeMap.
594 if (Ty->isAbstract()) {
595 typename AbstractTypeMapTy::iterator TI =
596 AbstractTypeMap.lower_bound(Ty);
598 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
599 // Add ourselves to the ATU list of the type.
600 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
602 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
608 void remove(ConstantClass *CP) {
609 MapIterator I = Map.find(MapKey((TypeClass*)CP->getRawType(),
611 if (I == Map.end() || I->second != CP) {
612 // FIXME: This should not use a linear scan. If this gets to be a
613 // performance problem, someone should look at this.
614 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
618 assert(I != Map.end() && "Constant not found in constant table!");
619 assert(I->second == CP && "Didn't find correct element?");
621 // Now that we found the entry, make sure this isn't the entry that
622 // the AbstractTypeMap points to.
623 const TypeClass *Ty = I->first.first;
624 if (Ty->isAbstract()) {
625 assert(AbstractTypeMap.count(Ty) &&
626 "Abstract type not in AbstractTypeMap?");
627 MapIterator &ATMEntryIt = AbstractTypeMap[Ty];
628 if (ATMEntryIt == I) {
629 // Yes, we are removing the representative entry for this type.
630 // See if there are any other entries of the same type.
631 MapIterator TmpIt = ATMEntryIt;
633 // First check the entry before this one...
634 if (TmpIt != Map.begin()) {
636 if (TmpIt->first.first != Ty) // Not the same type, move back...
640 // If we didn't find the same type, try to move forward...
641 if (TmpIt == ATMEntryIt) {
643 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
644 --TmpIt; // No entry afterwards with the same type
647 // If there is another entry in the map of the same abstract type,
648 // update the AbstractTypeMap entry now.
649 if (TmpIt != ATMEntryIt) {
652 // Otherwise, we are removing the last instance of this type
653 // from the table. Remove from the ATM, and from user list.
654 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
655 AbstractTypeMap.erase(Ty);
663 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
664 typename AbstractTypeMapTy::iterator I =
665 AbstractTypeMap.find(cast<TypeClass>(OldTy));
667 assert(I != AbstractTypeMap.end() &&
668 "Abstract type not in AbstractTypeMap?");
670 // Convert a constant at a time until the last one is gone. The last one
671 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
672 // eliminated eventually.
674 ConvertConstantType<ConstantClass,
675 TypeClass>::convert(I->second->second,
676 cast<TypeClass>(NewTy));
678 I = AbstractTypeMap.find(cast<TypeClass>(OldTy));
679 } while (I != AbstractTypeMap.end());
682 // If the type became concrete without being refined to any other existing
683 // type, we just remove ourselves from the ATU list.
684 void typeBecameConcrete(const DerivedType *AbsTy) {
685 AbsTy->removeAbstractTypeUser(this);
689 std::cerr << "Constant.cpp: ValueMap\n";
694 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
696 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
697 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
699 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
700 return SIntConstants.getOrCreate(Ty, V);
703 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
704 return UIntConstants.getOrCreate(Ty, V);
707 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
708 assert(V <= 127 && "Can only be used with very small positive constants!");
709 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
710 return ConstantUInt::get(Ty, V);
713 //---- ConstantFP::get() implementation...
717 struct ConstantCreator<ConstantFP, Type, uint64_t> {
718 static ConstantFP *create(const Type *Ty, uint64_t V) {
719 assert(Ty == Type::DoubleTy);
725 return new ConstantFP(Ty, T.F);
729 struct ConstantCreator<ConstantFP, Type, uint32_t> {
730 static ConstantFP *create(const Type *Ty, uint32_t V) {
731 assert(Ty == Type::FloatTy);
737 return new ConstantFP(Ty, T.F);
742 static ValueMap<uint64_t, Type, ConstantFP> DoubleConstants;
743 static ValueMap<uint32_t, Type, ConstantFP> FloatConstants;
745 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
746 if (Ty == Type::FloatTy) {
747 // Force the value through memory to normalize it.
753 return FloatConstants.getOrCreate(Ty, T.I);
755 assert(Ty == Type::DoubleTy);
761 return DoubleConstants.getOrCreate(Ty, T.I);
765 //---- ConstantAggregateZero::get() implementation...
768 // ConstantAggregateZero does not take extra "value" argument...
769 template<class ValType>
770 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
771 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
772 return new ConstantAggregateZero(Ty);
777 struct ConvertConstantType<ConstantAggregateZero, Type> {
778 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
779 // Make everyone now use a constant of the new type...
780 Constant *New = ConstantAggregateZero::get(NewTy);
781 assert(New != OldC && "Didn't replace constant??");
782 OldC->uncheckedReplaceAllUsesWith(New);
783 OldC->destroyConstant(); // This constant is now dead, destroy it.
788 static ValueMap<char, Type, ConstantAggregateZero> AggZeroConstants;
790 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
792 Constant *ConstantAggregateZero::get(const Type *Ty) {
793 return AggZeroConstants.getOrCreate(Ty, 0);
796 // destroyConstant - Remove the constant from the constant table...
798 void ConstantAggregateZero::destroyConstant() {
799 AggZeroConstants.remove(this);
800 destroyConstantImpl();
803 void ConstantAggregateZero::replaceUsesOfWithOnConstant(Value *From, Value *To,
804 bool DisableChecking) {
805 assert(0 && "No uses!");
811 //---- ConstantArray::get() implementation...
815 struct ConvertConstantType<ConstantArray, ArrayType> {
816 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
817 // Make everyone now use a constant of the new type...
818 std::vector<Constant*> C;
819 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
820 C.push_back(cast<Constant>(OldC->getOperand(i)));
821 Constant *New = ConstantArray::get(NewTy, C);
822 assert(New != OldC && "Didn't replace constant??");
823 OldC->uncheckedReplaceAllUsesWith(New);
824 OldC->destroyConstant(); // This constant is now dead, destroy it.
829 static std::vector<Constant*> getValType(ConstantArray *CA) {
830 std::vector<Constant*> Elements;
831 Elements.reserve(CA->getNumOperands());
832 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
833 Elements.push_back(cast<Constant>(CA->getOperand(i)));
837 static ValueMap<std::vector<Constant*>, ArrayType,
838 ConstantArray> ArrayConstants;
840 Constant *ConstantArray::get(const ArrayType *Ty,
841 const std::vector<Constant*> &V) {
842 // If this is an all-zero array, return a ConstantAggregateZero object
845 if (!C->isNullValue())
846 return ArrayConstants.getOrCreate(Ty, V);
847 for (unsigned i = 1, e = V.size(); i != e; ++i)
849 return ArrayConstants.getOrCreate(Ty, V);
851 return ConstantAggregateZero::get(Ty);
854 // destroyConstant - Remove the constant from the constant table...
856 void ConstantArray::destroyConstant() {
857 ArrayConstants.remove(this);
858 destroyConstantImpl();
861 // ConstantArray::get(const string&) - Return an array that is initialized to
862 // contain the specified string. A null terminator is added to the specified
863 // string so that it may be used in a natural way...
865 Constant *ConstantArray::get(const std::string &Str) {
866 std::vector<Constant*> ElementVals;
868 for (unsigned i = 0; i < Str.length(); ++i)
869 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
871 // Add a null terminator to the string...
872 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
874 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
875 return ConstantArray::get(ATy, ElementVals);
878 /// isString - This method returns true if the array is an array of sbyte or
879 /// ubyte, and if the elements of the array are all ConstantInt's.
880 bool ConstantArray::isString() const {
881 // Check the element type for sbyte or ubyte...
882 if (getType()->getElementType() != Type::UByteTy &&
883 getType()->getElementType() != Type::SByteTy)
885 // Check the elements to make sure they are all integers, not constant
887 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
888 if (!isa<ConstantInt>(getOperand(i)))
893 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
894 // then this method converts the array to an std::string and returns it.
895 // Otherwise, it asserts out.
897 std::string ConstantArray::getAsString() const {
898 assert(isString() && "Not a string!");
900 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
901 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
906 //---- ConstantStruct::get() implementation...
911 struct ConvertConstantType<ConstantStruct, StructType> {
912 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
913 // Make everyone now use a constant of the new type...
914 std::vector<Constant*> C;
915 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
916 C.push_back(cast<Constant>(OldC->getOperand(i)));
917 Constant *New = ConstantStruct::get(NewTy, C);
918 assert(New != OldC && "Didn't replace constant??");
920 OldC->uncheckedReplaceAllUsesWith(New);
921 OldC->destroyConstant(); // This constant is now dead, destroy it.
926 static ValueMap<std::vector<Constant*>, StructType,
927 ConstantStruct> StructConstants;
929 static std::vector<Constant*> getValType(ConstantStruct *CS) {
930 std::vector<Constant*> Elements;
931 Elements.reserve(CS->getNumOperands());
932 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
933 Elements.push_back(cast<Constant>(CS->getOperand(i)));
937 Constant *ConstantStruct::get(const StructType *Ty,
938 const std::vector<Constant*> &V) {
939 // Create a ConstantAggregateZero value if all elements are zeros...
940 for (unsigned i = 0, e = V.size(); i != e; ++i)
941 if (!V[i]->isNullValue())
942 return StructConstants.getOrCreate(Ty, V);
944 return ConstantAggregateZero::get(Ty);
947 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
948 std::vector<const Type*> StructEls;
949 StructEls.reserve(V.size());
950 for (unsigned i = 0, e = V.size(); i != e; ++i)
951 StructEls.push_back(V[i]->getType());
952 return get(StructType::get(StructEls), V);
955 // destroyConstant - Remove the constant from the constant table...
957 void ConstantStruct::destroyConstant() {
958 StructConstants.remove(this);
959 destroyConstantImpl();
962 //---- ConstantPointerNull::get() implementation...
966 // ConstantPointerNull does not take extra "value" argument...
967 template<class ValType>
968 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
969 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
970 return new ConstantPointerNull(Ty);
975 struct ConvertConstantType<ConstantPointerNull, PointerType> {
976 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
977 // Make everyone now use a constant of the new type...
978 Constant *New = ConstantPointerNull::get(NewTy);
979 assert(New != OldC && "Didn't replace constant??");
980 OldC->uncheckedReplaceAllUsesWith(New);
981 OldC->destroyConstant(); // This constant is now dead, destroy it.
986 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
988 static char getValType(ConstantPointerNull *) {
993 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
994 return NullPtrConstants.getOrCreate(Ty, 0);
997 // destroyConstant - Remove the constant from the constant table...
999 void ConstantPointerNull::destroyConstant() {
1000 NullPtrConstants.remove(this);
1001 destroyConstantImpl();
1005 //---- ConstantExpr::get() implementations...
1007 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1011 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1012 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1013 if (V.first == Instruction::Cast)
1014 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
1015 if ((V.first >= Instruction::BinaryOpsBegin &&
1016 V.first < Instruction::BinaryOpsEnd) ||
1017 V.first == Instruction::Shl || V.first == Instruction::Shr)
1018 return new ConstantExpr(V.first, V.second[0], V.second[1]);
1019 if (V.first == Instruction::Select)
1020 return new ConstantExpr(V.second[0], V.second[1], V.second[2]);
1022 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1024 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1025 return new ConstantExpr(V.second[0], IdxList, Ty);
1030 struct ConvertConstantType<ConstantExpr, Type> {
1031 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1033 switch (OldC->getOpcode()) {
1034 case Instruction::Cast:
1035 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1037 case Instruction::Select:
1038 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1039 OldC->getOperand(1),
1040 OldC->getOperand(2));
1042 case Instruction::Shl:
1043 case Instruction::Shr:
1044 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1045 OldC->getOperand(0), OldC->getOperand(1));
1048 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1049 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1050 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1051 OldC->getOperand(1));
1053 case Instruction::GetElementPtr:
1054 // Make everyone now use a constant of the new type...
1055 std::vector<Constant*> C;
1056 for (unsigned i = 1, e = OldC->getNumOperands(); i != e; ++i)
1057 C.push_back(cast<Constant>(OldC->getOperand(i)));
1058 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), C);
1062 assert(New != OldC && "Didn't replace constant??");
1063 OldC->uncheckedReplaceAllUsesWith(New);
1064 OldC->destroyConstant(); // This constant is now dead, destroy it.
1067 } // end namespace llvm
1070 static ExprMapKeyType getValType(ConstantExpr *CE) {
1071 std::vector<Constant*> Operands;
1072 Operands.reserve(CE->getNumOperands());
1073 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1074 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1075 return ExprMapKeyType(CE->getOpcode(), Operands);
1078 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
1080 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1081 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1083 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1084 return FC; // Fold a few common cases...
1086 // Look up the constant in the table first to ensure uniqueness
1087 std::vector<Constant*> argVec(1, C);
1088 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1089 return ExprConstants.getOrCreate(Ty, Key);
1092 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1093 assert(C->getType()->isInteger() && Ty->isInteger() &&
1094 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1095 "This is an illegal sign extension!");
1096 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1097 return ConstantExpr::getCast(C, Ty);
1100 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1101 assert(C->getType()->isInteger() && Ty->isInteger() &&
1102 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1103 "This is an illegal zero extension!");
1104 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1105 return ConstantExpr::getCast(C, Ty);
1108 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1109 Constant *C1, Constant *C2) {
1110 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1111 return getShiftTy(ReqTy, Opcode, C1, C2);
1112 // Check the operands for consistency first
1113 assert((Opcode >= Instruction::BinaryOpsBegin &&
1114 Opcode < Instruction::BinaryOpsEnd) &&
1115 "Invalid opcode in binary constant expression");
1116 assert(C1->getType() == C2->getType() &&
1117 "Operand types in binary constant expression should match");
1119 if (ReqTy == C1->getType() || (Instruction::isRelational(Opcode) &&
1120 ReqTy == Type::BoolTy))
1121 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1122 return FC; // Fold a few common cases...
1124 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1125 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1126 return ExprConstants.getOrCreate(ReqTy, Key);
1129 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1132 case Instruction::Add: case Instruction::Sub:
1133 case Instruction::Mul: case Instruction::Div:
1134 case Instruction::Rem:
1135 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1136 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint()) &&
1137 "Tried to create an arithmetic operation on a non-arithmetic type!");
1139 case Instruction::And:
1140 case Instruction::Or:
1141 case Instruction::Xor:
1142 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1143 assert(C1->getType()->isIntegral() &&
1144 "Tried to create an logical operation on a non-integral type!");
1146 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1147 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1148 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1150 case Instruction::Shl:
1151 case Instruction::Shr:
1152 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1153 assert(C1->getType()->isInteger() &&
1154 "Tried to create a shift operation on a non-integer type!");
1161 if (Instruction::isRelational(Opcode))
1162 return getTy(Type::BoolTy, Opcode, C1, C2);
1164 return getTy(C1->getType(), Opcode, C1, C2);
1167 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1168 Constant *V1, Constant *V2) {
1169 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1170 assert(V1->getType() == V2->getType() && "Select value types must match!");
1171 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1173 if (ReqTy == V1->getType())
1174 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1175 return SC; // Fold common cases
1177 std::vector<Constant*> argVec(3, C);
1180 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1181 return ExprConstants.getOrCreate(ReqTy, Key);
1184 /// getShiftTy - Return a shift left or shift right constant expr
1185 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1186 Constant *C1, Constant *C2) {
1187 // Check the operands for consistency first
1188 assert((Opcode == Instruction::Shl ||
1189 Opcode == Instruction::Shr) &&
1190 "Invalid opcode in binary constant expression");
1191 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1192 "Invalid operand types for Shift constant expr!");
1194 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1195 return FC; // Fold a few common cases...
1197 // Look up the constant in the table first to ensure uniqueness
1198 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1199 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1200 return ExprConstants.getOrCreate(ReqTy, Key);
1204 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1205 const std::vector<Constant*> &IdxList) {
1206 assert(GetElementPtrInst::getIndexedType(C->getType(),
1207 std::vector<Value*>(IdxList.begin(), IdxList.end()), true) &&
1208 "GEP indices invalid!");
1210 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1211 return FC; // Fold a few common cases...
1213 assert(isa<PointerType>(C->getType()) &&
1214 "Non-pointer type for constant GetElementPtr expression");
1215 // Look up the constant in the table first to ensure uniqueness
1216 std::vector<Constant*> argVec(1, C);
1217 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
1218 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
1219 return ExprConstants.getOrCreate(ReqTy, Key);
1222 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1223 const std::vector<Constant*> &IdxList){
1224 // Get the result type of the getelementptr!
1225 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1227 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1229 assert(Ty && "GEP indices invalid!");
1230 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1234 // destroyConstant - Remove the constant from the constant table...
1236 void ConstantExpr::destroyConstant() {
1237 ExprConstants.remove(this);
1238 destroyConstantImpl();
1241 const char *ConstantExpr::getOpcodeName() const {
1242 return Instruction::getOpcodeName(getOpcode());