1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // This file implements the Constant* classes...
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Constants.h"
8 #include "llvm/ConstantHandling.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/SymbolTable.h"
12 #include "llvm/Module.h"
13 #include "Support/StringExtras.h"
16 ConstantBool *ConstantBool::True = new ConstantBool(true);
17 ConstantBool *ConstantBool::False = new ConstantBool(false);
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // Specialize setName to take care of symbol table majik
25 void Constant::setName(const std::string &Name, SymbolTable *ST) {
26 assert(ST && "Type::setName - Must provide symbol table argument!");
28 if (Name.size()) ST->insert(Name, this);
31 void Constant::destroyConstantImpl() {
32 // When a Constant is destroyed, there may be lingering
33 // references to the constant by other constants in the constant pool. These
34 // constants are implicitly dependent on the module that is being deleted,
35 // but they don't know that. Because we only find out when the CPV is
36 // deleted, we must now notify all of our users (that should only be
37 // Constants) that they are, in fact, invalid now and should be deleted.
39 while (!use_empty()) {
40 Value *V = use_back();
41 #ifndef NDEBUG // Only in -g mode...
42 if (!isa<Constant>(V))
43 std::cerr << "While deleting: " << *this
44 << "\n\nUse still stuck around after Def is destroyed: "
47 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
48 Constant *CPV = cast<Constant>(V);
49 CPV->destroyConstant();
51 // The constant should remove itself from our use list...
52 assert((use_empty() || use_back() != V) && "Constant not removed!");
55 // Value has no outstanding references it is safe to delete it now...
59 // Static constructor to create a '0' constant of arbitrary type...
60 Constant *Constant::getNullValue(const Type *Ty) {
61 switch (Ty->getPrimitiveID()) {
62 case Type::BoolTyID: return ConstantBool::get(false);
66 case Type::LongTyID: return ConstantSInt::get(Ty, 0);
69 case Type::UShortTyID:
71 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
74 case Type::DoubleTyID: return ConstantFP::get(Ty, 0);
76 case Type::PointerTyID:
77 return ConstantPointerNull::get(cast<PointerType>(Ty));
78 case Type::StructTyID: {
79 const StructType *ST = cast<StructType>(Ty);
81 const StructType::ElementTypes &ETs = ST->getElementTypes();
82 std::vector<Constant*> Elements;
83 Elements.resize(ETs.size());
84 for (unsigned i = 0, e = ETs.size(); i != e; ++i)
85 Elements[i] = Constant::getNullValue(ETs[i]);
86 return ConstantStruct::get(ST, Elements);
88 case Type::ArrayTyID: {
89 const ArrayType *AT = cast<ArrayType>(Ty);
90 Constant *El = Constant::getNullValue(AT->getElementType());
91 unsigned NumElements = AT->getNumElements();
92 return ConstantArray::get(AT, std::vector<Constant*>(NumElements, El));
95 // Function, Type, Label, or Opaque type?
96 assert(0 && "Cannot create a null constant of that type!");
101 // Static constructor to create the maximum constant of an integral type...
102 ConstantIntegral *ConstantIntegral::getMaxValue(const Type *Ty) {
103 switch (Ty->getPrimitiveID()) {
104 case Type::BoolTyID: return ConstantBool::True;
105 case Type::SByteTyID:
106 case Type::ShortTyID:
108 case Type::LongTyID: {
109 // Calculate 011111111111111...
110 unsigned TypeBits = Ty->getPrimitiveSize()*8;
111 int64_t Val = INT64_MAX; // All ones
112 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
113 return ConstantSInt::get(Ty, Val);
116 case Type::UByteTyID:
117 case Type::UShortTyID:
119 case Type::ULongTyID: return getAllOnesValue(Ty);
125 // Static constructor to create the minimum constant for an integral type...
126 ConstantIntegral *ConstantIntegral::getMinValue(const Type *Ty) {
127 switch (Ty->getPrimitiveID()) {
128 case Type::BoolTyID: return ConstantBool::False;
129 case Type::SByteTyID:
130 case Type::ShortTyID:
132 case Type::LongTyID: {
133 // Calculate 1111111111000000000000
134 unsigned TypeBits = Ty->getPrimitiveSize()*8;
135 int64_t Val = -1; // All ones
136 Val <<= TypeBits-1; // Shift over to the right spot
137 return ConstantSInt::get(Ty, Val);
140 case Type::UByteTyID:
141 case Type::UShortTyID:
143 case Type::ULongTyID: return ConstantUInt::get(Ty, 0);
149 // Static constructor to create an integral constant with all bits set
150 ConstantIntegral *ConstantIntegral::getAllOnesValue(const Type *Ty) {
151 switch (Ty->getPrimitiveID()) {
152 case Type::BoolTyID: return ConstantBool::True;
153 case Type::SByteTyID:
154 case Type::ShortTyID:
156 case Type::LongTyID: return ConstantSInt::get(Ty, -1);
158 case Type::UByteTyID:
159 case Type::UShortTyID:
161 case Type::ULongTyID: {
162 // Calculate ~0 of the right type...
163 unsigned TypeBits = Ty->getPrimitiveSize()*8;
164 uint64_t Val = ~0ULL; // All ones
165 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
166 return ConstantUInt::get(Ty, Val);
172 bool ConstantUInt::isAllOnesValue() const {
173 unsigned TypeBits = getType()->getPrimitiveSize()*8;
174 uint64_t Val = ~0ULL; // All ones
175 Val >>= 64-TypeBits; // Shift out inappropriate bits
176 return getValue() == Val;
180 //===----------------------------------------------------------------------===//
181 // ConstantXXX Classes
182 //===----------------------------------------------------------------------===//
184 //===----------------------------------------------------------------------===//
185 // Normal Constructors
187 ConstantBool::ConstantBool(bool V) : ConstantIntegral(Type::BoolTy) {
191 ConstantInt::ConstantInt(const Type *Ty, uint64_t V) : ConstantIntegral(Ty) {
195 ConstantSInt::ConstantSInt(const Type *Ty, int64_t V) : ConstantInt(Ty, V) {
196 assert(Ty->isInteger() && Ty->isSigned() &&
197 "Illegal type for unsigned integer constant!");
198 assert(isValueValidForType(Ty, V) && "Value too large for type!");
201 ConstantUInt::ConstantUInt(const Type *Ty, uint64_t V) : ConstantInt(Ty, V) {
202 assert(Ty->isInteger() && Ty->isUnsigned() &&
203 "Illegal type for unsigned integer constant!");
204 assert(isValueValidForType(Ty, V) && "Value too large for type!");
207 ConstantFP::ConstantFP(const Type *Ty, double V) : Constant(Ty) {
208 assert(isValueValidForType(Ty, V) && "Value too large for type!");
212 ConstantArray::ConstantArray(const ArrayType *T,
213 const std::vector<Constant*> &V) : Constant(T) {
214 Operands.reserve(V.size());
215 for (unsigned i = 0, e = V.size(); i != e; ++i) {
216 assert(V[i]->getType() == T->getElementType() ||
218 V[i]->getType()->getPrimitiveID() ==
219 T->getElementType()->getPrimitiveID()));
220 Operands.push_back(Use(V[i], this));
224 ConstantStruct::ConstantStruct(const StructType *T,
225 const std::vector<Constant*> &V) : Constant(T) {
226 const StructType::ElementTypes &ETypes = T->getElementTypes();
227 assert(V.size() == ETypes.size() &&
228 "Invalid initializer vector for constant structure");
229 Operands.reserve(V.size());
230 for (unsigned i = 0, e = V.size(); i != e; ++i) {
231 assert((V[i]->getType() == ETypes[i] ||
232 (ETypes[i]->isAbstract() &&
233 ETypes[i]->getPrimitiveID()==V[i]->getType()->getPrimitiveID())) &&
234 "Initializer for struct element doesn't match struct element type!");
235 Operands.push_back(Use(V[i], this));
239 ConstantPointerRef::ConstantPointerRef(GlobalValue *GV)
240 : ConstantPointer(GV->getType()) {
241 Operands.push_back(Use(GV, this));
244 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
245 : Constant(Ty), iType(Opcode) {
246 Operands.push_back(Use(C, this));
249 static bool isSetCC(unsigned Opcode) {
250 return Opcode == Instruction::SetEQ || Opcode == Instruction::SetNE ||
251 Opcode == Instruction::SetLT || Opcode == Instruction::SetGT ||
252 Opcode == Instruction::SetLE || Opcode == Instruction::SetGE;
255 ConstantExpr::ConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
256 : Constant(isSetCC(Opcode) ? Type::BoolTy : C1->getType()), iType(Opcode) {
257 Operands.push_back(Use(C1, this));
258 Operands.push_back(Use(C2, this));
261 ConstantExpr::ConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
263 : Constant(DestTy), iType(Instruction::GetElementPtr) {
264 Operands.reserve(1+IdxList.size());
265 Operands.push_back(Use(C, this));
266 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
267 Operands.push_back(Use(IdxList[i], this));
272 //===----------------------------------------------------------------------===//
273 // classof implementations
275 bool ConstantIntegral::classof(const Constant *CPV) {
276 return CPV->getType()->isIntegral() && !isa<ConstantExpr>(CPV);
279 bool ConstantInt::classof(const Constant *CPV) {
280 return CPV->getType()->isInteger() && !isa<ConstantExpr>(CPV);
282 bool ConstantSInt::classof(const Constant *CPV) {
283 return CPV->getType()->isSigned() && !isa<ConstantExpr>(CPV);
285 bool ConstantUInt::classof(const Constant *CPV) {
286 return CPV->getType()->isUnsigned() && !isa<ConstantExpr>(CPV);
288 bool ConstantFP::classof(const Constant *CPV) {
289 const Type *Ty = CPV->getType();
290 return ((Ty == Type::FloatTy || Ty == Type::DoubleTy) &&
291 !isa<ConstantExpr>(CPV));
293 bool ConstantArray::classof(const Constant *CPV) {
294 return isa<ArrayType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
296 bool ConstantStruct::classof(const Constant *CPV) {
297 return isa<StructType>(CPV->getType()) && !isa<ConstantExpr>(CPV);
299 bool ConstantPointer::classof(const Constant *CPV) {
300 return (isa<PointerType>(CPV->getType()) && !isa<ConstantExpr>(CPV));
305 //===----------------------------------------------------------------------===//
306 // isValueValidForType implementations
308 bool ConstantSInt::isValueValidForType(const Type *Ty, int64_t Val) {
309 switch (Ty->getPrimitiveID()) {
311 return false; // These can't be represented as integers!!!
314 case Type::SByteTyID:
315 return (Val <= INT8_MAX && Val >= INT8_MIN);
316 case Type::ShortTyID:
317 return (Val <= INT16_MAX && Val >= INT16_MIN);
319 return (Val <= INT32_MAX && Val >= INT32_MIN);
321 return true; // This is the largest type...
327 bool ConstantUInt::isValueValidForType(const Type *Ty, uint64_t Val) {
328 switch (Ty->getPrimitiveID()) {
330 return false; // These can't be represented as integers!!!
333 case Type::UByteTyID:
334 return (Val <= UINT8_MAX);
335 case Type::UShortTyID:
336 return (Val <= UINT16_MAX);
338 return (Val <= UINT32_MAX);
339 case Type::ULongTyID:
340 return true; // This is the largest type...
346 bool ConstantFP::isValueValidForType(const Type *Ty, double Val) {
347 switch (Ty->getPrimitiveID()) {
349 return false; // These can't be represented as floating point!
351 // TODO: Figure out how to test if a double can be cast to a float!
352 case Type::FloatTyID:
353 case Type::DoubleTyID:
354 return true; // This is the largest type...
358 //===----------------------------------------------------------------------===//
359 // replaceUsesOfWithOnConstant implementations
361 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
362 bool DisableChecking) {
363 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
365 std::vector<Constant*> Values;
366 Values.reserve(getValues().size()); // Build replacement array...
367 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
368 Constant *Val = cast<Constant>(getValues()[i]);
369 if (Val == From) Val = cast<Constant>(To);
370 Values.push_back(Val);
373 ConstantArray *Replacement = ConstantArray::get(getType(), Values);
374 assert(Replacement != this && "I didn't contain From!");
376 // Everyone using this now uses the replacement...
378 uncheckedReplaceAllUsesWith(Replacement);
380 replaceAllUsesWith(Replacement);
382 // Delete the old constant!
386 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
387 bool DisableChecking) {
388 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
390 std::vector<Constant*> Values;
391 Values.reserve(getValues().size());
392 for (unsigned i = 0, e = getValues().size(); i != e; ++i) {
393 Constant *Val = cast<Constant>(getValues()[i]);
394 if (Val == From) Val = cast<Constant>(To);
395 Values.push_back(Val);
398 ConstantStruct *Replacement = ConstantStruct::get(getType(), Values);
399 assert(Replacement != this && "I didn't contain From!");
401 // Everyone using this now uses the replacement...
403 uncheckedReplaceAllUsesWith(Replacement);
405 replaceAllUsesWith(Replacement);
407 // Delete the old constant!
411 void ConstantPointerRef::replaceUsesOfWithOnConstant(Value *From, Value *To,
412 bool DisableChecking) {
413 if (isa<GlobalValue>(To)) {
414 assert(From == getOperand(0) && "Doesn't contain from!");
415 ConstantPointerRef *Replacement =
416 ConstantPointerRef::get(cast<GlobalValue>(To));
418 // Everyone using this now uses the replacement...
420 uncheckedReplaceAllUsesWith(Replacement);
422 replaceAllUsesWith(Replacement);
425 // Just replace ourselves with the To value specified.
427 uncheckedReplaceAllUsesWith(To);
429 replaceAllUsesWith(To);
432 // Delete the old constant!
436 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
437 bool DisableChecking) {
438 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
439 Constant *To = cast<Constant>(ToV);
441 Constant *Replacement = 0;
442 if (getOpcode() == Instruction::GetElementPtr) {
443 std::vector<Constant*> Indices;
444 Constant *Pointer = getOperand(0);
445 Indices.reserve(getNumOperands()-1);
446 if (Pointer == From) Pointer = To;
448 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
449 Constant *Val = getOperand(i);
450 if (Val == From) Val = To;
451 Indices.push_back(Val);
453 Replacement = ConstantExpr::getGetElementPtr(Pointer, Indices);
454 } else if (getOpcode() == Instruction::Cast) {
455 assert(getOperand(0) == From && "Cast only has one use!");
456 Replacement = ConstantExpr::getCast(To, getType());
457 } else if (getNumOperands() == 2) {
458 Constant *C1 = getOperand(0);
459 Constant *C2 = getOperand(1);
460 if (C1 == From) C1 = To;
461 if (C2 == From) C2 = To;
462 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
464 assert(0 && "Unknown ConstantExpr type!");
468 assert(Replacement != this && "I didn't contain From!");
470 // Everyone using this now uses the replacement...
472 uncheckedReplaceAllUsesWith(Replacement);
474 replaceAllUsesWith(Replacement);
476 // Delete the old constant!
480 //===----------------------------------------------------------------------===//
481 // Factory Function Implementation
483 // ConstantCreator - A class that is used to create constants by
484 // ValueMap*. This class should be partially specialized if there is
485 // something strange that needs to be done to interface to the ctor for the
488 template<class ConstantClass, class TypeClass, class ValType>
489 struct ConstantCreator {
490 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
491 return new ConstantClass(Ty, V);
496 template<class ValType, class TypeClass, class ConstantClass>
499 typedef std::pair<const TypeClass*, ValType> ConstHashKey;
500 std::map<ConstHashKey, ConstantClass *> Map;
502 // getOrCreate - Return the specified constant from the map, creating it if
504 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
505 ConstHashKey Lookup(Ty, V);
506 typename std::map<ConstHashKey,ConstantClass *>::iterator I =
507 Map.lower_bound(Lookup);
508 if (I != Map.end() && I->first == Lookup)
509 return I->second; // Is it in the map?
511 // If no preexisting value, create one now...
512 ConstantClass *Result =
513 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
515 Map.insert(I, std::make_pair(ConstHashKey(Ty, V), Result));
519 void remove(ConstantClass *CP) {
520 // FIXME: This could be sped up a LOT. If this gets to be a performance
521 // problem, someone should look at this.
522 for (typename std::map<ConstHashKey, ConstantClass*>::iterator
523 I = Map.begin(), E = Map.end(); I != E; ++I)
524 if (I->second == CP) {
528 assert(0 && "Constant not found in constant table!");
535 //---- ConstantUInt::get() and ConstantSInt::get() implementations...
537 static ValueMap< int64_t, Type, ConstantSInt> SIntConstants;
538 static ValueMap<uint64_t, Type, ConstantUInt> UIntConstants;
540 ConstantSInt *ConstantSInt::get(const Type *Ty, int64_t V) {
541 return SIntConstants.getOrCreate(Ty, V);
544 ConstantUInt *ConstantUInt::get(const Type *Ty, uint64_t V) {
545 return UIntConstants.getOrCreate(Ty, V);
548 ConstantInt *ConstantInt::get(const Type *Ty, unsigned char V) {
549 assert(V <= 127 && "Can only be used with very small positive constants!");
550 if (Ty->isSigned()) return ConstantSInt::get(Ty, V);
551 return ConstantUInt::get(Ty, V);
554 //---- ConstantFP::get() implementation...
556 static ValueMap<double, Type, ConstantFP> FPConstants;
558 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
559 return FPConstants.getOrCreate(Ty, V);
562 //---- ConstantArray::get() implementation...
564 static ValueMap<std::vector<Constant*>, ArrayType,
565 ConstantArray> ArrayConstants;
567 ConstantArray *ConstantArray::get(const ArrayType *Ty,
568 const std::vector<Constant*> &V) {
569 return ArrayConstants.getOrCreate(Ty, V);
572 // destroyConstant - Remove the constant from the constant table...
574 void ConstantArray::destroyConstant() {
575 ArrayConstants.remove(this);
576 destroyConstantImpl();
580 /// refineAbstractType - If this callback is invoked, then this constant is of a
581 /// derived type, change all users to use a concrete constant of the new type.
583 void ConstantArray::refineAbstractType(const DerivedType *OldTy,
585 if (OldTy == NewTy) return;
587 // Make everyone now use a constant of the new type...
588 std::vector<Constant*> C;
589 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
590 C.push_back(cast<Constant>(getOperand(i)));
591 Constant *New = ConstantArray::get(cast<ArrayType>(NewTy), C);
593 uncheckedReplaceAllUsesWith(New);
594 destroyConstant(); // This constant is now dead, destroy it.
599 // ConstantArray::get(const string&) - Return an array that is initialized to
600 // contain the specified string. A null terminator is added to the specified
601 // string so that it may be used in a natural way...
603 ConstantArray *ConstantArray::get(const std::string &Str) {
604 std::vector<Constant*> ElementVals;
606 for (unsigned i = 0; i < Str.length(); ++i)
607 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, Str[i]));
609 // Add a null terminator to the string...
610 ElementVals.push_back(ConstantSInt::get(Type::SByteTy, 0));
612 ArrayType *ATy = ArrayType::get(Type::SByteTy, Str.length()+1);
613 return ConstantArray::get(ATy, ElementVals);
616 // getAsString - If the sub-element type of this array is either sbyte or ubyte,
617 // then this method converts the array to an std::string and returns it.
618 // Otherwise, it asserts out.
620 std::string ConstantArray::getAsString() const {
621 assert((getType()->getElementType() == Type::UByteTy ||
622 getType()->getElementType() == Type::SByteTy) && "Not a string!");
625 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
626 Result += (char)cast<ConstantInt>(getOperand(i))->getRawValue();
631 //---- ConstantStruct::get() implementation...
633 static ValueMap<std::vector<Constant*>, StructType,
634 ConstantStruct> StructConstants;
636 ConstantStruct *ConstantStruct::get(const StructType *Ty,
637 const std::vector<Constant*> &V) {
638 return StructConstants.getOrCreate(Ty, V);
641 // destroyConstant - Remove the constant from the constant table...
643 void ConstantStruct::destroyConstant() {
644 StructConstants.remove(this);
645 destroyConstantImpl();
649 /// refineAbstractType - If this callback is invoked, then this constant is of a
650 /// derived type, change all users to use a concrete constant of the new type.
652 void ConstantStruct::refineAbstractType(const DerivedType *OldTy,
654 if (OldTy == NewTy) return;
656 // Make everyone now use a constant of the new type...
657 std::vector<Constant*> C;
658 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
659 C.push_back(cast<Constant>(getOperand(i)));
660 Constant *New = ConstantStruct::get(cast<StructType>(NewTy), C);
662 uncheckedReplaceAllUsesWith(New);
663 destroyConstant(); // This constant is now dead, destroy it.
668 //---- ConstantPointerNull::get() implementation...
671 // ConstantPointerNull does not take extra "value" argument...
672 template<class ValType>
673 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
674 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
675 return new ConstantPointerNull(Ty);
679 static ValueMap<char, PointerType, ConstantPointerNull> NullPtrConstants;
681 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
682 return NullPtrConstants.getOrCreate(Ty, 0);
685 // destroyConstant - Remove the constant from the constant table...
687 void ConstantPointerNull::destroyConstant() {
688 NullPtrConstants.remove(this);
689 destroyConstantImpl();
693 /// refineAbstractType - If this callback is invoked, then this constant is of a
694 /// derived type, change all users to use a concrete constant of the new type.
696 void ConstantPointerNull::refineAbstractType(const DerivedType *OldTy,
698 if (OldTy == NewTy) return;
700 // Make everyone now use a constant of the new type...
701 Constant *New = ConstantPointerNull::get(cast<PointerType>(NewTy));
703 uncheckedReplaceAllUsesWith(New);
705 // This constant is now dead, destroy it.
713 //---- ConstantPointerRef::get() implementation...
715 ConstantPointerRef *ConstantPointerRef::get(GlobalValue *GV) {
716 assert(GV->getParent() && "Global Value must be attached to a module!");
718 // The Module handles the pointer reference sharing...
719 return GV->getParent()->getConstantPointerRef(GV);
722 // destroyConstant - Remove the constant from the constant table...
724 void ConstantPointerRef::destroyConstant() {
725 getValue()->getParent()->destroyConstantPointerRef(this);
726 destroyConstantImpl();
730 //---- ConstantExpr::get() implementations...
732 typedef std::pair<unsigned, std::vector<Constant*> > ExprMapKeyType;
735 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
736 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V) {
737 if (V.first == Instruction::Cast)
738 return new ConstantExpr(Instruction::Cast, V.second[0], Ty);
739 if ((V.first >= Instruction::BinaryOpsBegin &&
740 V.first < Instruction::BinaryOpsEnd) ||
741 V.first == Instruction::Shl || V.first == Instruction::Shr)
742 return new ConstantExpr(V.first, V.second[0], V.second[1]);
744 assert(V.first == Instruction::GetElementPtr && "Invalid ConstantExpr!");
746 // Check that the indices list is valid...
747 std::vector<Value*> ValIdxList(V.second.begin()+1, V.second.end());
748 const Type *DestTy = GetElementPtrInst::getIndexedType(Ty, ValIdxList,
750 assert(DestTy && "Invalid index list for GetElementPtr expression");
752 std::vector<Constant*> IdxList(V.second.begin()+1, V.second.end());
753 return new ConstantExpr(V.second[0], IdxList, PointerType::get(DestTy));
757 static ValueMap<ExprMapKeyType, Type, ConstantExpr> ExprConstants;
759 Constant *ConstantExpr::getCast(Constant *C, const Type *Ty) {
760 if (Constant *FC = ConstantFoldCastInstruction(C, Ty))
761 return FC; // Fold a few common cases...
763 // Look up the constant in the table first to ensure uniqueness
764 std::vector<Constant*> argVec(1, C);
765 ExprMapKeyType Key = std::make_pair(Instruction::Cast, argVec);
766 return ExprConstants.getOrCreate(Ty, Key);
769 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
770 // Check the operands for consistency first
771 assert((Opcode >= Instruction::BinaryOpsBegin &&
772 Opcode < Instruction::BinaryOpsEnd) &&
773 "Invalid opcode in binary constant expression");
774 assert(C1->getType() == C2->getType() &&
775 "Operand types in binary constant expression should match");
777 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
778 return FC; // Fold a few common cases...
780 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
781 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
782 return ExprConstants.getOrCreate(C1->getType(), Key);
785 /// getShift - Return a shift left or shift right constant expr
786 Constant *ConstantExpr::getShift(unsigned Opcode, Constant *C1, Constant *C2) {
787 // Check the operands for consistency first
788 assert((Opcode == Instruction::Shl ||
789 Opcode == Instruction::Shr) &&
790 "Invalid opcode in binary constant expression");
791 assert(C1->getType()->isIntegral() && C2->getType() == Type::UByteTy &&
792 "Invalid operand types for Shift constant expr!");
794 if (Constant *FC = ConstantFoldShiftInstruction(Opcode, C1, C2))
795 return FC; // Fold a few common cases...
797 // Look up the constant in the table first to ensure uniqueness
798 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
799 ExprMapKeyType Key = std::make_pair(Opcode, argVec);
800 return ExprConstants.getOrCreate(C1->getType(), Key);
804 Constant *ConstantExpr::getGetElementPtr(Constant *C,
805 const std::vector<Constant*> &IdxList){
806 if (Constant *FC = ConstantFoldGetElementPtr(C, IdxList))
807 return FC; // Fold a few common cases...
808 const Type *Ty = C->getType();
809 assert(isa<PointerType>(Ty) &&
810 "Non-pointer type for constant GetElementPtr expression");
812 // Look up the constant in the table first to ensure uniqueness
813 std::vector<Constant*> argVec(1, C);
814 argVec.insert(argVec.end(), IdxList.begin(), IdxList.end());
816 const ExprMapKeyType &Key = std::make_pair(Instruction::GetElementPtr,argVec);
817 return ExprConstants.getOrCreate(Ty, Key);
820 // destroyConstant - Remove the constant from the constant table...
822 void ConstantExpr::destroyConstant() {
823 ExprConstants.remove(this);
824 destroyConstantImpl();
828 /// refineAbstractType - If this callback is invoked, then this constant is of a
829 /// derived type, change all users to use a concrete constant of the new type.
831 void ConstantExpr::refineAbstractType(const DerivedType *OldTy,
833 if (OldTy == NewTy) return;
835 // FIXME: These need to use a lower-level implementation method, because the
836 // ::get methods intuit the type of the result based on the types of the
837 // operands. The operand types may not have had their types resolved yet.
840 if (getOpcode() == Instruction::Cast) {
841 New = getCast(getOperand(0), NewTy);
842 } else if (getOpcode() >= Instruction::BinaryOpsBegin &&
843 getOpcode() < Instruction::BinaryOpsEnd) {
844 New = get(getOpcode(), getOperand(0), getOperand(0));
845 } else if (getOpcode() == Instruction::Shl || getOpcode() ==Instruction::Shr){
846 New = getShift(getOpcode(), getOperand(0), getOperand(0));
848 assert(getOpcode() == Instruction::GetElementPtr);
850 // Make everyone now use a constant of the new type...
851 std::vector<Constant*> C;
852 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
853 C.push_back(cast<Constant>(getOperand(i)));
854 New = ConstantExpr::getGetElementPtr(getOperand(0), C);
857 uncheckedReplaceAllUsesWith(New);
858 destroyConstant(); // This constant is now dead, destroy it.
866 const char *ConstantExpr::getOpcodeName() const {
867 return Instruction::getOpcodeName(getOpcode());
870 unsigned Constant::mutateReferences(Value *OldV, Value *NewV) {
871 // Uses of constant pointer refs are global values, not constants!
872 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(this)) {
873 GlobalValue *NewGV = cast<GlobalValue>(NewV);
874 GlobalValue *OldGV = CPR->getValue();
876 assert(OldGV == OldV && "Cannot mutate old value if I'm not using it!");
878 OldGV->getParent()->mutateConstantPointerRef(OldGV, NewGV);
881 Constant *NewC = cast<Constant>(NewV);
882 unsigned NumReplaced = 0;
883 for (unsigned i = 0, N = getNumOperands(); i != N; ++i)
884 if (Operands[i] == OldV) {