1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFolding.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/SymbolTable.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/ManagedStatic.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 void Constant::destroyConstantImpl() {
34 // When a Constant is destroyed, there may be lingering
35 // references to the constant by other constants in the constant pool. These
36 // constants are implicitly dependent on the module that is being deleted,
37 // but they don't know that. Because we only find out when the CPV is
38 // deleted, we must now notify all of our users (that should only be
39 // Constants) that they are, in fact, invalid now and should be deleted.
41 while (!use_empty()) {
42 Value *V = use_back();
43 #ifndef NDEBUG // Only in -g mode...
44 if (!isa<Constant>(V))
45 std::cerr << "While deleting: " << *this
46 << "\n\nUse still stuck around after Def is destroyed: "
49 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
50 Constant *CV = cast<Constant>(V);
51 CV->destroyConstant();
53 // The constant should remove itself from our use list...
54 assert((use_empty() || use_back() != V) && "Constant not removed!");
57 // Value has no outstanding references it is safe to delete it now...
61 /// canTrap - Return true if evaluation of this constant could trap. This is
62 /// true for things like constant expressions that could divide by zero.
63 bool Constant::canTrap() const {
64 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
65 // The only thing that could possibly trap are constant exprs.
66 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
67 if (!CE) return false;
69 // ConstantExpr traps if any operands can trap.
70 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
71 if (getOperand(i)->canTrap())
74 // Otherwise, only specific operations can trap.
75 switch (CE->getOpcode()) {
78 case Instruction::Div:
79 case Instruction::Rem:
80 // Div and rem can trap if the RHS is not known to be non-zero.
81 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
88 // Static constructor to create a '0' constant of arbitrary type...
89 Constant *Constant::getNullValue(const Type *Ty) {
90 switch (Ty->getTypeID()) {
91 case Type::BoolTyID: {
92 static Constant *NullBool = ConstantBool::get(false);
95 case Type::SByteTyID: {
96 static Constant *NullSByte = ConstantSInt::get(Type::SByteTy, 0);
99 case Type::UByteTyID: {
100 static Constant *NullUByte = ConstantUInt::get(Type::UByteTy, 0);
103 case Type::ShortTyID: {
104 static Constant *NullShort = ConstantSInt::get(Type::ShortTy, 0);
107 case Type::UShortTyID: {
108 static Constant *NullUShort = ConstantUInt::get(Type::UShortTy, 0);
111 case Type::IntTyID: {
112 static Constant *NullInt = ConstantSInt::get(Type::IntTy, 0);
115 case Type::UIntTyID: {
116 static Constant *NullUInt = ConstantUInt::get(Type::UIntTy, 0);
119 case Type::LongTyID: {
120 static Constant *NullLong = ConstantSInt::get(Type::LongTy, 0);
123 case Type::ULongTyID: {
124 static Constant *NullULong = ConstantUInt::get(Type::ULongTy, 0);
128 case Type::FloatTyID: {
129 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
132 case Type::DoubleTyID: {
133 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
137 case Type::PointerTyID:
138 return ConstantPointerNull::get(cast<PointerType>(Ty));
140 case Type::StructTyID:
141 case Type::ArrayTyID:
142 case Type::PackedTyID:
143 return ConstantAggregateZero::get(Ty);
145 // Function, Label, or Opaque type?
146 assert(!"Cannot create a null constant of that type!");
151 // Static constructor to create the maximum constant of an integral type...
152 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
153 switch (Ty->getTypeID()) {
154 case Type::BoolTyID: return ConstantBool::getTrue();
155 case Type::SByteTyID:
156 case Type::ShortTyID:
158 case Type::LongTyID: {
159 // Calculate 011111111111111...
160 unsigned TypeBits = Ty->getPrimitiveSize()*8;
161 int64_t Val = INT64_MAX; // All ones
162 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
163 return ConstantSInt::get(Ty, Val);
166 case Type::UByteTyID:
167 case Type::UShortTyID:
169 case Type::ULongTyID: return getAllOnesValue(Ty);
175 // Static constructor to create the minimum constant for an integral type...
176 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
177 switch (Ty->getTypeID()) {
178 case Type::BoolTyID: return ConstantBool::getFalse();
179 case Type::SByteTyID:
180 case Type::ShortTyID:
182 case Type::LongTyID: {
183 // Calculate 1111111111000000000000
184 unsigned TypeBits = Ty->getPrimitiveSize()*8;
185 int64_t Val = -1; // All ones
186 Val <<= TypeBits-1; // Shift over to the right spot
187 return ConstantSInt::get(Ty, Val);
190 case Type::UByteTyID:
191 case Type::UShortTyID:
193 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
199 // Static constructor to create an integral constant with all bits set
200 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
201 switch (Ty->getTypeID()) {
202 case Type::BoolTyID: return ConstantBool::getTrue();
203 case Type::SByteTyID:
204 case Type::ShortTyID:
206 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
208 case Type::UByteTyID:
209 case Type::UShortTyID:
211 case Type::ULongTyID: {
212 // Calculate ~0 of the right type...
213 unsigned TypeBits = Ty->getPrimitiveSize()*8;
214 uint64_t Val = ~0ULL; // All ones
215 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
216 return ConstantUInt::get(Ty, Val);
222 bool ConstantUInt::isAllOnesValue() const {
223 unsigned TypeBits = getType()->getPrimitiveSize()*8;
224 uint64_t Val = ~0ULL; // All ones
225 Val >>= 64-TypeBits; // Shift out inappropriate bits
226 return getValue() == Val;
230 //===----------------------------------------------------------------------===//
231 // ConstantXXX Classes
232 //===----------------------------------------------------------------------===//
234 //===----------------------------------------------------------------------===//
235 // Normal Constructors
237 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
238 : Constant(Ty, VT, 0, 0) {
242 ConstantBool::ConstantBool(bool V)
243 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, V) {
246 ConstantInt::ConstantInt(const Type *Ty, ValueTy VT, uint64_t V)
247 : ConstantIntegral(Ty, VT, V) {
250 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V)
251 : ConstantInt(Ty, ConstantSIntVal, V) {
252 assert(Ty->isInteger() && Ty->isSigned() &&
253 "Illegal type for signed integer constant!");
254 assert(isValueValidForType(Ty, V) && "Value too large for type!");
257 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V)
258 : ConstantInt(Ty, ConstantUIntVal, V) {
259 assert(Ty->isInteger() && Ty->isUnsigned() &&
260 "Illegal type for unsigned integer constant!");
261 assert(isValueValidForType(Ty, V) && "Value too large for type!");
264 ConstantFP::ConstantFP(const Type *Ty, double V)
265 : Constant(Ty, ConstantFPVal, 0, 0) {
266 assert(isValueValidForType(Ty, V) && "Value too large for type!");
270 ConstantArray::ConstantArray(const ArrayType *T,
271 const std::vector<Constant*> &V)
272 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
273 assert(V.size() == T->getNumElements() &&
274 "Invalid initializer vector for constant array");
275 Use *OL = OperandList;
276 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
279 assert((C->getType() == T->getElementType() ||
281 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
282 "Initializer for array element doesn't match array element type!");
287 ConstantArray::~ConstantArray() {
288 delete [] OperandList;
291 ConstantStruct::ConstantStruct(const StructType *T,
292 const std::vector<Constant*> &V)
293 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
294 assert(V.size() == T->getNumElements() &&
295 "Invalid initializer vector for constant structure");
296 Use *OL = OperandList;
297 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
300 assert((C->getType() == T->getElementType(I-V.begin()) ||
301 ((T->getElementType(I-V.begin())->isAbstract() ||
302 C->getType()->isAbstract()) &&
303 T->getElementType(I-V.begin())->getTypeID() ==
304 C->getType()->getTypeID())) &&
305 "Initializer for struct element doesn't match struct element type!");
310 ConstantStruct::~ConstantStruct() {
311 delete [] OperandList;
315 ConstantPacked::ConstantPacked(const PackedType *T,
316 const std::vector<Constant*> &V)
317 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
318 Use *OL = OperandList;
319 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
322 assert((C->getType() == T->getElementType() ||
324 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
325 "Initializer for packed element doesn't match packed element type!");
330 ConstantPacked::~ConstantPacked() {
331 delete [] OperandList;
334 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
335 /// behind the scenes to implement unary constant exprs.
337 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
340 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
341 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
345 static bool isSetCC(unsigned Opcode) {
346 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
347 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
348 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
351 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
352 /// behind the scenes to implement binary constant exprs.
354 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
357 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
358 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
360 Ops[0].init(C1, this);
361 Ops[1].init(C2, this);
366 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
367 /// behind the scenes to implement select constant exprs.
369 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
372 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
373 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
374 Ops[0].init(C1, this);
375 Ops[1].init(C2, this);
376 Ops[2].init(C3, this);
381 /// ExtractElementConstantExpr - This class is private to
382 /// Constants.cpp, and is used behind the scenes to implement
383 /// extractelement constant exprs.
385 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
388 ExtractElementConstantExpr(Constant *C1, Constant *C2)
389 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
390 Instruction::ExtractElement, Ops, 2) {
391 Ops[0].init(C1, this);
392 Ops[1].init(C2, this);
397 /// InsertElementConstantExpr - This class is private to
398 /// Constants.cpp, and is used behind the scenes to implement
399 /// insertelement constant exprs.
401 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
404 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
405 : ConstantExpr(C1->getType(), Instruction::InsertElement,
407 Ops[0].init(C1, this);
408 Ops[1].init(C2, this);
409 Ops[2].init(C3, this);
414 /// ShuffleVectorConstantExpr - This class is private to
415 /// Constants.cpp, and is used behind the scenes to implement
416 /// shufflevector constant exprs.
418 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
421 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
422 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
424 Ops[0].init(C1, this);
425 Ops[1].init(C2, this);
426 Ops[2].init(C3, this);
431 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
432 /// used behind the scenes to implement getelementpr constant exprs.
434 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
435 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
437 : ConstantExpr(DestTy, Instruction::GetElementPtr,
438 new Use[IdxList.size()+1], IdxList.size()+1) {
439 OperandList[0].init(C, this);
440 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
441 OperandList[i+1].init(IdxList[i], this);
443 ~GetElementPtrConstantExpr() {
444 delete [] OperandList;
449 /// ConstantExpr::get* - Return some common constants without having to
450 /// specify the full Instruction::OPCODE identifier.
452 Constant *ConstantExpr::getNeg(Constant *C) {
453 if (!C->getType()->isFloatingPoint())
454 return get(Instruction::Sub, getNullValue(C->getType()), C);
456 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
458 Constant *ConstantExpr::getNot(Constant *C) {
459 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
460 return get(Instruction::Xor, C,
461 ConstantIntegral::getAllOnesValue(C->getType()));
463 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
464 return get(Instruction::Add, C1, C2);
466 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
467 return get(Instruction::Sub, C1, C2);
469 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
470 return get(Instruction::Mul, C1, C2);
472 Constant *ConstantExpr::getDiv(Constant *C1, Constant *C2) {
473 return get(Instruction::Div, C1, C2);
475 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
476 return get(Instruction::Rem, C1, C2);
478 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
479 return get(Instruction::And, C1, C2);
481 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
482 return get(Instruction::Or, C1, C2);
484 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
485 return get(Instruction::Xor, C1, C2);
487 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
488 return get(Instruction::SetEQ, C1, C2);
490 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
491 return get(Instruction::SetNE, C1, C2);
493 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
494 return get(Instruction::SetLT, C1, C2);
496 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
497 return get(Instruction::SetGT, C1, C2);
499 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
500 return get(Instruction::SetLE, C1, C2);
502 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
503 return get(Instruction::SetGE, C1, C2);
505 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
506 return get(Instruction::Shl, C1, C2);
508 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
509 return get(Instruction::Shr, C1, C2);
512 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
513 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
514 return getCast(getShr(getCast(C1,
515 C1->getType()->getUnsignedVersion()), C2), C1->getType());
518 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
519 if (C1->getType()->isSigned()) return getShr(C1, C2);
520 return getCast(getShr(getCast(C1,
521 C1->getType()->getSignedVersion()), C2), C1->getType());
524 /// getWithOperandReplaced - Return a constant expression identical to this
525 /// one, but with the specified operand set to the specified value.
526 Constant *ConstantExpr::getWithOperandReplaced(unsigned OpNo,
527 Constant *Op) const {
528 assert(OpNo < getNumOperands() && "Operand num is out of range!");
529 assert(Op->getType() == getOperand(OpNo)->getType() &&
530 "Replacing operand with value of different type!");
531 if (getOperand(OpNo) == Op)
532 return const_cast<ConstantExpr*>(this);
534 Constant *Op0, *Op1, *Op2;
535 switch (getOpcode()) {
536 case Instruction::Cast:
537 return ConstantExpr::getCast(Op, getType());
538 case Instruction::Select:
539 Op0 = (OpNo == 0) ? Op : getOperand(0);
540 Op1 = (OpNo == 1) ? Op : getOperand(1);
541 Op2 = (OpNo == 2) ? Op : getOperand(2);
542 return ConstantExpr::getSelect(Op0, Op1, Op2);
543 case Instruction::InsertElement:
544 Op0 = (OpNo == 0) ? Op : getOperand(0);
545 Op1 = (OpNo == 1) ? Op : getOperand(1);
546 Op2 = (OpNo == 2) ? Op : getOperand(2);
547 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
548 case Instruction::ExtractElement:
549 Op0 = (OpNo == 0) ? Op : getOperand(0);
550 Op1 = (OpNo == 1) ? Op : getOperand(1);
551 return ConstantExpr::getExtractElement(Op0, Op1);
552 case Instruction::ShuffleVector:
553 Op0 = (OpNo == 0) ? Op : getOperand(0);
554 Op1 = (OpNo == 1) ? Op : getOperand(1);
555 Op2 = (OpNo == 2) ? Op : getOperand(2);
556 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
557 case Instruction::GetElementPtr: {
558 std::vector<Constant*> Ops;
559 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
560 Ops.push_back(getOperand(i));
562 return ConstantExpr::getGetElementPtr(Op, Ops);
564 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
567 assert(getNumOperands() == 2 && "Must be binary operator?");
568 Op0 = (OpNo == 0) ? Op : getOperand(0);
569 Op1 = (OpNo == 1) ? Op : getOperand(1);
570 return ConstantExpr::get(getOpcode(), Op0, Op1);
574 /// getWithOperands - This returns the current constant expression with the
575 /// operands replaced with the specified values. The specified operands must
576 /// match count and type with the existing ones.
577 Constant *ConstantExpr::
578 getWithOperands(const std::vector<Constant*> &Ops) const {
579 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
580 bool AnyChange = false;
581 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
582 assert(Ops[i]->getType() == getOperand(i)->getType() &&
583 "Operand type mismatch!");
584 AnyChange |= Ops[i] != getOperand(i);
586 if (!AnyChange) // No operands changed, return self.
587 return const_cast<ConstantExpr*>(this);
589 switch (getOpcode()) {
590 case Instruction::Cast:
591 return ConstantExpr::getCast(Ops[0], getType());
592 case Instruction::Select:
593 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
594 case Instruction::InsertElement:
595 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
596 case Instruction::ExtractElement:
597 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
598 case Instruction::ShuffleVector:
599 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
600 case Instruction::GetElementPtr: {
601 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
602 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
605 assert(getNumOperands() == 2 && "Must be binary operator?");
606 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
611 //===----------------------------------------------------------------------===//
612 // isValueValidForType implementations
614 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
615 switch (Ty->getTypeID()) {
617 return false; // These can't be represented as integers!!!
619 case Type::SByteTyID:
620 return (Val <= INT8_MAX && Val >= INT8_MIN);
621 case Type::ShortTyID:
622 return (Val <= INT16_MAX && Val >= INT16_MIN);
624 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
626 return true; // This is the largest type...
630 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
631 switch (Ty->getTypeID()) {
633 return false; // These can't be represented as integers!!!
636 case Type::UByteTyID:
637 return (Val <= UINT8_MAX);
638 case Type::UShortTyID:
639 return (Val <= UINT16_MAX);
641 return (Val <= UINT32_MAX);
642 case Type::ULongTyID:
643 return true; // This is the largest type...
647 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
648 switch (Ty->getTypeID()) {
650 return false; // These can't be represented as floating point!
652 // TODO: Figure out how to test if a double can be cast to a float!
653 case Type::FloatTyID:
654 case Type::DoubleTyID:
655 return true; // This is the largest type...
659 //===----------------------------------------------------------------------===//
660 // Factory Function Implementation
662 // ConstantCreator - A class that is used to create constants by
663 // ValueMap*. This class should be partially specialized if there is
664 // something strange that needs to be done to interface to the ctor for the
668 template<class ConstantClass, class TypeClass, class ValType>
669 struct VISIBILITY_HIDDEN ConstantCreator {
670 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
671 return new ConstantClass(Ty, V);
675 template<class ConstantClass, class TypeClass>
676 struct VISIBILITY_HIDDEN ConvertConstantType {
677 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
678 assert(0 && "This type cannot be converted!\n");
683 template<class ValType, class TypeClass, class ConstantClass,
684 bool HasLargeKey = false /*true for arrays and structs*/ >
685 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
687 typedef std::pair<const Type*, ValType> MapKey;
688 typedef std::map<MapKey, Constant *> MapTy;
689 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
690 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
692 /// Map - This is the main map from the element descriptor to the Constants.
693 /// This is the primary way we avoid creating two of the same shape
697 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
698 /// from the constants to their element in Map. This is important for
699 /// removal of constants from the array, which would otherwise have to scan
700 /// through the map with very large keys.
701 InverseMapTy InverseMap;
703 /// AbstractTypeMap - Map for abstract type constants.
705 AbstractTypeMapTy AbstractTypeMap;
708 void clear(std::vector<Constant *> &Constants) {
709 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
710 Constants.push_back(I->second);
712 AbstractTypeMap.clear();
717 typename MapTy::iterator map_end() { return Map.end(); }
719 /// InsertOrGetItem - Return an iterator for the specified element.
720 /// If the element exists in the map, the returned iterator points to the
721 /// entry and Exists=true. If not, the iterator points to the newly
722 /// inserted entry and returns Exists=false. Newly inserted entries have
723 /// I->second == 0, and should be filled in.
724 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
727 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
733 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
735 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
736 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
737 IMI->second->second == CP &&
738 "InverseMap corrupt!");
742 typename MapTy::iterator I =
743 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
744 if (I == Map.end() || I->second != CP) {
745 // FIXME: This should not use a linear scan. If this gets to be a
746 // performance problem, someone should look at this.
747 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
754 /// getOrCreate - Return the specified constant from the map, creating it if
756 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
757 MapKey Lookup(Ty, V);
758 typename MapTy::iterator I = Map.lower_bound(Lookup);
759 if (I != Map.end() && I->first == Lookup)
760 return static_cast<ConstantClass *>(I->second); // Is it in the map?
762 // If no preexisting value, create one now...
763 ConstantClass *Result =
764 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
766 /// FIXME: why does this assert fail when loading 176.gcc?
767 //assert(Result->getType() == Ty && "Type specified is not correct!");
768 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
770 if (HasLargeKey) // Remember the reverse mapping if needed.
771 InverseMap.insert(std::make_pair(Result, I));
773 // If the type of the constant is abstract, make sure that an entry exists
774 // for it in the AbstractTypeMap.
775 if (Ty->isAbstract()) {
776 typename AbstractTypeMapTy::iterator TI =
777 AbstractTypeMap.lower_bound(Ty);
779 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
780 // Add ourselves to the ATU list of the type.
781 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
783 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
789 void remove(ConstantClass *CP) {
790 typename MapTy::iterator I = FindExistingElement(CP);
791 assert(I != Map.end() && "Constant not found in constant table!");
792 assert(I->second == CP && "Didn't find correct element?");
794 if (HasLargeKey) // Remember the reverse mapping if needed.
795 InverseMap.erase(CP);
797 // Now that we found the entry, make sure this isn't the entry that
798 // the AbstractTypeMap points to.
799 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
800 if (Ty->isAbstract()) {
801 assert(AbstractTypeMap.count(Ty) &&
802 "Abstract type not in AbstractTypeMap?");
803 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
804 if (ATMEntryIt == I) {
805 // Yes, we are removing the representative entry for this type.
806 // See if there are any other entries of the same type.
807 typename MapTy::iterator TmpIt = ATMEntryIt;
809 // First check the entry before this one...
810 if (TmpIt != Map.begin()) {
812 if (TmpIt->first.first != Ty) // Not the same type, move back...
816 // If we didn't find the same type, try to move forward...
817 if (TmpIt == ATMEntryIt) {
819 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
820 --TmpIt; // No entry afterwards with the same type
823 // If there is another entry in the map of the same abstract type,
824 // update the AbstractTypeMap entry now.
825 if (TmpIt != ATMEntryIt) {
828 // Otherwise, we are removing the last instance of this type
829 // from the table. Remove from the ATM, and from user list.
830 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
831 AbstractTypeMap.erase(Ty);
840 /// MoveConstantToNewSlot - If we are about to change C to be the element
841 /// specified by I, update our internal data structures to reflect this
843 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
844 // First, remove the old location of the specified constant in the map.
845 typename MapTy::iterator OldI = FindExistingElement(C);
846 assert(OldI != Map.end() && "Constant not found in constant table!");
847 assert(OldI->second == C && "Didn't find correct element?");
849 // If this constant is the representative element for its abstract type,
850 // update the AbstractTypeMap so that the representative element is I.
851 if (C->getType()->isAbstract()) {
852 typename AbstractTypeMapTy::iterator ATI =
853 AbstractTypeMap.find(C->getType());
854 assert(ATI != AbstractTypeMap.end() &&
855 "Abstract type not in AbstractTypeMap?");
856 if (ATI->second == OldI)
860 // Remove the old entry from the map.
863 // Update the inverse map so that we know that this constant is now
864 // located at descriptor I.
866 assert(I->second == C && "Bad inversemap entry!");
871 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
872 typename AbstractTypeMapTy::iterator I =
873 AbstractTypeMap.find(cast<Type>(OldTy));
875 assert(I != AbstractTypeMap.end() &&
876 "Abstract type not in AbstractTypeMap?");
878 // Convert a constant at a time until the last one is gone. The last one
879 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
880 // eliminated eventually.
882 ConvertConstantType<ConstantClass,
884 static_cast<ConstantClass *>(I->second->second),
885 cast<TypeClass>(NewTy));
887 I = AbstractTypeMap.find(cast<Type>(OldTy));
888 } while (I != AbstractTypeMap.end());
891 // If the type became concrete without being refined to any other existing
892 // type, we just remove ourselves from the ATU list.
893 void typeBecameConcrete(const DerivedType *AbsTy) {
894 AbsTy->removeAbstractTypeUser(this);
898 std::cerr << "Constant.cpp: ValueMap\n";
904 //---- ConstantBool::get*() implementation.
906 ConstantBool *ConstantBool::getTrue() {
907 static ConstantBool *T = 0;
909 return T = new ConstantBool(true);
911 ConstantBool *ConstantBool::getFalse() {
912 static ConstantBool *F = 0;
914 return F = new ConstantBool(false);
917 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
919 static ManagedStatic<ValueMap< int64_t, Type, ConstantSInt> > SIntConstants;
920 static ManagedStatic<ValueMap<uint64_t, Type, ConstantUInt> > UIntConstants;
922 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
923 return SIntConstants->getOrCreate(Ty, V);
926 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
927 return UIntConstants->getOrCreate(Ty, V);
930 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
931 assert(V <= 127 && "Can only be used with very small positive constants!");
932 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
933 return ConstantUInt::get(Ty, V);
936 //---- ConstantFP::get() implementation...
940 struct ConstantCreator<ConstantFP, Type, uint64_t> {
941 static ConstantFP *create(const Type *Ty, uint64_t V) {
942 assert(Ty == Type::DoubleTy);
943 return new ConstantFP(Ty, BitsToDouble(V));
947 struct ConstantCreator<ConstantFP, Type, uint32_t> {
948 static ConstantFP *create(const Type *Ty, uint32_t V) {
949 assert(Ty == Type::FloatTy);
950 return new ConstantFP(Ty, BitsToFloat(V));
955 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
956 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
958 bool ConstantFP::isNullValue() const {
959 return DoubleToBits(Val) == 0;
962 bool ConstantFP::isExactlyValue(double V) const {
963 return DoubleToBits(V) == DoubleToBits(Val);
967 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
968 if (Ty == Type::FloatTy) {
969 // Force the value through memory to normalize it.
970 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
972 assert(Ty == Type::DoubleTy);
973 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
977 //---- ConstantAggregateZero::get() implementation...
980 // ConstantAggregateZero does not take extra "value" argument...
981 template<class ValType>
982 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
983 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
984 return new ConstantAggregateZero(Ty);
989 struct ConvertConstantType<ConstantAggregateZero, Type> {
990 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
991 // Make everyone now use a constant of the new type...
992 Constant *New = ConstantAggregateZero::get(NewTy);
993 assert(New != OldC && "Didn't replace constant??");
994 OldC->uncheckedReplaceAllUsesWith(New);
995 OldC->destroyConstant(); // This constant is now dead, destroy it.
1000 static ManagedStatic<ValueMap<char, Type,
1001 ConstantAggregateZero> > AggZeroConstants;
1003 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1005 Constant *ConstantAggregateZero::get(const Type *Ty) {
1006 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
1007 "Cannot create an aggregate zero of non-aggregate type!");
1008 return AggZeroConstants->getOrCreate(Ty, 0);
1011 // destroyConstant - Remove the constant from the constant table...
1013 void ConstantAggregateZero::destroyConstant() {
1014 AggZeroConstants->remove(this);
1015 destroyConstantImpl();
1018 //---- ConstantArray::get() implementation...
1022 struct ConvertConstantType<ConstantArray, ArrayType> {
1023 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1024 // Make everyone now use a constant of the new type...
1025 std::vector<Constant*> C;
1026 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1027 C.push_back(cast<Constant>(OldC->getOperand(i)));
1028 Constant *New = ConstantArray::get(NewTy, C);
1029 assert(New != OldC && "Didn't replace constant??");
1030 OldC->uncheckedReplaceAllUsesWith(New);
1031 OldC->destroyConstant(); // This constant is now dead, destroy it.
1036 static std::vector<Constant*> getValType(ConstantArray *CA) {
1037 std::vector<Constant*> Elements;
1038 Elements.reserve(CA->getNumOperands());
1039 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1040 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1044 typedef ValueMap<std::vector<Constant*>, ArrayType,
1045 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1046 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1048 Constant *ConstantArray::get(const ArrayType *Ty,
1049 const std::vector<Constant*> &V) {
1050 // If this is an all-zero array, return a ConstantAggregateZero object
1053 if (!C->isNullValue())
1054 return ArrayConstants->getOrCreate(Ty, V);
1055 for (unsigned i = 1, e = V.size(); i != e; ++i)
1057 return ArrayConstants->getOrCreate(Ty, V);
1059 return ConstantAggregateZero::get(Ty);
1062 // destroyConstant - Remove the constant from the constant table...
1064 void ConstantArray::destroyConstant() {
1065 ArrayConstants->remove(this);
1066 destroyConstantImpl();
1069 /// ConstantArray::get(const string&) - Return an array that is initialized to
1070 /// contain the specified string. If length is zero then a null terminator is
1071 /// added to the specified string so that it may be used in a natural way.
1072 /// Otherwise, the length parameter specifies how much of the string to use
1073 /// and it won't be null terminated.
1075 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1076 std::vector<Constant*> ElementVals;
1077 for (unsigned i = 0; i < Str.length(); ++i)
1078 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
1080 // Add a null terminator to the string...
1082 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
1085 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
1086 return ConstantArray::get(ATy, ElementVals);
1089 /// isString - This method returns true if the array is an array of sbyte or
1090 /// ubyte, and if the elements of the array are all ConstantInt's.
1091 bool ConstantArray::isString() const {
1092 // Check the element type for sbyte or ubyte...
1093 if (getType()->getElementType() != Type::UByteTy &&
1094 getType()->getElementType() != Type::SByteTy)
1096 // Check the elements to make sure they are all integers, not constant
1098 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1099 if (!isa<ConstantInt>(getOperand(i)))
1104 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1105 // then this method converts the array to an std::string and returns it.
1106 // Otherwise, it asserts out.
1108 std::string ConstantArray::getAsString() const {
1109 assert(isString() && "Not a string!");
1111 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1112 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
1117 //---- ConstantStruct::get() implementation...
1122 struct ConvertConstantType<ConstantStruct, StructType> {
1123 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1124 // Make everyone now use a constant of the new type...
1125 std::vector<Constant*> C;
1126 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1127 C.push_back(cast<Constant>(OldC->getOperand(i)));
1128 Constant *New = ConstantStruct::get(NewTy, C);
1129 assert(New != OldC && "Didn't replace constant??");
1131 OldC->uncheckedReplaceAllUsesWith(New);
1132 OldC->destroyConstant(); // This constant is now dead, destroy it.
1137 typedef ValueMap<std::vector<Constant*>, StructType,
1138 ConstantStruct, true /*largekey*/> StructConstantsTy;
1139 static ManagedStatic<StructConstantsTy> StructConstants;
1141 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1142 std::vector<Constant*> Elements;
1143 Elements.reserve(CS->getNumOperands());
1144 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1145 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1149 Constant *ConstantStruct::get(const StructType *Ty,
1150 const std::vector<Constant*> &V) {
1151 // Create a ConstantAggregateZero value if all elements are zeros...
1152 for (unsigned i = 0, e = V.size(); i != e; ++i)
1153 if (!V[i]->isNullValue())
1154 return StructConstants->getOrCreate(Ty, V);
1156 return ConstantAggregateZero::get(Ty);
1159 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1160 std::vector<const Type*> StructEls;
1161 StructEls.reserve(V.size());
1162 for (unsigned i = 0, e = V.size(); i != e; ++i)
1163 StructEls.push_back(V[i]->getType());
1164 return get(StructType::get(StructEls), V);
1167 // destroyConstant - Remove the constant from the constant table...
1169 void ConstantStruct::destroyConstant() {
1170 StructConstants->remove(this);
1171 destroyConstantImpl();
1174 //---- ConstantPacked::get() implementation...
1178 struct ConvertConstantType<ConstantPacked, PackedType> {
1179 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1180 // Make everyone now use a constant of the new type...
1181 std::vector<Constant*> C;
1182 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1183 C.push_back(cast<Constant>(OldC->getOperand(i)));
1184 Constant *New = ConstantPacked::get(NewTy, C);
1185 assert(New != OldC && "Didn't replace constant??");
1186 OldC->uncheckedReplaceAllUsesWith(New);
1187 OldC->destroyConstant(); // This constant is now dead, destroy it.
1192 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1193 std::vector<Constant*> Elements;
1194 Elements.reserve(CP->getNumOperands());
1195 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1196 Elements.push_back(CP->getOperand(i));
1200 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1201 ConstantPacked> > PackedConstants;
1203 Constant *ConstantPacked::get(const PackedType *Ty,
1204 const std::vector<Constant*> &V) {
1205 // If this is an all-zero packed, return a ConstantAggregateZero object
1208 if (!C->isNullValue())
1209 return PackedConstants->getOrCreate(Ty, V);
1210 for (unsigned i = 1, e = V.size(); i != e; ++i)
1212 return PackedConstants->getOrCreate(Ty, V);
1214 return ConstantAggregateZero::get(Ty);
1217 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1218 assert(!V.empty() && "Cannot infer type if V is empty");
1219 return get(PackedType::get(V.front()->getType(),V.size()), V);
1222 // destroyConstant - Remove the constant from the constant table...
1224 void ConstantPacked::destroyConstant() {
1225 PackedConstants->remove(this);
1226 destroyConstantImpl();
1229 //---- ConstantPointerNull::get() implementation...
1233 // ConstantPointerNull does not take extra "value" argument...
1234 template<class ValType>
1235 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1236 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1237 return new ConstantPointerNull(Ty);
1242 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1243 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1244 // Make everyone now use a constant of the new type...
1245 Constant *New = ConstantPointerNull::get(NewTy);
1246 assert(New != OldC && "Didn't replace constant??");
1247 OldC->uncheckedReplaceAllUsesWith(New);
1248 OldC->destroyConstant(); // This constant is now dead, destroy it.
1253 static ManagedStatic<ValueMap<char, PointerType,
1254 ConstantPointerNull> > NullPtrConstants;
1256 static char getValType(ConstantPointerNull *) {
1261 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1262 return NullPtrConstants->getOrCreate(Ty, 0);
1265 // destroyConstant - Remove the constant from the constant table...
1267 void ConstantPointerNull::destroyConstant() {
1268 NullPtrConstants->remove(this);
1269 destroyConstantImpl();
1273 //---- UndefValue::get() implementation...
1277 // UndefValue does not take extra "value" argument...
1278 template<class ValType>
1279 struct ConstantCreator<UndefValue, Type, ValType> {
1280 static UndefValue *create(const Type *Ty, const ValType &V) {
1281 return new UndefValue(Ty);
1286 struct ConvertConstantType<UndefValue, Type> {
1287 static void convert(UndefValue *OldC, const Type *NewTy) {
1288 // Make everyone now use a constant of the new type.
1289 Constant *New = UndefValue::get(NewTy);
1290 assert(New != OldC && "Didn't replace constant??");
1291 OldC->uncheckedReplaceAllUsesWith(New);
1292 OldC->destroyConstant(); // This constant is now dead, destroy it.
1297 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1299 static char getValType(UndefValue *) {
1304 UndefValue *UndefValue::get(const Type *Ty) {
1305 return UndefValueConstants->getOrCreate(Ty, 0);
1308 // destroyConstant - Remove the constant from the constant table.
1310 void UndefValue::destroyConstant() {
1311 UndefValueConstants->remove(this);
1312 destroyConstantImpl();
1318 //---- ConstantExpr::get() implementations...
1320 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1324 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1325 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1326 if (V.first == Instruction::Cast)
1327 return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1328 if ((V.first >= Instruction::BinaryOpsBegin &&
1329 V.first < Instruction::BinaryOpsEnd) ||
1330 V.first == Instruction::Shl || V.first == Instruction::Shr)
1331 return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1332 if (V.first == Instruction::Select)
1333 return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1334 if (V.first == Instruction::ExtractElement)
1335 return new ExtractElementConstantExpr(V.second[0], V.second[1]);
1336 if (V.first == Instruction::InsertElement)
1337 return new InsertElementConstantExpr(V.second[0], V.second[1],
1339 if (V.first == Instruction::ShuffleVector)
1340 return new ShuffleVectorConstantExpr(V.second[0], V.second[1],
1343 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1345 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1346 return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1351 struct ConvertConstantType<ConstantExpr, Type> {
1352 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1354 switch (OldC->getOpcode()) {
1355 case Instruction::Cast:
1356 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1358 case Instruction::Select:
1359 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1360 OldC->getOperand(1),
1361 OldC->getOperand(2));
1363 case Instruction::Shl:
1364 case Instruction::Shr:
1365 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1366 OldC->getOperand(0), OldC->getOperand(1));
1369 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1370 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1371 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1372 OldC->getOperand(1));
1374 case Instruction::GetElementPtr:
1375 // Make everyone now use a constant of the new type...
1376 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1377 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1381 assert(New != OldC && "Didn't replace constant??");
1382 OldC->uncheckedReplaceAllUsesWith(New);
1383 OldC->destroyConstant(); // This constant is now dead, destroy it.
1386 } // end namespace llvm
1389 static ExprMapKeyType getValType(ConstantExpr *CE) {
1390 std::vector<Constant*> Operands;
1391 Operands.reserve(CE->getNumOperands());
1392 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1393 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1394 return ExprMapKeyType(CE->getOpcode(), Operands);
1397 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1398 ConstantExpr> > ExprConstants;
1400 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1401 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1403 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1404 return FC; // Fold a few common cases...
1406 // Look up the constant in the table first to ensure uniqueness
1407 std::vector<Constant*> argVec(1, C);
1408 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1409 return ExprConstants->getOrCreate(Ty, Key);
1412 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1413 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1414 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1415 "This is an illegal sign extension!");
1416 if (C->getType() != Type::BoolTy) {
1417 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1418 return ConstantExpr::getCast(C, Ty);
1420 if (C == ConstantBool::getTrue())
1421 return ConstantIntegral::getAllOnesValue(Ty);
1423 return ConstantIntegral::getNullValue(Ty);
1427 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1428 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1429 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1430 "This is an illegal zero extension!");
1431 if (C->getType() != Type::BoolTy)
1432 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1433 return ConstantExpr::getCast(C, Ty);
1436 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1437 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1439 getGetElementPtr(getNullValue(PointerType::get(Ty)),
1440 std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1444 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1445 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1446 static std::vector<Constant*> Indices(2, ConstantUInt::get(Type::UIntTy, 0));
1448 return ConstantExpr::getGetElementPtr(C, Indices);
1451 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1452 Constant *C1, Constant *C2) {
1453 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1454 return getShiftTy(ReqTy, Opcode, C1, C2);
1455 // Check the operands for consistency first
1456 assert((Opcode >= Instruction::BinaryOpsBegin &&
1457 Opcode < Instruction::BinaryOpsEnd) &&
1458 "Invalid opcode in binary constant expression");
1459 assert(C1->getType() == C2->getType() &&
1460 "Operand types in binary constant expression should match");
1462 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
1463 ReqTy == Type::BoolTy))
1464 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1465 return FC; // Fold a few common cases...
1467 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1468 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1469 return ExprConstants->getOrCreate(ReqTy, Key);
1472 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1475 case Instruction::Add: case Instruction::Sub:
1476 case Instruction::Mul: case Instruction::Div:
1477 case Instruction::Rem:
1478 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1479 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1480 isa<PackedType>(C1->getType())) &&
1481 "Tried to create an arithmetic operation on a non-arithmetic type!");
1483 case Instruction::And:
1484 case Instruction::Or:
1485 case Instruction::Xor:
1486 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1487 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1488 "Tried to create a logical operation on a non-integral type!");
1490 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1491 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1492 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1494 case Instruction::Shl:
1495 case Instruction::Shr:
1496 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1497 assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
1498 "Tried to create a shift operation on a non-integer type!");
1505 if (Instruction::isComparison(Opcode))
1506 return getTy(Type::BoolTy, Opcode, C1, C2);
1508 return getTy(C1->getType(), Opcode, C1, C2);
1511 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1512 Constant *V1, Constant *V2) {
1513 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1514 assert(V1->getType() == V2->getType() && "Select value types must match!");
1515 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1517 if (ReqTy == V1->getType())
1518 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1519 return SC; // Fold common cases
1521 std::vector<Constant*> argVec(3, C);
1524 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1525 return ExprConstants->getOrCreate(ReqTy, Key);
1528 /// getShiftTy - Return a shift left or shift right constant expr
1529 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1530 Constant *C1, Constant *C2) {
1531 // Check the operands for consistency first
1532 assert((Opcode == Instruction::Shl ||
1533 Opcode == Instruction::Shr) &&
1534 "Invalid opcode in binary constant expression");
1535 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1536 "Invalid operand types for Shift constant expr!");
1538 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1539 return FC; // Fold a few common cases...
1541 // Look up the constant in the table first to ensure uniqueness
1542 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1543 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1544 return ExprConstants->getOrCreate(ReqTy, Key);
1548 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1549 const std::vector<Value*> &IdxList) {
1550 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1551 "GEP indices invalid!");
1553 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1554 return FC; // Fold a few common cases...
1556 assert(isa<PointerType>(C->getType()) &&
1557 "Non-pointer type for constant GetElementPtr expression");
1558 // Look up the constant in the table first to ensure uniqueness
1559 std::vector<Constant*> ArgVec;
1560 ArgVec.reserve(IdxList.size()+1);
1561 ArgVec.push_back(C);
1562 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1563 ArgVec.push_back(cast<Constant>(IdxList[i]));
1564 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1565 return ExprConstants->getOrCreate(ReqTy, Key);
1568 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1569 const std::vector<Constant*> &IdxList){
1570 // Get the result type of the getelementptr!
1571 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1573 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1575 assert(Ty && "GEP indices invalid!");
1576 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1579 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1580 const std::vector<Value*> &IdxList) {
1581 // Get the result type of the getelementptr!
1582 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1584 assert(Ty && "GEP indices invalid!");
1585 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1588 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1590 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1591 return FC; // Fold a few common cases...
1592 // Look up the constant in the table first to ensure uniqueness
1593 std::vector<Constant*> ArgVec(1, Val);
1594 ArgVec.push_back(Idx);
1595 const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
1596 return ExprConstants->getOrCreate(ReqTy, Key);
1599 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1600 assert(isa<PackedType>(Val->getType()) &&
1601 "Tried to create extractelement operation on non-packed type!");
1602 assert(Idx->getType() == Type::UIntTy &&
1603 "Extractelement index must be uint type!");
1604 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1608 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1609 Constant *Elt, Constant *Idx) {
1610 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1611 return FC; // Fold a few common cases...
1612 // Look up the constant in the table first to ensure uniqueness
1613 std::vector<Constant*> ArgVec(1, Val);
1614 ArgVec.push_back(Elt);
1615 ArgVec.push_back(Idx);
1616 const ExprMapKeyType &Key = std::make_pair(Instruction::InsertElement,ArgVec);
1617 return ExprConstants->getOrCreate(ReqTy, Key);
1620 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1622 assert(isa<PackedType>(Val->getType()) &&
1623 "Tried to create insertelement operation on non-packed type!");
1624 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1625 && "Insertelement types must match!");
1626 assert(Idx->getType() == Type::UIntTy &&
1627 "Insertelement index must be uint type!");
1628 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1632 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1633 Constant *V2, Constant *Mask) {
1634 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1635 return FC; // Fold a few common cases...
1636 // Look up the constant in the table first to ensure uniqueness
1637 std::vector<Constant*> ArgVec(1, V1);
1638 ArgVec.push_back(V2);
1639 ArgVec.push_back(Mask);
1640 const ExprMapKeyType &Key = std::make_pair(Instruction::ShuffleVector,ArgVec);
1641 return ExprConstants->getOrCreate(ReqTy, Key);
1644 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1646 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1647 "Invalid shuffle vector constant expr operands!");
1648 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1652 // destroyConstant - Remove the constant from the constant table...
1654 void ConstantExpr::destroyConstant() {
1655 ExprConstants->remove(this);
1656 destroyConstantImpl();
1659 const char *ConstantExpr::getOpcodeName() const {
1660 return Instruction::getOpcodeName(getOpcode());
1663 //===----------------------------------------------------------------------===//
1664 // replaceUsesOfWithOnConstant implementations
1666 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1668 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1669 Constant *ToC = cast<Constant>(To);
1671 unsigned OperandToUpdate = U-OperandList;
1672 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1674 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1675 Lookup.first.first = getType();
1676 Lookup.second = this;
1678 std::vector<Constant*> &Values = Lookup.first.second;
1679 Values.reserve(getNumOperands()); // Build replacement array.
1681 // Fill values with the modified operands of the constant array. Also,
1682 // compute whether this turns into an all-zeros array.
1683 bool isAllZeros = false;
1684 if (!ToC->isNullValue()) {
1685 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1686 Values.push_back(cast<Constant>(O->get()));
1689 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1690 Constant *Val = cast<Constant>(O->get());
1691 Values.push_back(Val);
1692 if (isAllZeros) isAllZeros = Val->isNullValue();
1695 Values[OperandToUpdate] = ToC;
1697 Constant *Replacement = 0;
1699 Replacement = ConstantAggregateZero::get(getType());
1701 // Check to see if we have this array type already.
1703 ArrayConstantsTy::MapTy::iterator I =
1704 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1707 Replacement = I->second;
1709 // Okay, the new shape doesn't exist in the system yet. Instead of
1710 // creating a new constant array, inserting it, replaceallusesof'ing the
1711 // old with the new, then deleting the old... just update the current one
1713 ArrayConstants->MoveConstantToNewSlot(this, I);
1715 // Update to the new value.
1716 setOperand(OperandToUpdate, ToC);
1721 // Otherwise, I do need to replace this with an existing value.
1722 assert(Replacement != this && "I didn't contain From!");
1724 // Everyone using this now uses the replacement.
1725 uncheckedReplaceAllUsesWith(Replacement);
1727 // Delete the old constant!
1731 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1733 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1734 Constant *ToC = cast<Constant>(To);
1736 unsigned OperandToUpdate = U-OperandList;
1737 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1739 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1740 Lookup.first.first = getType();
1741 Lookup.second = this;
1742 std::vector<Constant*> &Values = Lookup.first.second;
1743 Values.reserve(getNumOperands()); // Build replacement struct.
1746 // Fill values with the modified operands of the constant struct. Also,
1747 // compute whether this turns into an all-zeros struct.
1748 bool isAllZeros = false;
1749 if (!ToC->isNullValue()) {
1750 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1751 Values.push_back(cast<Constant>(O->get()));
1754 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1755 Constant *Val = cast<Constant>(O->get());
1756 Values.push_back(Val);
1757 if (isAllZeros) isAllZeros = Val->isNullValue();
1760 Values[OperandToUpdate] = ToC;
1762 Constant *Replacement = 0;
1764 Replacement = ConstantAggregateZero::get(getType());
1766 // Check to see if we have this array type already.
1768 StructConstantsTy::MapTy::iterator I =
1769 StructConstants->InsertOrGetItem(Lookup, Exists);
1772 Replacement = I->second;
1774 // Okay, the new shape doesn't exist in the system yet. Instead of
1775 // creating a new constant struct, inserting it, replaceallusesof'ing the
1776 // old with the new, then deleting the old... just update the current one
1778 StructConstants->MoveConstantToNewSlot(this, I);
1780 // Update to the new value.
1781 setOperand(OperandToUpdate, ToC);
1786 assert(Replacement != this && "I didn't contain From!");
1788 // Everyone using this now uses the replacement.
1789 uncheckedReplaceAllUsesWith(Replacement);
1791 // Delete the old constant!
1795 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1797 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1799 std::vector<Constant*> Values;
1800 Values.reserve(getNumOperands()); // Build replacement array...
1801 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1802 Constant *Val = getOperand(i);
1803 if (Val == From) Val = cast<Constant>(To);
1804 Values.push_back(Val);
1807 Constant *Replacement = ConstantPacked::get(getType(), Values);
1808 assert(Replacement != this && "I didn't contain From!");
1810 // Everyone using this now uses the replacement.
1811 uncheckedReplaceAllUsesWith(Replacement);
1813 // Delete the old constant!
1817 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1819 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1820 Constant *To = cast<Constant>(ToV);
1822 Constant *Replacement = 0;
1823 if (getOpcode() == Instruction::GetElementPtr) {
1824 std::vector<Constant*> Indices;
1825 Constant *Pointer = getOperand(0);
1826 Indices.reserve(getNumOperands()-1);
1827 if (Pointer == From) Pointer = To;
1829 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1830 Constant *Val = getOperand(i);
1831 if (Val == From) Val = To;
1832 Indices.push_back(Val);
1834 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1835 } else if (getOpcode() == Instruction::Cast) {
1836 assert(getOperand(0) == From && "Cast only has one use!");
1837 Replacement = ConstantExpr::getCast(To, getType());
1838 } else if (getOpcode() == Instruction::Select) {
1839 Constant *C1 = getOperand(0);
1840 Constant *C2 = getOperand(1);
1841 Constant *C3 = getOperand(2);
1842 if (C1 == From) C1 = To;
1843 if (C2 == From) C2 = To;
1844 if (C3 == From) C3 = To;
1845 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1846 } else if (getOpcode() == Instruction::ExtractElement) {
1847 Constant *C1 = getOperand(0);
1848 Constant *C2 = getOperand(1);
1849 if (C1 == From) C1 = To;
1850 if (C2 == From) C2 = To;
1851 Replacement = ConstantExpr::getExtractElement(C1, C2);
1852 } else if (getOpcode() == Instruction::InsertElement) {
1853 Constant *C1 = getOperand(0);
1854 Constant *C2 = getOperand(1);
1855 Constant *C3 = getOperand(1);
1856 if (C1 == From) C1 = To;
1857 if (C2 == From) C2 = To;
1858 if (C3 == From) C3 = To;
1859 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
1860 } else if (getOpcode() == Instruction::ShuffleVector) {
1861 Constant *C1 = getOperand(0);
1862 Constant *C2 = getOperand(1);
1863 Constant *C3 = getOperand(2);
1864 if (C1 == From) C1 = To;
1865 if (C2 == From) C2 = To;
1866 if (C3 == From) C3 = To;
1867 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
1868 } else if (getNumOperands() == 2) {
1869 Constant *C1 = getOperand(0);
1870 Constant *C2 = getOperand(1);
1871 if (C1 == From) C1 = To;
1872 if (C2 == From) C2 = To;
1873 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1875 assert(0 && "Unknown ConstantExpr type!");
1879 assert(Replacement != this && "I didn't contain From!");
1881 // Everyone using this now uses the replacement.
1882 uncheckedReplaceAllUsesWith(Replacement);
1884 // Delete the old constant!
1889 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
1890 /// global into a string value. Return an empty string if we can't do it.
1891 /// Parameter Chop determines if the result is chopped at the first null
1894 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
1895 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
1896 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
1897 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1898 if (Init->isString()) {
1899 std::string Result = Init->getAsString();
1900 if (Offset < Result.size()) {
1901 // If we are pointing INTO The string, erase the beginning...
1902 Result.erase(Result.begin(), Result.begin()+Offset);
1904 // Take off the null terminator, and any string fragments after it.
1906 std::string::size_type NullPos = Result.find_first_of((char)0);
1907 if (NullPos != std::string::npos)
1908 Result.erase(Result.begin()+NullPos, Result.end());
1914 } else if (Constant *C = dyn_cast<Constant>(this)) {
1915 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1916 return GV->getStringValue(Chop, Offset);
1917 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1918 if (CE->getOpcode() == Instruction::GetElementPtr) {
1919 // Turn a gep into the specified offset.
1920 if (CE->getNumOperands() == 3 &&
1921 cast<Constant>(CE->getOperand(1))->isNullValue() &&
1922 isa<ConstantInt>(CE->getOperand(2))) {
1923 Offset += cast<ConstantInt>(CE->getOperand(2))->getRawValue();
1924 return CE->getOperand(0)->getStringValue(Chop, Offset);