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::UDiv:
79 case Instruction::SDiv:
80 case Instruction::FDiv:
81 case Instruction::Rem:
82 // Div and rem can trap if the RHS is not known to be non-zero.
83 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
90 // Static constructor to create a '0' constant of arbitrary type...
91 Constant *Constant::getNullValue(const Type *Ty) {
92 switch (Ty->getTypeID()) {
93 case Type::BoolTyID: {
94 static Constant *NullBool = ConstantBool::get(false);
97 case Type::SByteTyID: {
98 static Constant *NullSByte = ConstantInt::get(Type::SByteTy, 0);
101 case Type::UByteTyID: {
102 static Constant *NullUByte = ConstantInt::get(Type::UByteTy, 0);
105 case Type::ShortTyID: {
106 static Constant *NullShort = ConstantInt::get(Type::ShortTy, 0);
109 case Type::UShortTyID: {
110 static Constant *NullUShort = ConstantInt::get(Type::UShortTy, 0);
113 case Type::IntTyID: {
114 static Constant *NullInt = ConstantInt::get(Type::IntTy, 0);
117 case Type::UIntTyID: {
118 static Constant *NullUInt = ConstantInt::get(Type::UIntTy, 0);
121 case Type::LongTyID: {
122 static Constant *NullLong = ConstantInt::get(Type::LongTy, 0);
125 case Type::ULongTyID: {
126 static Constant *NullULong = ConstantInt::get(Type::ULongTy, 0);
130 case Type::FloatTyID: {
131 static Constant *NullFloat = ConstantFP::get(Type::FloatTy, 0);
134 case Type::DoubleTyID: {
135 static Constant *NullDouble = ConstantFP::get(Type::DoubleTy, 0);
139 case Type::PointerTyID:
140 return ConstantPointerNull::get(cast<PointerType>(Ty));
142 case Type::StructTyID:
143 case Type::ArrayTyID:
144 case Type::PackedTyID:
145 return ConstantAggregateZero::get(Ty);
147 // Function, Label, or Opaque type?
148 assert(!"Cannot create a null constant of that type!");
153 // Static constructor to create the maximum constant of an integral type...
154 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
155 switch (Ty->getTypeID()) {
156 case Type::BoolTyID: return ConstantBool::getTrue();
157 case Type::SByteTyID:
158 case Type::ShortTyID:
160 case Type::LongTyID: {
161 // Calculate 011111111111111...
162 unsigned TypeBits = Ty->getPrimitiveSize()*8;
163 int64_t Val = INT64_MAX; // All ones
164 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
165 return ConstantInt::get(Ty, Val);
168 case Type::UByteTyID:
169 case Type::UShortTyID:
171 case Type::ULongTyID: return getAllOnesValue(Ty);
177 // Static constructor to create the minimum constant for an integral type...
178 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
179 switch (Ty->getTypeID()) {
180 case Type::BoolTyID: return ConstantBool::getFalse();
181 case Type::SByteTyID:
182 case Type::ShortTyID:
184 case Type::LongTyID: {
185 // Calculate 1111111111000000000000
186 unsigned TypeBits = Ty->getPrimitiveSize()*8;
187 int64_t Val = -1; // All ones
188 Val <<= TypeBits-1; // Shift over to the right spot
189 return ConstantInt::get(Ty, Val);
192 case Type::UByteTyID:
193 case Type::UShortTyID:
195 case Type::ULongTyID: return ConstantInt::get(Ty, 0);
201 // Static constructor to create an integral constant with all bits set
202 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
203 switch (Ty->getTypeID()) {
204 case Type::BoolTyID: return ConstantBool::getTrue();
205 case Type::SByteTyID:
206 case Type::ShortTyID:
208 case Type::LongTyID: return ConstantInt::get(Ty, -1);
210 case Type::UByteTyID:
211 case Type::UShortTyID:
213 case Type::ULongTyID: {
214 // Calculate ~0 of the right type...
215 unsigned TypeBits = Ty->getPrimitiveSize()*8;
216 uint64_t Val = ~0ULL; // All ones
217 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
218 return ConstantInt::get(Ty, Val);
224 //===----------------------------------------------------------------------===//
225 // ConstantXXX Classes
226 //===----------------------------------------------------------------------===//
228 //===----------------------------------------------------------------------===//
229 // Normal Constructors
231 ConstantIntegral::ConstantIntegral(const Type *Ty, ValueTy VT, uint64_t V)
232 : Constant(Ty, VT, 0, 0), Val(V) {
235 ConstantBool::ConstantBool(bool V)
236 : ConstantIntegral(Type::BoolTy, ConstantBoolVal, uint64_t(V)) {
239 ConstantInt::ConstantInt(const Type *Ty, uint64_t V)
240 : ConstantIntegral(Ty, ConstantIntVal, V) {
243 ConstantFP::ConstantFP(const Type *Ty, double V)
244 : Constant(Ty, ConstantFPVal, 0, 0) {
245 assert(isValueValidForType(Ty, V) && "Value too large for type!");
249 ConstantArray::ConstantArray(const ArrayType *T,
250 const std::vector<Constant*> &V)
251 : Constant(T, ConstantArrayVal, new Use[V.size()], V.size()) {
252 assert(V.size() == T->getNumElements() &&
253 "Invalid initializer vector for constant array");
254 Use *OL = OperandList;
255 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
258 assert((C->getType() == T->getElementType() ||
260 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
261 "Initializer for array element doesn't match array element type!");
266 ConstantArray::~ConstantArray() {
267 delete [] OperandList;
270 ConstantStruct::ConstantStruct(const StructType *T,
271 const std::vector<Constant*> &V)
272 : Constant(T, ConstantStructVal, new Use[V.size()], V.size()) {
273 assert(V.size() == T->getNumElements() &&
274 "Invalid initializer vector for constant structure");
275 Use *OL = OperandList;
276 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
279 assert((C->getType() == T->getElementType(I-V.begin()) ||
280 ((T->getElementType(I-V.begin())->isAbstract() ||
281 C->getType()->isAbstract()) &&
282 T->getElementType(I-V.begin())->getTypeID() ==
283 C->getType()->getTypeID())) &&
284 "Initializer for struct element doesn't match struct element type!");
289 ConstantStruct::~ConstantStruct() {
290 delete [] OperandList;
294 ConstantPacked::ConstantPacked(const PackedType *T,
295 const std::vector<Constant*> &V)
296 : Constant(T, ConstantPackedVal, new Use[V.size()], V.size()) {
297 Use *OL = OperandList;
298 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
301 assert((C->getType() == T->getElementType() ||
303 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
304 "Initializer for packed element doesn't match packed element type!");
309 ConstantPacked::~ConstantPacked() {
310 delete [] OperandList;
313 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
314 /// behind the scenes to implement unary constant exprs.
316 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
319 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
320 : ConstantExpr(Ty, Opcode, &Op, 1), Op(C, this) {}
324 static bool isSetCC(unsigned Opcode) {
325 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
326 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
327 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
330 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
331 /// behind the scenes to implement binary constant exprs.
333 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
336 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
337 : ConstantExpr(isSetCC(Opcode) ? Type::BoolTy : C1->getType(),
339 Ops[0].init(C1, this);
340 Ops[1].init(C2, this);
345 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
346 /// behind the scenes to implement select constant exprs.
348 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
351 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
352 : ConstantExpr(C2->getType(), Instruction::Select, Ops, 3) {
353 Ops[0].init(C1, this);
354 Ops[1].init(C2, this);
355 Ops[2].init(C3, this);
360 /// ExtractElementConstantExpr - This class is private to
361 /// Constants.cpp, and is used behind the scenes to implement
362 /// extractelement constant exprs.
364 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
367 ExtractElementConstantExpr(Constant *C1, Constant *C2)
368 : ConstantExpr(cast<PackedType>(C1->getType())->getElementType(),
369 Instruction::ExtractElement, Ops, 2) {
370 Ops[0].init(C1, this);
371 Ops[1].init(C2, this);
376 /// InsertElementConstantExpr - This class is private to
377 /// Constants.cpp, and is used behind the scenes to implement
378 /// insertelement constant exprs.
380 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
383 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
384 : ConstantExpr(C1->getType(), Instruction::InsertElement,
386 Ops[0].init(C1, this);
387 Ops[1].init(C2, this);
388 Ops[2].init(C3, this);
393 /// ShuffleVectorConstantExpr - This class is private to
394 /// Constants.cpp, and is used behind the scenes to implement
395 /// shufflevector constant exprs.
397 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
400 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
401 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
403 Ops[0].init(C1, this);
404 Ops[1].init(C2, this);
405 Ops[2].init(C3, this);
410 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
411 /// used behind the scenes to implement getelementpr constant exprs.
413 struct VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
414 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
416 : ConstantExpr(DestTy, Instruction::GetElementPtr,
417 new Use[IdxList.size()+1], IdxList.size()+1) {
418 OperandList[0].init(C, this);
419 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
420 OperandList[i+1].init(IdxList[i], this);
422 ~GetElementPtrConstantExpr() {
423 delete [] OperandList;
428 /// ConstantExpr::get* - Return some common constants without having to
429 /// specify the full Instruction::OPCODE identifier.
431 Constant *ConstantExpr::getNeg(Constant *C) {
432 if (!C->getType()->isFloatingPoint())
433 return get(Instruction::Sub, getNullValue(C->getType()), C);
435 return get(Instruction::Sub, ConstantFP::get(C->getType(), -0.0), C);
437 Constant *ConstantExpr::getNot(Constant *C) {
438 assert(isa<ConstantIntegral>(C) && "Cannot NOT a nonintegral type!");
439 return get(Instruction::Xor, C,
440 ConstantIntegral::getAllOnesValue(C->getType()));
442 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
443 return get(Instruction::Add, C1, C2);
445 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
446 return get(Instruction::Sub, C1, C2);
448 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
449 return get(Instruction::Mul, C1, C2);
451 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
452 return get(Instruction::UDiv, C1, C2);
454 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
455 return get(Instruction::SDiv, C1, C2);
457 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
458 return get(Instruction::FDiv, C1, C2);
460 Constant *ConstantExpr::getRem(Constant *C1, Constant *C2) {
461 return get(Instruction::Rem, C1, C2);
463 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
464 return get(Instruction::And, C1, C2);
466 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
467 return get(Instruction::Or, C1, C2);
469 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
470 return get(Instruction::Xor, C1, C2);
472 Constant *ConstantExpr::getSetEQ(Constant *C1, Constant *C2) {
473 return get(Instruction::SetEQ, C1, C2);
475 Constant *ConstantExpr::getSetNE(Constant *C1, Constant *C2) {
476 return get(Instruction::SetNE, C1, C2);
478 Constant *ConstantExpr::getSetLT(Constant *C1, Constant *C2) {
479 return get(Instruction::SetLT, C1, C2);
481 Constant *ConstantExpr::getSetGT(Constant *C1, Constant *C2) {
482 return get(Instruction::SetGT, C1, C2);
484 Constant *ConstantExpr::getSetLE(Constant *C1, Constant *C2) {
485 return get(Instruction::SetLE, C1, C2);
487 Constant *ConstantExpr::getSetGE(Constant *C1, Constant *C2) {
488 return get(Instruction::SetGE, C1, C2);
490 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
491 return get(Instruction::Shl, C1, C2);
493 Constant *ConstantExpr::getShr(Constant *C1, Constant *C2) {
494 return get(Instruction::Shr, C1, C2);
497 Constant *ConstantExpr::getUShr(Constant *C1, Constant *C2) {
498 if (C1->getType()->isUnsigned()) return getShr(C1, C2);
499 return getCast(getShr(getCast(C1,
500 C1->getType()->getUnsignedVersion()), C2), C1->getType());
503 Constant *ConstantExpr::getSShr(Constant *C1, Constant *C2) {
504 if (C1->getType()->isSigned()) return getShr(C1, C2);
505 return getCast(getShr(getCast(C1,
506 C1->getType()->getSignedVersion()), C2), C1->getType());
509 /// getWithOperandReplaced - Return a constant expression identical to this
510 /// one, but with the specified operand set to the specified value.
511 Constant *ConstantExpr::getWithOperandReplaced(unsigned OpNo,
512 Constant *Op) const {
513 assert(OpNo < getNumOperands() && "Operand num is out of range!");
514 assert(Op->getType() == getOperand(OpNo)->getType() &&
515 "Replacing operand with value of different type!");
516 if (getOperand(OpNo) == Op)
517 return const_cast<ConstantExpr*>(this);
519 Constant *Op0, *Op1, *Op2;
520 switch (getOpcode()) {
521 case Instruction::Cast:
522 return ConstantExpr::getCast(Op, getType());
523 case Instruction::Select:
524 Op0 = (OpNo == 0) ? Op : getOperand(0);
525 Op1 = (OpNo == 1) ? Op : getOperand(1);
526 Op2 = (OpNo == 2) ? Op : getOperand(2);
527 return ConstantExpr::getSelect(Op0, Op1, Op2);
528 case Instruction::InsertElement:
529 Op0 = (OpNo == 0) ? Op : getOperand(0);
530 Op1 = (OpNo == 1) ? Op : getOperand(1);
531 Op2 = (OpNo == 2) ? Op : getOperand(2);
532 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
533 case Instruction::ExtractElement:
534 Op0 = (OpNo == 0) ? Op : getOperand(0);
535 Op1 = (OpNo == 1) ? Op : getOperand(1);
536 return ConstantExpr::getExtractElement(Op0, Op1);
537 case Instruction::ShuffleVector:
538 Op0 = (OpNo == 0) ? Op : getOperand(0);
539 Op1 = (OpNo == 1) ? Op : getOperand(1);
540 Op2 = (OpNo == 2) ? Op : getOperand(2);
541 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
542 case Instruction::GetElementPtr: {
543 std::vector<Constant*> Ops;
544 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
545 Ops.push_back(getOperand(i));
547 return ConstantExpr::getGetElementPtr(Op, Ops);
549 return ConstantExpr::getGetElementPtr(getOperand(0), Ops);
552 assert(getNumOperands() == 2 && "Must be binary operator?");
553 Op0 = (OpNo == 0) ? Op : getOperand(0);
554 Op1 = (OpNo == 1) ? Op : getOperand(1);
555 return ConstantExpr::get(getOpcode(), Op0, Op1);
559 /// getWithOperands - This returns the current constant expression with the
560 /// operands replaced with the specified values. The specified operands must
561 /// match count and type with the existing ones.
562 Constant *ConstantExpr::
563 getWithOperands(const std::vector<Constant*> &Ops) const {
564 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
565 bool AnyChange = false;
566 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
567 assert(Ops[i]->getType() == getOperand(i)->getType() &&
568 "Operand type mismatch!");
569 AnyChange |= Ops[i] != getOperand(i);
571 if (!AnyChange) // No operands changed, return self.
572 return const_cast<ConstantExpr*>(this);
574 switch (getOpcode()) {
575 case Instruction::Cast:
576 return ConstantExpr::getCast(Ops[0], getType());
577 case Instruction::Select:
578 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
579 case Instruction::InsertElement:
580 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
581 case Instruction::ExtractElement:
582 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
583 case Instruction::ShuffleVector:
584 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
585 case Instruction::GetElementPtr: {
586 std::vector<Constant*> ActualOps(Ops.begin()+1, Ops.end());
587 return ConstantExpr::getGetElementPtr(Ops[0], ActualOps);
590 assert(getNumOperands() == 2 && "Must be binary operator?");
591 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
596 //===----------------------------------------------------------------------===//
597 // isValueValidForType implementations
599 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
600 switch (Ty->getTypeID()) {
602 return false; // These can't be represented as integers!!!
604 case Type::SByteTyID:
605 return (Val <= INT8_MAX && Val >= INT8_MIN);
606 case Type::UByteTyID:
607 return (Val >= 0) && (Val <= UINT8_MAX);
608 case Type::ShortTyID:
609 return (Val <= INT16_MAX && Val >= INT16_MIN);
610 case Type::UShortTyID:
611 return (Val >= 0) && (Val <= UINT16_MAX);
613 return (Val <= int(INT32_MAX) && Val >= int(INT32_MIN));
615 return (Val >= 0) && (Val <= UINT32_MAX);
617 case Type::ULongTyID:
618 return true; // always true, has to fit in largest type
622 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
623 switch (Ty->getTypeID()) {
625 return false; // These can't be represented as floating point!
627 // TODO: Figure out how to test if a double can be cast to a float!
628 case Type::FloatTyID:
629 case Type::DoubleTyID:
630 return true; // This is the largest type...
634 //===----------------------------------------------------------------------===//
635 // Factory Function Implementation
637 // ConstantCreator - A class that is used to create constants by
638 // ValueMap*. This class should be partially specialized if there is
639 // something strange that needs to be done to interface to the ctor for the
643 template<class ConstantClass, class TypeClass, class ValType>
644 struct VISIBILITY_HIDDEN ConstantCreator {
645 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
646 return new ConstantClass(Ty, V);
650 template<class ConstantClass, class TypeClass>
651 struct VISIBILITY_HIDDEN ConvertConstantType {
652 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
653 assert(0 && "This type cannot be converted!\n");
658 template<class ValType, class TypeClass, class ConstantClass,
659 bool HasLargeKey = false /*true for arrays and structs*/ >
660 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
662 typedef std::pair<const Type*, ValType> MapKey;
663 typedef std::map<MapKey, Constant *> MapTy;
664 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
665 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
667 /// Map - This is the main map from the element descriptor to the Constants.
668 /// This is the primary way we avoid creating two of the same shape
672 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
673 /// from the constants to their element in Map. This is important for
674 /// removal of constants from the array, which would otherwise have to scan
675 /// through the map with very large keys.
676 InverseMapTy InverseMap;
678 /// AbstractTypeMap - Map for abstract type constants.
680 AbstractTypeMapTy AbstractTypeMap;
683 void clear(std::vector<Constant *> &Constants) {
684 for(typename MapTy::iterator I = Map.begin(); I != Map.end(); ++I)
685 Constants.push_back(I->second);
687 AbstractTypeMap.clear();
692 typename MapTy::iterator map_end() { return Map.end(); }
694 /// InsertOrGetItem - Return an iterator for the specified element.
695 /// If the element exists in the map, the returned iterator points to the
696 /// entry and Exists=true. If not, the iterator points to the newly
697 /// inserted entry and returns Exists=false. Newly inserted entries have
698 /// I->second == 0, and should be filled in.
699 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
702 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
708 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
710 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
711 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
712 IMI->second->second == CP &&
713 "InverseMap corrupt!");
717 typename MapTy::iterator I =
718 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
719 if (I == Map.end() || I->second != CP) {
720 // FIXME: This should not use a linear scan. If this gets to be a
721 // performance problem, someone should look at this.
722 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
729 /// getOrCreate - Return the specified constant from the map, creating it if
731 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
732 MapKey Lookup(Ty, V);
733 typename MapTy::iterator I = Map.lower_bound(Lookup);
735 if (I != Map.end() && I->first == Lookup)
736 return static_cast<ConstantClass *>(I->second);
738 // If no preexisting value, create one now...
739 ConstantClass *Result =
740 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
742 /// FIXME: why does this assert fail when loading 176.gcc?
743 //assert(Result->getType() == Ty && "Type specified is not correct!");
744 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
746 if (HasLargeKey) // Remember the reverse mapping if needed.
747 InverseMap.insert(std::make_pair(Result, I));
749 // If the type of the constant is abstract, make sure that an entry exists
750 // for it in the AbstractTypeMap.
751 if (Ty->isAbstract()) {
752 typename AbstractTypeMapTy::iterator TI =
753 AbstractTypeMap.lower_bound(Ty);
755 if (TI == AbstractTypeMap.end() || TI->first != Ty) {
756 // Add ourselves to the ATU list of the type.
757 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
759 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
765 void remove(ConstantClass *CP) {
766 typename MapTy::iterator I = FindExistingElement(CP);
767 assert(I != Map.end() && "Constant not found in constant table!");
768 assert(I->second == CP && "Didn't find correct element?");
770 if (HasLargeKey) // Remember the reverse mapping if needed.
771 InverseMap.erase(CP);
773 // Now that we found the entry, make sure this isn't the entry that
774 // the AbstractTypeMap points to.
775 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
776 if (Ty->isAbstract()) {
777 assert(AbstractTypeMap.count(Ty) &&
778 "Abstract type not in AbstractTypeMap?");
779 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
780 if (ATMEntryIt == I) {
781 // Yes, we are removing the representative entry for this type.
782 // See if there are any other entries of the same type.
783 typename MapTy::iterator TmpIt = ATMEntryIt;
785 // First check the entry before this one...
786 if (TmpIt != Map.begin()) {
788 if (TmpIt->first.first != Ty) // Not the same type, move back...
792 // If we didn't find the same type, try to move forward...
793 if (TmpIt == ATMEntryIt) {
795 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
796 --TmpIt; // No entry afterwards with the same type
799 // If there is another entry in the map of the same abstract type,
800 // update the AbstractTypeMap entry now.
801 if (TmpIt != ATMEntryIt) {
804 // Otherwise, we are removing the last instance of this type
805 // from the table. Remove from the ATM, and from user list.
806 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
807 AbstractTypeMap.erase(Ty);
816 /// MoveConstantToNewSlot - If we are about to change C to be the element
817 /// specified by I, update our internal data structures to reflect this
819 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
820 // First, remove the old location of the specified constant in the map.
821 typename MapTy::iterator OldI = FindExistingElement(C);
822 assert(OldI != Map.end() && "Constant not found in constant table!");
823 assert(OldI->second == C && "Didn't find correct element?");
825 // If this constant is the representative element for its abstract type,
826 // update the AbstractTypeMap so that the representative element is I.
827 if (C->getType()->isAbstract()) {
828 typename AbstractTypeMapTy::iterator ATI =
829 AbstractTypeMap.find(C->getType());
830 assert(ATI != AbstractTypeMap.end() &&
831 "Abstract type not in AbstractTypeMap?");
832 if (ATI->second == OldI)
836 // Remove the old entry from the map.
839 // Update the inverse map so that we know that this constant is now
840 // located at descriptor I.
842 assert(I->second == C && "Bad inversemap entry!");
847 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
848 typename AbstractTypeMapTy::iterator I =
849 AbstractTypeMap.find(cast<Type>(OldTy));
851 assert(I != AbstractTypeMap.end() &&
852 "Abstract type not in AbstractTypeMap?");
854 // Convert a constant at a time until the last one is gone. The last one
855 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
856 // eliminated eventually.
858 ConvertConstantType<ConstantClass,
860 static_cast<ConstantClass *>(I->second->second),
861 cast<TypeClass>(NewTy));
863 I = AbstractTypeMap.find(cast<Type>(OldTy));
864 } while (I != AbstractTypeMap.end());
867 // If the type became concrete without being refined to any other existing
868 // type, we just remove ourselves from the ATU list.
869 void typeBecameConcrete(const DerivedType *AbsTy) {
870 AbsTy->removeAbstractTypeUser(this);
874 std::cerr << "Constant.cpp: ValueMap\n";
880 //---- ConstantBool::get*() implementation.
882 ConstantBool *ConstantBool::getTrue() {
883 static ConstantBool *T = 0;
885 return T = new ConstantBool(true);
887 ConstantBool *ConstantBool::getFalse() {
888 static ConstantBool *F = 0;
890 return F = new ConstantBool(false);
893 //---- ConstantInt::get() implementations...
895 static ManagedStatic<ValueMap<uint64_t, Type, ConstantInt> > IntConstants;
897 // Get a ConstantInt from an int64_t. Note here that we canoncialize the value
898 // to a uint64_t value that has been zero extended down to the size of the
899 // integer type of the ConstantInt. This allows the getZExtValue method to
900 // just return the stored value while getSExtValue has to convert back to sign
901 // extended. getZExtValue is more common in LLVM than getSExtValue().
902 ConstantInt *ConstantInt::get(const Type *Ty, int64_t V) {
903 unsigned Size = Ty->getPrimitiveSizeInBits();
904 uint64_t ZeroExtendedCanonicalization = V & (~uint64_t(0UL) >> (64-Size));
905 return IntConstants->getOrCreate(Ty, ZeroExtendedCanonicalization );
908 //---- ConstantFP::get() implementation...
912 struct ConstantCreator<ConstantFP, Type, uint64_t> {
913 static ConstantFP *create(const Type *Ty, uint64_t V) {
914 assert(Ty == Type::DoubleTy);
915 return new ConstantFP(Ty, BitsToDouble(V));
919 struct ConstantCreator<ConstantFP, Type, uint32_t> {
920 static ConstantFP *create(const Type *Ty, uint32_t V) {
921 assert(Ty == Type::FloatTy);
922 return new ConstantFP(Ty, BitsToFloat(V));
927 static ManagedStatic<ValueMap<uint64_t, Type, ConstantFP> > DoubleConstants;
928 static ManagedStatic<ValueMap<uint32_t, Type, ConstantFP> > FloatConstants;
930 bool ConstantFP::isNullValue() const {
931 return DoubleToBits(Val) == 0;
934 bool ConstantFP::isExactlyValue(double V) const {
935 return DoubleToBits(V) == DoubleToBits(Val);
939 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
940 if (Ty == Type::FloatTy) {
941 // Force the value through memory to normalize it.
942 return FloatConstants->getOrCreate(Ty, FloatToBits(V));
944 assert(Ty == Type::DoubleTy);
945 return DoubleConstants->getOrCreate(Ty, DoubleToBits(V));
949 //---- ConstantAggregateZero::get() implementation...
952 // ConstantAggregateZero does not take extra "value" argument...
953 template<class ValType>
954 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
955 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
956 return new ConstantAggregateZero(Ty);
961 struct ConvertConstantType<ConstantAggregateZero, Type> {
962 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
963 // Make everyone now use a constant of the new type...
964 Constant *New = ConstantAggregateZero::get(NewTy);
965 assert(New != OldC && "Didn't replace constant??");
966 OldC->uncheckedReplaceAllUsesWith(New);
967 OldC->destroyConstant(); // This constant is now dead, destroy it.
972 static ManagedStatic<ValueMap<char, Type,
973 ConstantAggregateZero> > AggZeroConstants;
975 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
977 Constant *ConstantAggregateZero::get(const Type *Ty) {
978 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<PackedType>(Ty)) &&
979 "Cannot create an aggregate zero of non-aggregate type!");
980 return AggZeroConstants->getOrCreate(Ty, 0);
983 // destroyConstant - Remove the constant from the constant table...
985 void ConstantAggregateZero::destroyConstant() {
986 AggZeroConstants->remove(this);
987 destroyConstantImpl();
990 //---- ConstantArray::get() implementation...
994 struct ConvertConstantType<ConstantArray, ArrayType> {
995 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
996 // Make everyone now use a constant of the new type...
997 std::vector<Constant*> C;
998 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
999 C.push_back(cast<Constant>(OldC->getOperand(i)));
1000 Constant *New = ConstantArray::get(NewTy, C);
1001 assert(New != OldC && "Didn't replace constant??");
1002 OldC->uncheckedReplaceAllUsesWith(New);
1003 OldC->destroyConstant(); // This constant is now dead, destroy it.
1008 static std::vector<Constant*> getValType(ConstantArray *CA) {
1009 std::vector<Constant*> Elements;
1010 Elements.reserve(CA->getNumOperands());
1011 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1012 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1016 typedef ValueMap<std::vector<Constant*>, ArrayType,
1017 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1018 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1020 Constant *ConstantArray::get(const ArrayType *Ty,
1021 const std::vector<Constant*> &V) {
1022 // If this is an all-zero array, return a ConstantAggregateZero object
1025 if (!C->isNullValue())
1026 return ArrayConstants->getOrCreate(Ty, V);
1027 for (unsigned i = 1, e = V.size(); i != e; ++i)
1029 return ArrayConstants->getOrCreate(Ty, V);
1031 return ConstantAggregateZero::get(Ty);
1034 // destroyConstant - Remove the constant from the constant table...
1036 void ConstantArray::destroyConstant() {
1037 ArrayConstants->remove(this);
1038 destroyConstantImpl();
1041 /// ConstantArray::get(const string&) - Return an array that is initialized to
1042 /// contain the specified string. If length is zero then a null terminator is
1043 /// added to the specified string so that it may be used in a natural way.
1044 /// Otherwise, the length parameter specifies how much of the string to use
1045 /// and it won't be null terminated.
1047 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1048 std::vector<Constant*> ElementVals;
1049 for (unsigned i = 0; i < Str.length(); ++i)
1050 ElementVals.push_back(ConstantInt::get(Type::SByteTy, Str[i]));
1052 // Add a null terminator to the string...
1054 ElementVals.push_back(ConstantInt::get(Type::SByteTy, 0));
1057 ArrayType *ATy = ArrayType::get(Type::SByteTy, ElementVals.size());
1058 return ConstantArray::get(ATy, ElementVals);
1061 /// isString - This method returns true if the array is an array of sbyte or
1062 /// ubyte, and if the elements of the array are all ConstantInt's.
1063 bool ConstantArray::isString() const {
1064 // Check the element type for sbyte or ubyte...
1065 if (getType()->getElementType() != Type::UByteTy &&
1066 getType()->getElementType() != Type::SByteTy)
1068 // Check the elements to make sure they are all integers, not constant
1070 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1071 if (!isa<ConstantInt>(getOperand(i)))
1076 /// isCString - This method returns true if the array is a string (see
1077 /// isString) and it ends in a null byte \0 and does not contains any other
1078 /// null bytes except its terminator.
1079 bool ConstantArray::isCString() const {
1080 // Check the element type for sbyte or ubyte...
1081 if (getType()->getElementType() != Type::UByteTy &&
1082 getType()->getElementType() != Type::SByteTy)
1084 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1085 // Last element must be a null.
1086 if (getOperand(getNumOperands()-1) != Zero)
1088 // Other elements must be non-null integers.
1089 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1090 if (!isa<ConstantInt>(getOperand(i)))
1092 if (getOperand(i) == Zero)
1099 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
1100 // then this method converts the array to an std::string and returns it.
1101 // Otherwise, it asserts out.
1103 std::string ConstantArray::getAsString() const {
1104 assert(isString() && "Not a string!");
1106 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1107 Result += (char)cast<ConstantInt>(getOperand(i))->getZExtValue();
1112 //---- ConstantStruct::get() implementation...
1117 struct ConvertConstantType<ConstantStruct, StructType> {
1118 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1119 // Make everyone now use a constant of the new type...
1120 std::vector<Constant*> C;
1121 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1122 C.push_back(cast<Constant>(OldC->getOperand(i)));
1123 Constant *New = ConstantStruct::get(NewTy, C);
1124 assert(New != OldC && "Didn't replace constant??");
1126 OldC->uncheckedReplaceAllUsesWith(New);
1127 OldC->destroyConstant(); // This constant is now dead, destroy it.
1132 typedef ValueMap<std::vector<Constant*>, StructType,
1133 ConstantStruct, true /*largekey*/> StructConstantsTy;
1134 static ManagedStatic<StructConstantsTy> StructConstants;
1136 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1137 std::vector<Constant*> Elements;
1138 Elements.reserve(CS->getNumOperands());
1139 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1140 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1144 Constant *ConstantStruct::get(const StructType *Ty,
1145 const std::vector<Constant*> &V) {
1146 // Create a ConstantAggregateZero value if all elements are zeros...
1147 for (unsigned i = 0, e = V.size(); i != e; ++i)
1148 if (!V[i]->isNullValue())
1149 return StructConstants->getOrCreate(Ty, V);
1151 return ConstantAggregateZero::get(Ty);
1154 Constant *ConstantStruct::get(const std::vector<Constant*> &V) {
1155 std::vector<const Type*> StructEls;
1156 StructEls.reserve(V.size());
1157 for (unsigned i = 0, e = V.size(); i != e; ++i)
1158 StructEls.push_back(V[i]->getType());
1159 return get(StructType::get(StructEls), V);
1162 // destroyConstant - Remove the constant from the constant table...
1164 void ConstantStruct::destroyConstant() {
1165 StructConstants->remove(this);
1166 destroyConstantImpl();
1169 //---- ConstantPacked::get() implementation...
1173 struct ConvertConstantType<ConstantPacked, PackedType> {
1174 static void convert(ConstantPacked *OldC, const PackedType *NewTy) {
1175 // Make everyone now use a constant of the new type...
1176 std::vector<Constant*> C;
1177 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1178 C.push_back(cast<Constant>(OldC->getOperand(i)));
1179 Constant *New = ConstantPacked::get(NewTy, C);
1180 assert(New != OldC && "Didn't replace constant??");
1181 OldC->uncheckedReplaceAllUsesWith(New);
1182 OldC->destroyConstant(); // This constant is now dead, destroy it.
1187 static std::vector<Constant*> getValType(ConstantPacked *CP) {
1188 std::vector<Constant*> Elements;
1189 Elements.reserve(CP->getNumOperands());
1190 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1191 Elements.push_back(CP->getOperand(i));
1195 static ManagedStatic<ValueMap<std::vector<Constant*>, PackedType,
1196 ConstantPacked> > PackedConstants;
1198 Constant *ConstantPacked::get(const PackedType *Ty,
1199 const std::vector<Constant*> &V) {
1200 // If this is an all-zero packed, return a ConstantAggregateZero object
1203 if (!C->isNullValue())
1204 return PackedConstants->getOrCreate(Ty, V);
1205 for (unsigned i = 1, e = V.size(); i != e; ++i)
1207 return PackedConstants->getOrCreate(Ty, V);
1209 return ConstantAggregateZero::get(Ty);
1212 Constant *ConstantPacked::get(const std::vector<Constant*> &V) {
1213 assert(!V.empty() && "Cannot infer type if V is empty");
1214 return get(PackedType::get(V.front()->getType(),V.size()), V);
1217 // destroyConstant - Remove the constant from the constant table...
1219 void ConstantPacked::destroyConstant() {
1220 PackedConstants->remove(this);
1221 destroyConstantImpl();
1224 //---- ConstantPointerNull::get() implementation...
1228 // ConstantPointerNull does not take extra "value" argument...
1229 template<class ValType>
1230 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1231 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1232 return new ConstantPointerNull(Ty);
1237 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1238 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1239 // Make everyone now use a constant of the new type...
1240 Constant *New = ConstantPointerNull::get(NewTy);
1241 assert(New != OldC && "Didn't replace constant??");
1242 OldC->uncheckedReplaceAllUsesWith(New);
1243 OldC->destroyConstant(); // This constant is now dead, destroy it.
1248 static ManagedStatic<ValueMap<char, PointerType,
1249 ConstantPointerNull> > NullPtrConstants;
1251 static char getValType(ConstantPointerNull *) {
1256 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1257 return NullPtrConstants->getOrCreate(Ty, 0);
1260 // destroyConstant - Remove the constant from the constant table...
1262 void ConstantPointerNull::destroyConstant() {
1263 NullPtrConstants->remove(this);
1264 destroyConstantImpl();
1268 //---- UndefValue::get() implementation...
1272 // UndefValue does not take extra "value" argument...
1273 template<class ValType>
1274 struct ConstantCreator<UndefValue, Type, ValType> {
1275 static UndefValue *create(const Type *Ty, const ValType &V) {
1276 return new UndefValue(Ty);
1281 struct ConvertConstantType<UndefValue, Type> {
1282 static void convert(UndefValue *OldC, const Type *NewTy) {
1283 // Make everyone now use a constant of the new type.
1284 Constant *New = UndefValue::get(NewTy);
1285 assert(New != OldC && "Didn't replace constant??");
1286 OldC->uncheckedReplaceAllUsesWith(New);
1287 OldC->destroyConstant(); // This constant is now dead, destroy it.
1292 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1294 static char getValType(UndefValue *) {
1299 UndefValue *UndefValue::get(const Type *Ty) {
1300 return UndefValueConstants->getOrCreate(Ty, 0);
1303 // destroyConstant - Remove the constant from the constant table.
1305 void UndefValue::destroyConstant() {
1306 UndefValueConstants->remove(this);
1307 destroyConstantImpl();
1313 //---- ConstantExpr::get() implementations...
1315 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
1319 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1320 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
1321 if (V.first == Instruction::Cast)
1322 return new UnaryConstantExpr(Instruction::Cast, V.second[0], Ty);
1323 if ((V.first >= Instruction::BinaryOpsBegin &&
1324 V.first < Instruction::BinaryOpsEnd) ||
1325 V.first == Instruction::Shl || V.first == Instruction::Shr)
1326 return new BinaryConstantExpr(V.first, V.second[0], V.second[1]);
1327 if (V.first == Instruction::Select)
1328 return new SelectConstantExpr(V.second[0], V.second[1], V.second[2]);
1329 if (V.first == Instruction::ExtractElement)
1330 return new ExtractElementConstantExpr(V.second[0], V.second[1]);
1331 if (V.first == Instruction::InsertElement)
1332 return new InsertElementConstantExpr(V.second[0], V.second[1],
1334 if (V.first == Instruction::ShuffleVector)
1335 return new ShuffleVectorConstantExpr(V.second[0], V.second[1],
1338 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
1340 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
1341 return new GetElementPtrConstantExpr(V.second[0], IdxList, Ty);
1346 struct ConvertConstantType<ConstantExpr, Type> {
1347 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1349 switch (OldC->getOpcode()) {
1350 case Instruction::Cast:
1351 New = ConstantExpr::getCast(OldC->getOperand(0), NewTy);
1353 case Instruction::Select:
1354 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1355 OldC->getOperand(1),
1356 OldC->getOperand(2));
1358 case Instruction::Shl:
1359 case Instruction::Shr:
1360 New = ConstantExpr::getShiftTy(NewTy, OldC->getOpcode(),
1361 OldC->getOperand(0), OldC->getOperand(1));
1364 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1365 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1366 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1367 OldC->getOperand(1));
1369 case Instruction::GetElementPtr:
1370 // Make everyone now use a constant of the new type...
1371 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1372 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0), Idx);
1376 assert(New != OldC && "Didn't replace constant??");
1377 OldC->uncheckedReplaceAllUsesWith(New);
1378 OldC->destroyConstant(); // This constant is now dead, destroy it.
1381 } // end namespace llvm
1384 static ExprMapKeyType getValType(ConstantExpr *CE) {
1385 std::vector<Constant*> Operands;
1386 Operands.reserve(CE->getNumOperands());
1387 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1388 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1389 return ExprMapKeyType(CE->getOpcode(), Operands);
1392 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1393 ConstantExpr> > ExprConstants;
1395 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
1396 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1398 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
1399 return FC; // Fold a few common cases...
1401 // Look up the constant in the table first to ensure uniqueness
1402 std::vector<Constant*> argVec(1, C);
1403 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
1404 return ExprConstants->getOrCreate(Ty, Key);
1407 Constant *ConstantExpr::getSignExtend(Constant *C, const Type *Ty) {
1408 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1409 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1410 "This is an illegal sign extension!");
1411 if (C->getType() != Type::BoolTy) {
1412 C = ConstantExpr::getCast(C, C->getType()->getSignedVersion());
1413 return ConstantExpr::getCast(C, Ty);
1415 if (C == ConstantBool::getTrue())
1416 return ConstantIntegral::getAllOnesValue(Ty);
1418 return ConstantIntegral::getNullValue(Ty);
1422 Constant *ConstantExpr::getZeroExtend(Constant *C, const Type *Ty) {
1423 assert(C->getType()->isIntegral() && Ty->isIntegral() &&
1424 C->getType()->getPrimitiveSize() <= Ty->getPrimitiveSize() &&
1425 "This is an illegal zero extension!");
1426 if (C->getType() != Type::BoolTy)
1427 C = ConstantExpr::getCast(C, C->getType()->getUnsignedVersion());
1428 return ConstantExpr::getCast(C, Ty);
1431 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1432 // sizeof is implemented as: (ulong) gep (Ty*)null, 1
1434 getGetElementPtr(getNullValue(PointerType::get(Ty)),
1435 std::vector<Constant*>(1, ConstantInt::get(Type::UIntTy, 1))),
1439 Constant *ConstantExpr::getPtrPtrFromArrayPtr(Constant *C) {
1440 // pointer from array is implemented as: getelementptr arr ptr, 0, 0
1441 static std::vector<Constant*> Indices(2, ConstantInt::get(Type::UIntTy, 0));
1443 return ConstantExpr::getGetElementPtr(C, Indices);
1446 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1447 Constant *C1, Constant *C2) {
1448 if (Opcode == Instruction::Shl || Opcode == Instruction::Shr)
1449 return getShiftTy(ReqTy, Opcode, C1, C2);
1450 // Check the operands for consistency first
1451 assert((Opcode >= Instruction::BinaryOpsBegin &&
1452 Opcode < Instruction::BinaryOpsEnd) &&
1453 "Invalid opcode in binary constant expression");
1454 assert(C1->getType() == C2->getType() &&
1455 "Operand types in binary constant expression should match");
1457 if (ReqTy == C1->getType() || (Instruction::isComparison(Opcode) &&
1458 ReqTy == Type::BoolTy))
1459 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1460 return FC; // Fold a few common cases...
1462 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1463 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1464 return ExprConstants->getOrCreate(ReqTy, Key);
1467 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1470 case Instruction::Add: case Instruction::Sub:
1471 case Instruction::Mul:
1472 case Instruction::Rem:
1473 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1474 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
1475 isa<PackedType>(C1->getType())) &&
1476 "Tried to create an arithmetic operation on a non-arithmetic type!");
1479 case Instruction::UDiv:
1480 case Instruction::SDiv:
1481 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1482 assert((C1->getType()->isInteger() || (isa<PackedType>(C1->getType()) &&
1483 cast<PackedType>(C1->getType())->getElementType()->isInteger())) &&
1484 "Tried to create an arithmetic operation on a non-arithmetic type!");
1486 case Instruction::FDiv:
1487 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1488 assert((C1->getType()->isFloatingPoint() || (isa<PackedType>(C1->getType())
1489 && cast<PackedType>(C1->getType())->getElementType()->isFloatingPoint()))
1490 && "Tried to create an arithmetic operation on a non-arithmetic type!");
1492 case Instruction::And:
1493 case Instruction::Or:
1494 case Instruction::Xor:
1495 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1496 assert((C1->getType()->isIntegral() || isa<PackedType>(C1->getType())) &&
1497 "Tried to create a logical operation on a non-integral type!");
1499 case Instruction::SetLT: case Instruction::SetGT: case Instruction::SetLE:
1500 case Instruction::SetGE: case Instruction::SetEQ: case Instruction::SetNE:
1501 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1503 case Instruction::Shl:
1504 case Instruction::Shr:
1505 assert(C2->getType() == Type::UByteTy && "Shift should be by ubyte!");
1506 assert((C1->getType()->isInteger() || isa<PackedType>(C1->getType())) &&
1507 "Tried to create a shift operation on a non-integer type!");
1514 if (Instruction::isComparison(Opcode))
1515 return getTy(Type::BoolTy, Opcode, C1, C2);
1517 return getTy(C1->getType(), Opcode, C1, C2);
1520 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1521 Constant *V1, Constant *V2) {
1522 assert(C->getType() == Type::BoolTy && "Select condition must be bool!");
1523 assert(V1->getType() == V2->getType() && "Select value types must match!");
1524 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
1526 if (ReqTy == V1->getType())
1527 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1528 return SC; // Fold common cases
1530 std::vector<Constant*> argVec(3, C);
1533 ExprMapKeyType Key = std::make_pair(Instruction::Select, argVec);
1534 return ExprConstants->getOrCreate(ReqTy, Key);
1537 /// getShiftTy - Return a shift left or shift right constant expr
1538 Constant *ConstantExpr::getShiftTy(const Type *ReqTy, unsigned Opcode,
1539 Constant *C1, Constant *C2) {
1540 // Check the operands for consistency first
1541 assert((Opcode == Instruction::Shl ||
1542 Opcode == Instruction::Shr) &&
1543 "Invalid opcode in binary constant expression");
1544 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
1545 "Invalid operand types for Shift constant expr!");
1547 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1548 return FC; // Fold a few common cases...
1550 // Look up the constant in the table first to ensure uniqueness
1551 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1552 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
1553 return ExprConstants->getOrCreate(ReqTy, Key);
1557 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1558 const std::vector<Value*> &IdxList) {
1559 assert(GetElementPtrInst::getIndexedType(C->getType(), IdxList, true) &&
1560 "GEP indices invalid!");
1562 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
1563 return FC; // Fold a few common cases...
1565 assert(isa<PointerType>(C->getType()) &&
1566 "Non-pointer type for constant GetElementPtr expression");
1567 // Look up the constant in the table first to ensure uniqueness
1568 std::vector<Constant*> ArgVec;
1569 ArgVec.reserve(IdxList.size()+1);
1570 ArgVec.push_back(C);
1571 for (unsigned i = 0, e = IdxList.size(); i != e; ++i)
1572 ArgVec.push_back(cast<Constant>(IdxList[i]));
1573 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,ArgVec);
1574 return ExprConstants->getOrCreate(ReqTy, Key);
1577 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1578 const std::vector<Constant*> &IdxList){
1579 // Get the result type of the getelementptr!
1580 std::vector<Value*> VIdxList(IdxList.begin(), IdxList.end());
1582 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), VIdxList,
1584 assert(Ty && "GEP indices invalid!");
1585 return getGetElementPtrTy(PointerType::get(Ty), C, VIdxList);
1588 Constant *ConstantExpr::getGetElementPtr(Constant *C,
1589 const std::vector<Value*> &IdxList) {
1590 // Get the result type of the getelementptr!
1591 const Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), IdxList,
1593 assert(Ty && "GEP indices invalid!");
1594 return getGetElementPtrTy(PointerType::get(Ty), C, IdxList);
1597 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1599 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1600 return FC; // Fold a few common cases...
1601 // Look up the constant in the table first to ensure uniqueness
1602 std::vector<Constant*> ArgVec(1, Val);
1603 ArgVec.push_back(Idx);
1604 const ExprMapKeyType &Key = std::make_pair(Instruction::ExtractElement,ArgVec);
1605 return ExprConstants->getOrCreate(ReqTy, Key);
1608 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1609 assert(isa<PackedType>(Val->getType()) &&
1610 "Tried to create extractelement operation on non-packed type!");
1611 assert(Idx->getType() == Type::UIntTy &&
1612 "Extractelement index must be uint type!");
1613 return getExtractElementTy(cast<PackedType>(Val->getType())->getElementType(),
1617 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1618 Constant *Elt, Constant *Idx) {
1619 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1620 return FC; // Fold a few common cases...
1621 // Look up the constant in the table first to ensure uniqueness
1622 std::vector<Constant*> ArgVec(1, Val);
1623 ArgVec.push_back(Elt);
1624 ArgVec.push_back(Idx);
1625 const ExprMapKeyType &Key = std::make_pair(Instruction::InsertElement,ArgVec);
1626 return ExprConstants->getOrCreate(ReqTy, Key);
1629 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1631 assert(isa<PackedType>(Val->getType()) &&
1632 "Tried to create insertelement operation on non-packed type!");
1633 assert(Elt->getType() == cast<PackedType>(Val->getType())->getElementType()
1634 && "Insertelement types must match!");
1635 assert(Idx->getType() == Type::UIntTy &&
1636 "Insertelement index must be uint type!");
1637 return getInsertElementTy(cast<PackedType>(Val->getType())->getElementType(),
1641 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1642 Constant *V2, Constant *Mask) {
1643 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1644 return FC; // Fold a few common cases...
1645 // Look up the constant in the table first to ensure uniqueness
1646 std::vector<Constant*> ArgVec(1, V1);
1647 ArgVec.push_back(V2);
1648 ArgVec.push_back(Mask);
1649 const ExprMapKeyType &Key = std::make_pair(Instruction::ShuffleVector,ArgVec);
1650 return ExprConstants->getOrCreate(ReqTy, Key);
1653 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1655 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1656 "Invalid shuffle vector constant expr operands!");
1657 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
1661 // destroyConstant - Remove the constant from the constant table...
1663 void ConstantExpr::destroyConstant() {
1664 ExprConstants->remove(this);
1665 destroyConstantImpl();
1668 const char *ConstantExpr::getOpcodeName() const {
1669 return Instruction::getOpcodeName(getOpcode());
1672 //===----------------------------------------------------------------------===//
1673 // replaceUsesOfWithOnConstant implementations
1675 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1677 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1678 Constant *ToC = cast<Constant>(To);
1680 unsigned OperandToUpdate = U-OperandList;
1681 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1683 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
1684 Lookup.first.first = getType();
1685 Lookup.second = this;
1687 std::vector<Constant*> &Values = Lookup.first.second;
1688 Values.reserve(getNumOperands()); // Build replacement array.
1690 // Fill values with the modified operands of the constant array. Also,
1691 // compute whether this turns into an all-zeros array.
1692 bool isAllZeros = false;
1693 if (!ToC->isNullValue()) {
1694 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1695 Values.push_back(cast<Constant>(O->get()));
1698 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1699 Constant *Val = cast<Constant>(O->get());
1700 Values.push_back(Val);
1701 if (isAllZeros) isAllZeros = Val->isNullValue();
1704 Values[OperandToUpdate] = ToC;
1706 Constant *Replacement = 0;
1708 Replacement = ConstantAggregateZero::get(getType());
1710 // Check to see if we have this array type already.
1712 ArrayConstantsTy::MapTy::iterator I =
1713 ArrayConstants->InsertOrGetItem(Lookup, Exists);
1716 Replacement = I->second;
1718 // Okay, the new shape doesn't exist in the system yet. Instead of
1719 // creating a new constant array, inserting it, replaceallusesof'ing the
1720 // old with the new, then deleting the old... just update the current one
1722 ArrayConstants->MoveConstantToNewSlot(this, I);
1724 // Update to the new value.
1725 setOperand(OperandToUpdate, ToC);
1730 // Otherwise, I do need to replace this with an existing value.
1731 assert(Replacement != this && "I didn't contain From!");
1733 // Everyone using this now uses the replacement.
1734 uncheckedReplaceAllUsesWith(Replacement);
1736 // Delete the old constant!
1740 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1742 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1743 Constant *ToC = cast<Constant>(To);
1745 unsigned OperandToUpdate = U-OperandList;
1746 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1748 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
1749 Lookup.first.first = getType();
1750 Lookup.second = this;
1751 std::vector<Constant*> &Values = Lookup.first.second;
1752 Values.reserve(getNumOperands()); // Build replacement struct.
1755 // Fill values with the modified operands of the constant struct. Also,
1756 // compute whether this turns into an all-zeros struct.
1757 bool isAllZeros = false;
1758 if (!ToC->isNullValue()) {
1759 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
1760 Values.push_back(cast<Constant>(O->get()));
1763 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1764 Constant *Val = cast<Constant>(O->get());
1765 Values.push_back(Val);
1766 if (isAllZeros) isAllZeros = Val->isNullValue();
1769 Values[OperandToUpdate] = ToC;
1771 Constant *Replacement = 0;
1773 Replacement = ConstantAggregateZero::get(getType());
1775 // Check to see if we have this array type already.
1777 StructConstantsTy::MapTy::iterator I =
1778 StructConstants->InsertOrGetItem(Lookup, Exists);
1781 Replacement = I->second;
1783 // Okay, the new shape doesn't exist in the system yet. Instead of
1784 // creating a new constant struct, inserting it, replaceallusesof'ing the
1785 // old with the new, then deleting the old... just update the current one
1787 StructConstants->MoveConstantToNewSlot(this, I);
1789 // Update to the new value.
1790 setOperand(OperandToUpdate, ToC);
1795 assert(Replacement != this && "I didn't contain From!");
1797 // Everyone using this now uses the replacement.
1798 uncheckedReplaceAllUsesWith(Replacement);
1800 // Delete the old constant!
1804 void ConstantPacked::replaceUsesOfWithOnConstant(Value *From, Value *To,
1806 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1808 std::vector<Constant*> Values;
1809 Values.reserve(getNumOperands()); // Build replacement array...
1810 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1811 Constant *Val = getOperand(i);
1812 if (Val == From) Val = cast<Constant>(To);
1813 Values.push_back(Val);
1816 Constant *Replacement = ConstantPacked::get(getType(), Values);
1817 assert(Replacement != this && "I didn't contain From!");
1819 // Everyone using this now uses the replacement.
1820 uncheckedReplaceAllUsesWith(Replacement);
1822 // Delete the old constant!
1826 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1828 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1829 Constant *To = cast<Constant>(ToV);
1831 Constant *Replacement = 0;
1832 if (getOpcode() == Instruction::GetElementPtr) {
1833 std::vector<Constant*> Indices;
1834 Constant *Pointer = getOperand(0);
1835 Indices.reserve(getNumOperands()-1);
1836 if (Pointer == From) Pointer = To;
1838 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1839 Constant *Val = getOperand(i);
1840 if (Val == From) Val = To;
1841 Indices.push_back(Val);
1843 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
1844 } else if (getOpcode() == Instruction::Cast) {
1845 assert(getOperand(0) == From && "Cast only has one use!");
1846 Replacement = ConstantExpr::getCast(To, getType());
1847 } else if (getOpcode() == Instruction::Select) {
1848 Constant *C1 = getOperand(0);
1849 Constant *C2 = getOperand(1);
1850 Constant *C3 = getOperand(2);
1851 if (C1 == From) C1 = To;
1852 if (C2 == From) C2 = To;
1853 if (C3 == From) C3 = To;
1854 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1855 } else if (getOpcode() == Instruction::ExtractElement) {
1856 Constant *C1 = getOperand(0);
1857 Constant *C2 = getOperand(1);
1858 if (C1 == From) C1 = To;
1859 if (C2 == From) C2 = To;
1860 Replacement = ConstantExpr::getExtractElement(C1, C2);
1861 } else if (getOpcode() == Instruction::InsertElement) {
1862 Constant *C1 = getOperand(0);
1863 Constant *C2 = getOperand(1);
1864 Constant *C3 = getOperand(1);
1865 if (C1 == From) C1 = To;
1866 if (C2 == From) C2 = To;
1867 if (C3 == From) C3 = To;
1868 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
1869 } else if (getOpcode() == Instruction::ShuffleVector) {
1870 Constant *C1 = getOperand(0);
1871 Constant *C2 = getOperand(1);
1872 Constant *C3 = getOperand(2);
1873 if (C1 == From) C1 = To;
1874 if (C2 == From) C2 = To;
1875 if (C3 == From) C3 = To;
1876 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
1877 } else if (getNumOperands() == 2) {
1878 Constant *C1 = getOperand(0);
1879 Constant *C2 = getOperand(1);
1880 if (C1 == From) C1 = To;
1881 if (C2 == From) C2 = To;
1882 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
1884 assert(0 && "Unknown ConstantExpr type!");
1888 assert(Replacement != this && "I didn't contain From!");
1890 // Everyone using this now uses the replacement.
1891 uncheckedReplaceAllUsesWith(Replacement);
1893 // Delete the old constant!
1898 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
1899 /// global into a string value. Return an empty string if we can't do it.
1900 /// Parameter Chop determines if the result is chopped at the first null
1903 std::string Constant::getStringValue(bool Chop, unsigned Offset) {
1904 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(this)) {
1905 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
1906 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1907 if (Init->isString()) {
1908 std::string Result = Init->getAsString();
1909 if (Offset < Result.size()) {
1910 // If we are pointing INTO The string, erase the beginning...
1911 Result.erase(Result.begin(), Result.begin()+Offset);
1913 // Take off the null terminator, and any string fragments after it.
1915 std::string::size_type NullPos = Result.find_first_of((char)0);
1916 if (NullPos != std::string::npos)
1917 Result.erase(Result.begin()+NullPos, Result.end());
1923 } else if (Constant *C = dyn_cast<Constant>(this)) {
1924 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1925 return GV->getStringValue(Chop, Offset);
1926 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1927 if (CE->getOpcode() == Instruction::GetElementPtr) {
1928 // Turn a gep into the specified offset.
1929 if (CE->getNumOperands() == 3 &&
1930 cast<Constant>(CE->getOperand(1))->isNullValue() &&
1931 isa<ConstantInt>(CE->getOperand(2))) {
1932 Offset += cast<ConstantInt>(CE->getOperand(2))->getZExtValue();
1933 return CE->getOperand(0)->getStringValue(Chop, Offset);