1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/System/Mutex.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // Becomes a no-op when multithreading is disabled.
43 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
45 void Constant::destroyConstantImpl() {
46 // When a Constant is destroyed, there may be lingering
47 // references to the constant by other constants in the constant pool. These
48 // constants are implicitly dependent on the module that is being deleted,
49 // but they don't know that. Because we only find out when the CPV is
50 // deleted, we must now notify all of our users (that should only be
51 // Constants) that they are, in fact, invalid now and should be deleted.
53 while (!use_empty()) {
54 Value *V = use_back();
55 #ifndef NDEBUG // Only in -g mode...
56 if (!isa<Constant>(V))
57 DOUT << "While deleting: " << *this
58 << "\n\nUse still stuck around after Def is destroyed: "
61 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
62 Constant *CV = cast<Constant>(V);
63 CV->destroyConstant();
65 // The constant should remove itself from our use list...
66 assert((use_empty() || use_back() != V) && "Constant not removed!");
69 // Value has no outstanding references it is safe to delete it now...
73 /// canTrap - Return true if evaluation of this constant could trap. This is
74 /// true for things like constant expressions that could divide by zero.
75 bool Constant::canTrap() const {
76 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
77 // The only thing that could possibly trap are constant exprs.
78 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
79 if (!CE) return false;
81 // ConstantExpr traps if any operands can trap.
82 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
83 if (getOperand(i)->canTrap())
86 // Otherwise, only specific operations can trap.
87 switch (CE->getOpcode()) {
90 case Instruction::UDiv:
91 case Instruction::SDiv:
92 case Instruction::FDiv:
93 case Instruction::URem:
94 case Instruction::SRem:
95 case Instruction::FRem:
96 // Div and rem can trap if the RHS is not known to be non-zero.
97 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
103 /// ContainsRelocations - Return true if the constant value contains relocations
104 /// which cannot be resolved at compile time. Kind argument is used to filter
105 /// only 'interesting' sorts of relocations.
106 bool Constant::ContainsRelocations(unsigned Kind) const {
107 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
108 bool isLocal = GV->hasLocalLinkage();
109 if ((Kind & Reloc::Local) && isLocal) {
110 // Global has local linkage and 'local' kind of relocations are
115 if ((Kind & Reloc::Global) && !isLocal) {
116 // Global has non-local linkage and 'global' kind of relocations are
124 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
125 if (getOperand(i)->ContainsRelocations(Kind))
131 /// getVectorElements - This method, which is only valid on constant of vector
132 /// type, returns the elements of the vector in the specified smallvector.
133 /// This handles breaking down a vector undef into undef elements, etc. For
134 /// constant exprs and other cases we can't handle, we return an empty vector.
135 void Constant::getVectorElements(LLVMContext &Context,
136 SmallVectorImpl<Constant*> &Elts) const {
137 assert(isa<VectorType>(getType()) && "Not a vector constant!");
139 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
140 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
141 Elts.push_back(CV->getOperand(i));
145 const VectorType *VT = cast<VectorType>(getType());
146 if (isa<ConstantAggregateZero>(this)) {
147 Elts.assign(VT->getNumElements(),
148 Context.getNullValue(VT->getElementType()));
152 if (isa<UndefValue>(this)) {
153 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
157 // Unknown type, must be constant expr etc.
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
166 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
167 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
168 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
171 ConstantInt *ConstantInt::TheTrueVal = 0;
172 ConstantInt *ConstantInt::TheFalseVal = 0;
175 void CleanupTrueFalse(void *) {
176 ConstantInt::ResetTrueFalse();
180 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
182 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
183 assert(TheTrueVal == 0 && TheFalseVal == 0);
184 TheTrueVal = getGlobalContext().getConstantInt(Type::Int1Ty, 1);
185 TheFalseVal = getGlobalContext().getConstantInt(Type::Int1Ty, 0);
187 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
188 TrueFalseCleanup.Register();
190 return WhichOne ? TheTrueVal : TheFalseVal;
195 struct DenseMapAPIntKeyInfo {
199 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
200 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
201 bool operator==(const KeyTy& that) const {
202 return type == that.type && this->val == that.val;
204 bool operator!=(const KeyTy& that) const {
205 return !this->operator==(that);
208 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
209 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
210 static unsigned getHashValue(const KeyTy &Key) {
211 return DenseMapInfo<void*>::getHashValue(Key.type) ^
212 Key.val.getHashValue();
214 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
217 static bool isPod() { return false; }
222 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
223 DenseMapAPIntKeyInfo> IntMapTy;
224 static ManagedStatic<IntMapTy> IntConstants;
226 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
227 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
228 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
229 // compare APInt's of different widths, which would violate an APInt class
230 // invariant which generates an assertion.
231 ConstantInt *ConstantInt::get(const APInt& V) {
232 // Get the corresponding integer type for the bit width of the value.
233 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
234 // get an existing value or the insertion position
235 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
237 ConstantsLock->reader_acquire();
238 ConstantInt *&Slot = (*IntConstants)[Key];
239 ConstantsLock->reader_release();
242 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
243 ConstantInt *&NewSlot = (*IntConstants)[Key];
245 NewSlot = new ConstantInt(ITy, V);
254 //===----------------------------------------------------------------------===//
256 //===----------------------------------------------------------------------===//
258 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
259 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
260 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
264 bool ConstantFP::isNullValue() const {
265 return Val.isZero() && !Val.isNegative();
268 bool ConstantFP::isExactlyValue(const APFloat& V) const {
269 return Val.bitwiseIsEqual(V);
273 struct DenseMapAPFloatKeyInfo {
276 KeyTy(const APFloat& V) : val(V){}
277 KeyTy(const KeyTy& that) : val(that.val) {}
278 bool operator==(const KeyTy& that) const {
279 return this->val.bitwiseIsEqual(that.val);
281 bool operator!=(const KeyTy& that) const {
282 return !this->operator==(that);
285 static inline KeyTy getEmptyKey() {
286 return KeyTy(APFloat(APFloat::Bogus,1));
288 static inline KeyTy getTombstoneKey() {
289 return KeyTy(APFloat(APFloat::Bogus,2));
291 static unsigned getHashValue(const KeyTy &Key) {
292 return Key.val.getHashValue();
294 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
297 static bool isPod() { return false; }
301 //---- ConstantFP::get() implementation...
303 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
304 DenseMapAPFloatKeyInfo> FPMapTy;
306 static ManagedStatic<FPMapTy> FPConstants;
308 ConstantFP *ConstantFP::get(const APFloat &V) {
309 DenseMapAPFloatKeyInfo::KeyTy Key(V);
311 ConstantsLock->reader_acquire();
312 ConstantFP *&Slot = (*FPConstants)[Key];
313 ConstantsLock->reader_release();
316 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
317 ConstantFP *&NewSlot = (*FPConstants)[Key];
320 if (&V.getSemantics() == &APFloat::IEEEsingle)
322 else if (&V.getSemantics() == &APFloat::IEEEdouble)
324 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
325 Ty = Type::X86_FP80Ty;
326 else if (&V.getSemantics() == &APFloat::IEEEquad)
329 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
330 "Unknown FP format");
331 Ty = Type::PPC_FP128Ty;
333 NewSlot = new ConstantFP(Ty, V);
342 //===----------------------------------------------------------------------===//
343 // ConstantXXX Classes
344 //===----------------------------------------------------------------------===//
347 ConstantArray::ConstantArray(const ArrayType *T,
348 const std::vector<Constant*> &V)
349 : Constant(T, ConstantArrayVal,
350 OperandTraits<ConstantArray>::op_end(this) - V.size(),
352 assert(V.size() == T->getNumElements() &&
353 "Invalid initializer vector for constant array");
354 Use *OL = OperandList;
355 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
358 assert((C->getType() == T->getElementType() ||
360 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
361 "Initializer for array element doesn't match array element type!");
367 ConstantStruct::ConstantStruct(const StructType *T,
368 const std::vector<Constant*> &V)
369 : Constant(T, ConstantStructVal,
370 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
372 assert(V.size() == T->getNumElements() &&
373 "Invalid initializer vector for constant structure");
374 Use *OL = OperandList;
375 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
378 assert((C->getType() == T->getElementType(I-V.begin()) ||
379 ((T->getElementType(I-V.begin())->isAbstract() ||
380 C->getType()->isAbstract()) &&
381 T->getElementType(I-V.begin())->getTypeID() ==
382 C->getType()->getTypeID())) &&
383 "Initializer for struct element doesn't match struct element type!");
389 ConstantVector::ConstantVector(const VectorType *T,
390 const std::vector<Constant*> &V)
391 : Constant(T, ConstantVectorVal,
392 OperandTraits<ConstantVector>::op_end(this) - V.size(),
394 Use *OL = OperandList;
395 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
398 assert((C->getType() == T->getElementType() ||
400 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
401 "Initializer for vector element doesn't match vector element type!");
408 // We declare several classes private to this file, so use an anonymous
412 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
413 /// behind the scenes to implement unary constant exprs.
414 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
415 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
417 // allocate space for exactly one operand
418 void *operator new(size_t s) {
419 return User::operator new(s, 1);
421 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
422 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
425 /// Transparently provide more efficient getOperand methods.
426 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
429 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
430 /// behind the scenes to implement binary constant exprs.
431 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
432 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
434 // allocate space for exactly two operands
435 void *operator new(size_t s) {
436 return User::operator new(s, 2);
438 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
439 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
443 /// Transparently provide more efficient getOperand methods.
444 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
447 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
448 /// behind the scenes to implement select constant exprs.
449 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
450 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
452 // allocate space for exactly three operands
453 void *operator new(size_t s) {
454 return User::operator new(s, 3);
456 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
457 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
462 /// Transparently provide more efficient getOperand methods.
463 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
466 /// ExtractElementConstantExpr - This class is private to
467 /// Constants.cpp, and is used behind the scenes to implement
468 /// extractelement constant exprs.
469 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
470 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
472 // allocate space for exactly two operands
473 void *operator new(size_t s) {
474 return User::operator new(s, 2);
476 ExtractElementConstantExpr(Constant *C1, Constant *C2)
477 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
478 Instruction::ExtractElement, &Op<0>(), 2) {
482 /// Transparently provide more efficient getOperand methods.
483 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
486 /// InsertElementConstantExpr - This class is private to
487 /// Constants.cpp, and is used behind the scenes to implement
488 /// insertelement constant exprs.
489 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
490 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
492 // allocate space for exactly three operands
493 void *operator new(size_t s) {
494 return User::operator new(s, 3);
496 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
497 : ConstantExpr(C1->getType(), Instruction::InsertElement,
503 /// Transparently provide more efficient getOperand methods.
504 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
507 /// ShuffleVectorConstantExpr - This class is private to
508 /// Constants.cpp, and is used behind the scenes to implement
509 /// shufflevector constant exprs.
510 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
511 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
513 // allocate space for exactly three operands
514 void *operator new(size_t s) {
515 return User::operator new(s, 3);
517 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
518 : ConstantExpr(VectorType::get(
519 cast<VectorType>(C1->getType())->getElementType(),
520 cast<VectorType>(C3->getType())->getNumElements()),
521 Instruction::ShuffleVector,
527 /// Transparently provide more efficient getOperand methods.
528 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
531 /// ExtractValueConstantExpr - This class is private to
532 /// Constants.cpp, and is used behind the scenes to implement
533 /// extractvalue constant exprs.
534 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
535 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
537 // allocate space for exactly one operand
538 void *operator new(size_t s) {
539 return User::operator new(s, 1);
541 ExtractValueConstantExpr(Constant *Agg,
542 const SmallVector<unsigned, 4> &IdxList,
544 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
549 /// Indices - These identify which value to extract.
550 const SmallVector<unsigned, 4> Indices;
552 /// Transparently provide more efficient getOperand methods.
553 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
556 /// InsertValueConstantExpr - This class is private to
557 /// Constants.cpp, and is used behind the scenes to implement
558 /// insertvalue constant exprs.
559 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
560 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
562 // allocate space for exactly one operand
563 void *operator new(size_t s) {
564 return User::operator new(s, 2);
566 InsertValueConstantExpr(Constant *Agg, Constant *Val,
567 const SmallVector<unsigned, 4> &IdxList,
569 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
575 /// Indices - These identify the position for the insertion.
576 const SmallVector<unsigned, 4> Indices;
578 /// Transparently provide more efficient getOperand methods.
579 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
583 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
584 /// used behind the scenes to implement getelementpr constant exprs.
585 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
586 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
589 static GetElementPtrConstantExpr *Create(Constant *C,
590 const std::vector<Constant*>&IdxList,
591 const Type *DestTy) {
592 return new(IdxList.size() + 1)
593 GetElementPtrConstantExpr(C, IdxList, DestTy);
595 /// Transparently provide more efficient getOperand methods.
596 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
599 // CompareConstantExpr - This class is private to Constants.cpp, and is used
600 // behind the scenes to implement ICmp and FCmp constant expressions. This is
601 // needed in order to store the predicate value for these instructions.
602 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
603 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
604 // allocate space for exactly two operands
605 void *operator new(size_t s) {
606 return User::operator new(s, 2);
608 unsigned short predicate;
609 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
610 unsigned short pred, Constant* LHS, Constant* RHS)
611 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
615 /// Transparently provide more efficient getOperand methods.
616 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
619 } // end anonymous namespace
622 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
624 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
627 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
629 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
632 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
634 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
637 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
639 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
642 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
644 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
647 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
649 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
652 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
654 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
657 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
659 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
662 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
665 GetElementPtrConstantExpr::GetElementPtrConstantExpr
667 const std::vector<Constant*> &IdxList,
669 : ConstantExpr(DestTy, Instruction::GetElementPtr,
670 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
671 - (IdxList.size()+1),
674 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
675 OperandList[i+1] = IdxList[i];
678 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
682 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
684 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
687 } // End llvm namespace
690 // Utility function for determining if a ConstantExpr is a CastOp or not. This
691 // can't be inline because we don't want to #include Instruction.h into
693 bool ConstantExpr::isCast() const {
694 return Instruction::isCast(getOpcode());
697 bool ConstantExpr::isCompare() const {
698 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
701 bool ConstantExpr::hasIndices() const {
702 return getOpcode() == Instruction::ExtractValue ||
703 getOpcode() == Instruction::InsertValue;
706 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
707 if (const ExtractValueConstantExpr *EVCE =
708 dyn_cast<ExtractValueConstantExpr>(this))
709 return EVCE->Indices;
711 return cast<InsertValueConstantExpr>(this)->Indices;
714 unsigned ConstantExpr::getPredicate() const {
715 assert(getOpcode() == Instruction::FCmp ||
716 getOpcode() == Instruction::ICmp);
717 return ((const CompareConstantExpr*)this)->predicate;
720 /// getWithOperandReplaced - Return a constant expression identical to this
721 /// one, but with the specified operand set to the specified value.
723 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
724 assert(OpNo < getNumOperands() && "Operand num is out of range!");
725 assert(Op->getType() == getOperand(OpNo)->getType() &&
726 "Replacing operand with value of different type!");
727 if (getOperand(OpNo) == Op)
728 return const_cast<ConstantExpr*>(this);
730 Constant *Op0, *Op1, *Op2;
731 switch (getOpcode()) {
732 case Instruction::Trunc:
733 case Instruction::ZExt:
734 case Instruction::SExt:
735 case Instruction::FPTrunc:
736 case Instruction::FPExt:
737 case Instruction::UIToFP:
738 case Instruction::SIToFP:
739 case Instruction::FPToUI:
740 case Instruction::FPToSI:
741 case Instruction::PtrToInt:
742 case Instruction::IntToPtr:
743 case Instruction::BitCast:
744 return ConstantExpr::getCast(getOpcode(), Op, getType());
745 case Instruction::Select:
746 Op0 = (OpNo == 0) ? Op : getOperand(0);
747 Op1 = (OpNo == 1) ? Op : getOperand(1);
748 Op2 = (OpNo == 2) ? Op : getOperand(2);
749 return ConstantExpr::getSelect(Op0, Op1, Op2);
750 case Instruction::InsertElement:
751 Op0 = (OpNo == 0) ? Op : getOperand(0);
752 Op1 = (OpNo == 1) ? Op : getOperand(1);
753 Op2 = (OpNo == 2) ? Op : getOperand(2);
754 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
755 case Instruction::ExtractElement:
756 Op0 = (OpNo == 0) ? Op : getOperand(0);
757 Op1 = (OpNo == 1) ? Op : getOperand(1);
758 return ConstantExpr::getExtractElement(Op0, Op1);
759 case Instruction::ShuffleVector:
760 Op0 = (OpNo == 0) ? Op : getOperand(0);
761 Op1 = (OpNo == 1) ? Op : getOperand(1);
762 Op2 = (OpNo == 2) ? Op : getOperand(2);
763 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
764 case Instruction::GetElementPtr: {
765 SmallVector<Constant*, 8> Ops;
766 Ops.resize(getNumOperands()-1);
767 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
768 Ops[i-1] = getOperand(i);
770 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
772 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
775 assert(getNumOperands() == 2 && "Must be binary operator?");
776 Op0 = (OpNo == 0) ? Op : getOperand(0);
777 Op1 = (OpNo == 1) ? Op : getOperand(1);
778 return ConstantExpr::get(getOpcode(), Op0, Op1);
782 /// getWithOperands - This returns the current constant expression with the
783 /// operands replaced with the specified values. The specified operands must
784 /// match count and type with the existing ones.
785 Constant *ConstantExpr::
786 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
787 assert(NumOps == getNumOperands() && "Operand count mismatch!");
788 bool AnyChange = false;
789 for (unsigned i = 0; i != NumOps; ++i) {
790 assert(Ops[i]->getType() == getOperand(i)->getType() &&
791 "Operand type mismatch!");
792 AnyChange |= Ops[i] != getOperand(i);
794 if (!AnyChange) // No operands changed, return self.
795 return const_cast<ConstantExpr*>(this);
797 switch (getOpcode()) {
798 case Instruction::Trunc:
799 case Instruction::ZExt:
800 case Instruction::SExt:
801 case Instruction::FPTrunc:
802 case Instruction::FPExt:
803 case Instruction::UIToFP:
804 case Instruction::SIToFP:
805 case Instruction::FPToUI:
806 case Instruction::FPToSI:
807 case Instruction::PtrToInt:
808 case Instruction::IntToPtr:
809 case Instruction::BitCast:
810 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
811 case Instruction::Select:
812 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
813 case Instruction::InsertElement:
814 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
815 case Instruction::ExtractElement:
816 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
817 case Instruction::ShuffleVector:
818 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
819 case Instruction::GetElementPtr:
820 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
821 case Instruction::ICmp:
822 case Instruction::FCmp:
823 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
825 assert(getNumOperands() == 2 && "Must be binary operator?");
826 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
831 //===----------------------------------------------------------------------===//
832 // isValueValidForType implementations
834 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
835 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
836 if (Ty == Type::Int1Ty)
837 return Val == 0 || Val == 1;
839 return true; // always true, has to fit in largest type
840 uint64_t Max = (1ll << NumBits) - 1;
844 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
845 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
846 if (Ty == Type::Int1Ty)
847 return Val == 0 || Val == 1 || Val == -1;
849 return true; // always true, has to fit in largest type
850 int64_t Min = -(1ll << (NumBits-1));
851 int64_t Max = (1ll << (NumBits-1)) - 1;
852 return (Val >= Min && Val <= Max);
855 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
856 // convert modifies in place, so make a copy.
857 APFloat Val2 = APFloat(Val);
859 switch (Ty->getTypeID()) {
861 return false; // These can't be represented as floating point!
863 // FIXME rounding mode needs to be more flexible
864 case Type::FloatTyID: {
865 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
867 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
870 case Type::DoubleTyID: {
871 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
872 &Val2.getSemantics() == &APFloat::IEEEdouble)
874 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
877 case Type::X86_FP80TyID:
878 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
879 &Val2.getSemantics() == &APFloat::IEEEdouble ||
880 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
881 case Type::FP128TyID:
882 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
883 &Val2.getSemantics() == &APFloat::IEEEdouble ||
884 &Val2.getSemantics() == &APFloat::IEEEquad;
885 case Type::PPC_FP128TyID:
886 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
887 &Val2.getSemantics() == &APFloat::IEEEdouble ||
888 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
892 //===----------------------------------------------------------------------===//
893 // Factory Function Implementation
896 // The number of operands for each ConstantCreator::create method is
897 // determined by the ConstantTraits template.
898 // ConstantCreator - A class that is used to create constants by
899 // ValueMap*. This class should be partially specialized if there is
900 // something strange that needs to be done to interface to the ctor for the
904 template<class ValType>
905 struct ConstantTraits;
907 template<typename T, typename Alloc>
908 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
909 static unsigned uses(const std::vector<T, Alloc>& v) {
914 template<class ConstantClass, class TypeClass, class ValType>
915 struct VISIBILITY_HIDDEN ConstantCreator {
916 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
917 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
921 template<class ConstantClass, class TypeClass>
922 struct VISIBILITY_HIDDEN ConvertConstantType {
923 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
924 llvm_unreachable("This type cannot be converted!");
928 template<class ValType, class TypeClass, class ConstantClass,
929 bool HasLargeKey = false /*true for arrays and structs*/ >
930 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
932 typedef std::pair<const Type*, ValType> MapKey;
933 typedef std::map<MapKey, Constant *> MapTy;
934 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
935 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
937 /// Map - This is the main map from the element descriptor to the Constants.
938 /// This is the primary way we avoid creating two of the same shape
942 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
943 /// from the constants to their element in Map. This is important for
944 /// removal of constants from the array, which would otherwise have to scan
945 /// through the map with very large keys.
946 InverseMapTy InverseMap;
948 /// AbstractTypeMap - Map for abstract type constants.
950 AbstractTypeMapTy AbstractTypeMap;
952 /// ValueMapLock - Mutex for this map.
953 sys::SmartMutex<true> ValueMapLock;
956 // NOTE: This function is not locked. It is the caller's responsibility
957 // to enforce proper synchronization.
958 typename MapTy::iterator map_end() { return Map.end(); }
960 /// InsertOrGetItem - Return an iterator for the specified element.
961 /// If the element exists in the map, the returned iterator points to the
962 /// entry and Exists=true. If not, the iterator points to the newly
963 /// inserted entry and returns Exists=false. Newly inserted entries have
964 /// I->second == 0, and should be filled in.
965 /// NOTE: This function is not locked. It is the caller's responsibility
966 // to enforce proper synchronization.
967 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
970 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
976 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
978 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
979 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
980 IMI->second->second == CP &&
981 "InverseMap corrupt!");
985 typename MapTy::iterator I =
986 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
988 if (I == Map.end() || I->second != CP) {
989 // FIXME: This should not use a linear scan. If this gets to be a
990 // performance problem, someone should look at this.
991 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
997 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
998 typename MapTy::iterator I) {
999 ConstantClass* Result =
1000 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1002 assert(Result->getType() == Ty && "Type specified is not correct!");
1003 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1005 if (HasLargeKey) // Remember the reverse mapping if needed.
1006 InverseMap.insert(std::make_pair(Result, I));
1008 // If the type of the constant is abstract, make sure that an entry
1009 // exists for it in the AbstractTypeMap.
1010 if (Ty->isAbstract()) {
1011 typename AbstractTypeMapTy::iterator TI =
1012 AbstractTypeMap.find(Ty);
1014 if (TI == AbstractTypeMap.end()) {
1015 // Add ourselves to the ATU list of the type.
1016 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1018 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1026 /// getOrCreate - Return the specified constant from the map, creating it if
1028 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1029 sys::SmartScopedLock<true> Lock(ValueMapLock);
1030 MapKey Lookup(Ty, V);
1031 ConstantClass* Result = 0;
1033 typename MapTy::iterator I = Map.find(Lookup);
1034 // Is it in the map?
1036 Result = static_cast<ConstantClass *>(I->second);
1039 // If no preexisting value, create one now...
1040 Result = Create(Ty, V, I);
1046 void remove(ConstantClass *CP) {
1047 sys::SmartScopedLock<true> Lock(ValueMapLock);
1048 typename MapTy::iterator I = FindExistingElement(CP);
1049 assert(I != Map.end() && "Constant not found in constant table!");
1050 assert(I->second == CP && "Didn't find correct element?");
1052 if (HasLargeKey) // Remember the reverse mapping if needed.
1053 InverseMap.erase(CP);
1055 // Now that we found the entry, make sure this isn't the entry that
1056 // the AbstractTypeMap points to.
1057 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1058 if (Ty->isAbstract()) {
1059 assert(AbstractTypeMap.count(Ty) &&
1060 "Abstract type not in AbstractTypeMap?");
1061 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1062 if (ATMEntryIt == I) {
1063 // Yes, we are removing the representative entry for this type.
1064 // See if there are any other entries of the same type.
1065 typename MapTy::iterator TmpIt = ATMEntryIt;
1067 // First check the entry before this one...
1068 if (TmpIt != Map.begin()) {
1070 if (TmpIt->first.first != Ty) // Not the same type, move back...
1074 // If we didn't find the same type, try to move forward...
1075 if (TmpIt == ATMEntryIt) {
1077 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1078 --TmpIt; // No entry afterwards with the same type
1081 // If there is another entry in the map of the same abstract type,
1082 // update the AbstractTypeMap entry now.
1083 if (TmpIt != ATMEntryIt) {
1086 // Otherwise, we are removing the last instance of this type
1087 // from the table. Remove from the ATM, and from user list.
1088 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1089 AbstractTypeMap.erase(Ty);
1098 /// MoveConstantToNewSlot - If we are about to change C to be the element
1099 /// specified by I, update our internal data structures to reflect this
1101 /// NOTE: This function is not locked. It is the responsibility of the
1102 /// caller to enforce proper synchronization if using this method.
1103 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1104 // First, remove the old location of the specified constant in the map.
1105 typename MapTy::iterator OldI = FindExistingElement(C);
1106 assert(OldI != Map.end() && "Constant not found in constant table!");
1107 assert(OldI->second == C && "Didn't find correct element?");
1109 // If this constant is the representative element for its abstract type,
1110 // update the AbstractTypeMap so that the representative element is I.
1111 if (C->getType()->isAbstract()) {
1112 typename AbstractTypeMapTy::iterator ATI =
1113 AbstractTypeMap.find(C->getType());
1114 assert(ATI != AbstractTypeMap.end() &&
1115 "Abstract type not in AbstractTypeMap?");
1116 if (ATI->second == OldI)
1120 // Remove the old entry from the map.
1123 // Update the inverse map so that we know that this constant is now
1124 // located at descriptor I.
1126 assert(I->second == C && "Bad inversemap entry!");
1131 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1132 sys::SmartScopedLock<true> Lock(ValueMapLock);
1133 typename AbstractTypeMapTy::iterator I =
1134 AbstractTypeMap.find(cast<Type>(OldTy));
1136 assert(I != AbstractTypeMap.end() &&
1137 "Abstract type not in AbstractTypeMap?");
1139 // Convert a constant at a time until the last one is gone. The last one
1140 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1141 // eliminated eventually.
1143 ConvertConstantType<ConstantClass,
1144 TypeClass>::convert(
1145 static_cast<ConstantClass *>(I->second->second),
1146 cast<TypeClass>(NewTy));
1148 I = AbstractTypeMap.find(cast<Type>(OldTy));
1149 } while (I != AbstractTypeMap.end());
1152 // If the type became concrete without being refined to any other existing
1153 // type, we just remove ourselves from the ATU list.
1154 void typeBecameConcrete(const DerivedType *AbsTy) {
1155 AbsTy->removeAbstractTypeUser(this);
1159 DOUT << "Constant.cpp: ValueMap\n";
1166 //---- ConstantAggregateZero::get() implementation...
1169 // ConstantAggregateZero does not take extra "value" argument...
1170 template<class ValType>
1171 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1172 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1173 return new ConstantAggregateZero(Ty);
1178 struct ConvertConstantType<ConstantAggregateZero, Type> {
1179 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1180 // Make everyone now use a constant of the new type...
1181 Constant *New = ConstantAggregateZero::get(NewTy);
1182 assert(New != OldC && "Didn't replace constant??");
1183 OldC->uncheckedReplaceAllUsesWith(New);
1184 OldC->destroyConstant(); // This constant is now dead, destroy it.
1189 static ManagedStatic<ValueMap<char, Type,
1190 ConstantAggregateZero> > AggZeroConstants;
1192 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1194 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1195 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1196 "Cannot create an aggregate zero of non-aggregate type!");
1198 // Implicitly locked.
1199 return AggZeroConstants->getOrCreate(Ty, 0);
1202 /// destroyConstant - Remove the constant from the constant table...
1204 void ConstantAggregateZero::destroyConstant() {
1205 // Implicitly locked.
1206 AggZeroConstants->remove(this);
1207 destroyConstantImpl();
1210 //---- ConstantArray::get() implementation...
1214 struct ConvertConstantType<ConstantArray, ArrayType> {
1215 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1216 // Make everyone now use a constant of the new type...
1217 std::vector<Constant*> C;
1218 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1219 C.push_back(cast<Constant>(OldC->getOperand(i)));
1220 Constant *New = ConstantArray::get(NewTy, C);
1221 assert(New != OldC && "Didn't replace constant??");
1222 OldC->uncheckedReplaceAllUsesWith(New);
1223 OldC->destroyConstant(); // This constant is now dead, destroy it.
1228 static std::vector<Constant*> getValType(ConstantArray *CA) {
1229 std::vector<Constant*> Elements;
1230 Elements.reserve(CA->getNumOperands());
1231 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1232 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1236 typedef ValueMap<std::vector<Constant*>, ArrayType,
1237 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1238 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1240 Constant *ConstantArray::get(const ArrayType *Ty,
1241 const std::vector<Constant*> &V) {
1242 // If this is an all-zero array, return a ConstantAggregateZero object
1245 if (!C->isNullValue()) {
1246 // Implicitly locked.
1247 return ArrayConstants->getOrCreate(Ty, V);
1249 for (unsigned i = 1, e = V.size(); i != e; ++i)
1251 // Implicitly locked.
1252 return ArrayConstants->getOrCreate(Ty, V);
1256 return ConstantAggregateZero::get(Ty);
1259 /// destroyConstant - Remove the constant from the constant table...
1261 void ConstantArray::destroyConstant() {
1262 // Implicitly locked.
1263 ArrayConstants->remove(this);
1264 destroyConstantImpl();
1267 /// isString - This method returns true if the array is an array of i8, and
1268 /// if the elements of the array are all ConstantInt's.
1269 bool ConstantArray::isString() const {
1270 // Check the element type for i8...
1271 if (getType()->getElementType() != Type::Int8Ty)
1273 // Check the elements to make sure they are all integers, not constant
1275 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1276 if (!isa<ConstantInt>(getOperand(i)))
1281 /// isCString - This method returns true if the array is a string (see
1282 /// isString) and it ends in a null byte \\0 and does not contains any other
1283 /// null bytes except its terminator.
1284 bool ConstantArray::isCString() const {
1285 // Check the element type for i8...
1286 if (getType()->getElementType() != Type::Int8Ty)
1289 // Last element must be a null.
1290 if (!getOperand(getNumOperands()-1)->isNullValue())
1292 // Other elements must be non-null integers.
1293 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1294 if (!isa<ConstantInt>(getOperand(i)))
1296 if (getOperand(i)->isNullValue())
1303 /// getAsString - If the sub-element type of this array is i8
1304 /// then this method converts the array to an std::string and returns it.
1305 /// Otherwise, it asserts out.
1307 std::string ConstantArray::getAsString() const {
1308 assert(isString() && "Not a string!");
1310 Result.reserve(getNumOperands());
1311 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1312 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1317 //---- ConstantStruct::get() implementation...
1322 struct ConvertConstantType<ConstantStruct, StructType> {
1323 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1324 // Make everyone now use a constant of the new type...
1325 std::vector<Constant*> C;
1326 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1327 C.push_back(cast<Constant>(OldC->getOperand(i)));
1328 Constant *New = ConstantStruct::get(NewTy, C);
1329 assert(New != OldC && "Didn't replace constant??");
1331 OldC->uncheckedReplaceAllUsesWith(New);
1332 OldC->destroyConstant(); // This constant is now dead, destroy it.
1337 typedef ValueMap<std::vector<Constant*>, StructType,
1338 ConstantStruct, true /*largekey*/> StructConstantsTy;
1339 static ManagedStatic<StructConstantsTy> StructConstants;
1341 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1342 std::vector<Constant*> Elements;
1343 Elements.reserve(CS->getNumOperands());
1344 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1345 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1349 Constant *ConstantStruct::get(const StructType *Ty,
1350 const std::vector<Constant*> &V) {
1351 // Create a ConstantAggregateZero value if all elements are zeros...
1352 for (unsigned i = 0, e = V.size(); i != e; ++i)
1353 if (!V[i]->isNullValue())
1354 // Implicitly locked.
1355 return StructConstants->getOrCreate(Ty, V);
1357 return ConstantAggregateZero::get(Ty);
1360 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1361 std::vector<const Type*> StructEls;
1362 StructEls.reserve(V.size());
1363 for (unsigned i = 0, e = V.size(); i != e; ++i)
1364 StructEls.push_back(V[i]->getType());
1365 return get(StructType::get(StructEls, packed), V);
1368 // destroyConstant - Remove the constant from the constant table...
1370 void ConstantStruct::destroyConstant() {
1371 // Implicitly locked.
1372 StructConstants->remove(this);
1373 destroyConstantImpl();
1376 //---- ConstantVector::get() implementation...
1380 struct ConvertConstantType<ConstantVector, VectorType> {
1381 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1382 // Make everyone now use a constant of the new type...
1383 std::vector<Constant*> C;
1384 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1385 C.push_back(cast<Constant>(OldC->getOperand(i)));
1386 Constant *New = ConstantVector::get(NewTy, C);
1387 assert(New != OldC && "Didn't replace constant??");
1388 OldC->uncheckedReplaceAllUsesWith(New);
1389 OldC->destroyConstant(); // This constant is now dead, destroy it.
1394 static std::vector<Constant*> getValType(ConstantVector *CP) {
1395 std::vector<Constant*> Elements;
1396 Elements.reserve(CP->getNumOperands());
1397 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1398 Elements.push_back(CP->getOperand(i));
1402 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1403 ConstantVector> > VectorConstants;
1405 Constant *ConstantVector::get(const VectorType *Ty,
1406 const std::vector<Constant*> &V) {
1407 assert(!V.empty() && "Vectors can't be empty");
1408 // If this is an all-undef or alll-zero vector, return a
1409 // ConstantAggregateZero or UndefValue.
1411 bool isZero = C->isNullValue();
1412 bool isUndef = isa<UndefValue>(C);
1414 if (isZero || isUndef) {
1415 for (unsigned i = 1, e = V.size(); i != e; ++i)
1417 isZero = isUndef = false;
1423 return ConstantAggregateZero::get(Ty);
1425 return UndefValue::get(Ty);
1427 // Implicitly locked.
1428 return VectorConstants->getOrCreate(Ty, V);
1431 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1432 assert(!V.empty() && "Cannot infer type if V is empty");
1433 return get(VectorType::get(V.front()->getType(),V.size()), V);
1436 // destroyConstant - Remove the constant from the constant table...
1438 void ConstantVector::destroyConstant() {
1439 // Implicitly locked.
1440 VectorConstants->remove(this);
1441 destroyConstantImpl();
1444 /// This function will return true iff every element in this vector constant
1445 /// is set to all ones.
1446 /// @returns true iff this constant's emements are all set to all ones.
1447 /// @brief Determine if the value is all ones.
1448 bool ConstantVector::isAllOnesValue() const {
1449 // Check out first element.
1450 const Constant *Elt = getOperand(0);
1451 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1452 if (!CI || !CI->isAllOnesValue()) return false;
1453 // Then make sure all remaining elements point to the same value.
1454 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1455 if (getOperand(I) != Elt) return false;
1460 /// getSplatValue - If this is a splat constant, where all of the
1461 /// elements have the same value, return that value. Otherwise return null.
1462 Constant *ConstantVector::getSplatValue() {
1463 // Check out first element.
1464 Constant *Elt = getOperand(0);
1465 // Then make sure all remaining elements point to the same value.
1466 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1467 if (getOperand(I) != Elt) return 0;
1471 //---- ConstantPointerNull::get() implementation...
1475 // ConstantPointerNull does not take extra "value" argument...
1476 template<class ValType>
1477 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1478 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1479 return new ConstantPointerNull(Ty);
1484 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1485 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1486 // Make everyone now use a constant of the new type...
1487 Constant *New = ConstantPointerNull::get(NewTy);
1488 assert(New != OldC && "Didn't replace constant??");
1489 OldC->uncheckedReplaceAllUsesWith(New);
1490 OldC->destroyConstant(); // This constant is now dead, destroy it.
1495 static ManagedStatic<ValueMap<char, PointerType,
1496 ConstantPointerNull> > NullPtrConstants;
1498 static char getValType(ConstantPointerNull *) {
1503 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1504 // Implicitly locked.
1505 return NullPtrConstants->getOrCreate(Ty, 0);
1508 // destroyConstant - Remove the constant from the constant table...
1510 void ConstantPointerNull::destroyConstant() {
1511 // Implicitly locked.
1512 NullPtrConstants->remove(this);
1513 destroyConstantImpl();
1517 //---- UndefValue::get() implementation...
1521 // UndefValue does not take extra "value" argument...
1522 template<class ValType>
1523 struct ConstantCreator<UndefValue, Type, ValType> {
1524 static UndefValue *create(const Type *Ty, const ValType &V) {
1525 return new UndefValue(Ty);
1530 struct ConvertConstantType<UndefValue, Type> {
1531 static void convert(UndefValue *OldC, const Type *NewTy) {
1532 // Make everyone now use a constant of the new type.
1533 Constant *New = UndefValue::get(NewTy);
1534 assert(New != OldC && "Didn't replace constant??");
1535 OldC->uncheckedReplaceAllUsesWith(New);
1536 OldC->destroyConstant(); // This constant is now dead, destroy it.
1541 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1543 static char getValType(UndefValue *) {
1548 UndefValue *UndefValue::get(const Type *Ty) {
1549 // Implicitly locked.
1550 return UndefValueConstants->getOrCreate(Ty, 0);
1553 // destroyConstant - Remove the constant from the constant table.
1555 void UndefValue::destroyConstant() {
1556 // Implicitly locked.
1557 UndefValueConstants->remove(this);
1558 destroyConstantImpl();
1561 //---- MDString::get() implementation
1564 MDString::MDString(const char *begin, const char *end)
1565 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1566 StrBegin(begin), StrEnd(end) {}
1568 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1570 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1571 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1572 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1574 MDString *&S = Entry.getValue();
1575 if (!S) S = new MDString(Entry.getKeyData(),
1576 Entry.getKeyData() + Entry.getKeyLength());
1581 MDString *MDString::get(const std::string &Str) {
1582 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1583 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1584 Str.data(), Str.data() + Str.size());
1585 MDString *&S = Entry.getValue();
1586 if (!S) S = new MDString(Entry.getKeyData(),
1587 Entry.getKeyData() + Entry.getKeyLength());
1592 void MDString::destroyConstant() {
1593 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1594 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1595 destroyConstantImpl();
1598 //---- MDNode::get() implementation
1601 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1603 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1604 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1605 for (unsigned i = 0; i != NumVals; ++i)
1606 Node.push_back(ElementVH(Vals[i], this));
1609 void MDNode::Profile(FoldingSetNodeID &ID) const {
1610 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1614 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1615 FoldingSetNodeID ID;
1616 for (unsigned i = 0; i != NumVals; ++i)
1617 ID.AddPointer(Vals[i]);
1619 ConstantsLock->reader_acquire();
1621 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1622 ConstantsLock->reader_release();
1625 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1626 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1628 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1629 N = new(0) MDNode(Vals, NumVals);
1630 MDNodeSet->InsertNode(N, InsertPoint);
1636 void MDNode::destroyConstant() {
1637 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1638 MDNodeSet->RemoveNode(this);
1640 destroyConstantImpl();
1643 //---- ConstantExpr::get() implementations...
1648 struct ExprMapKeyType {
1649 typedef SmallVector<unsigned, 4> IndexList;
1651 ExprMapKeyType(unsigned opc,
1652 const std::vector<Constant*> &ops,
1653 unsigned short pred = 0,
1654 const IndexList &inds = IndexList())
1655 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1658 std::vector<Constant*> operands;
1660 bool operator==(const ExprMapKeyType& that) const {
1661 return this->opcode == that.opcode &&
1662 this->predicate == that.predicate &&
1663 this->operands == that.operands &&
1664 this->indices == that.indices;
1666 bool operator<(const ExprMapKeyType & that) const {
1667 return this->opcode < that.opcode ||
1668 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1669 (this->opcode == that.opcode && this->predicate == that.predicate &&
1670 this->operands < that.operands) ||
1671 (this->opcode == that.opcode && this->predicate == that.predicate &&
1672 this->operands == that.operands && this->indices < that.indices);
1675 bool operator!=(const ExprMapKeyType& that) const {
1676 return !(*this == that);
1684 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1685 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1686 unsigned short pred = 0) {
1687 if (Instruction::isCast(V.opcode))
1688 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1689 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1690 V.opcode < Instruction::BinaryOpsEnd))
1691 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1692 if (V.opcode == Instruction::Select)
1693 return new SelectConstantExpr(V.operands[0], V.operands[1],
1695 if (V.opcode == Instruction::ExtractElement)
1696 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1697 if (V.opcode == Instruction::InsertElement)
1698 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1700 if (V.opcode == Instruction::ShuffleVector)
1701 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1703 if (V.opcode == Instruction::InsertValue)
1704 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1706 if (V.opcode == Instruction::ExtractValue)
1707 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1708 if (V.opcode == Instruction::GetElementPtr) {
1709 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1710 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1713 // The compare instructions are weird. We have to encode the predicate
1714 // value and it is combined with the instruction opcode by multiplying
1715 // the opcode by one hundred. We must decode this to get the predicate.
1716 if (V.opcode == Instruction::ICmp)
1717 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1718 V.operands[0], V.operands[1]);
1719 if (V.opcode == Instruction::FCmp)
1720 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1721 V.operands[0], V.operands[1]);
1722 llvm_unreachable("Invalid ConstantExpr!");
1728 struct ConvertConstantType<ConstantExpr, Type> {
1729 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1731 switch (OldC->getOpcode()) {
1732 case Instruction::Trunc:
1733 case Instruction::ZExt:
1734 case Instruction::SExt:
1735 case Instruction::FPTrunc:
1736 case Instruction::FPExt:
1737 case Instruction::UIToFP:
1738 case Instruction::SIToFP:
1739 case Instruction::FPToUI:
1740 case Instruction::FPToSI:
1741 case Instruction::PtrToInt:
1742 case Instruction::IntToPtr:
1743 case Instruction::BitCast:
1744 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1747 case Instruction::Select:
1748 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1749 OldC->getOperand(1),
1750 OldC->getOperand(2));
1753 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1754 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1755 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1756 OldC->getOperand(1));
1758 case Instruction::GetElementPtr:
1759 // Make everyone now use a constant of the new type...
1760 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1761 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1762 &Idx[0], Idx.size());
1766 assert(New != OldC && "Didn't replace constant??");
1767 OldC->uncheckedReplaceAllUsesWith(New);
1768 OldC->destroyConstant(); // This constant is now dead, destroy it.
1771 } // end namespace llvm
1774 static ExprMapKeyType getValType(ConstantExpr *CE) {
1775 std::vector<Constant*> Operands;
1776 Operands.reserve(CE->getNumOperands());
1777 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1778 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1779 return ExprMapKeyType(CE->getOpcode(), Operands,
1780 CE->isCompare() ? CE->getPredicate() : 0,
1782 CE->getIndices() : SmallVector<unsigned, 4>());
1785 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1786 ConstantExpr> > ExprConstants;
1788 /// This is a utility function to handle folding of casts and lookup of the
1789 /// cast in the ExprConstants map. It is used by the various get* methods below.
1790 static inline Constant *getFoldedCast(
1791 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1792 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1793 // Fold a few common cases
1795 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1798 // Look up the constant in the table first to ensure uniqueness
1799 std::vector<Constant*> argVec(1, C);
1800 ExprMapKeyType Key(opc, argVec);
1802 // Implicitly locked.
1803 return ExprConstants->getOrCreate(Ty, Key);
1806 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1807 Instruction::CastOps opc = Instruction::CastOps(oc);
1808 assert(Instruction::isCast(opc) && "opcode out of range");
1809 assert(C && Ty && "Null arguments to getCast");
1810 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1814 llvm_unreachable("Invalid cast opcode");
1816 case Instruction::Trunc: return getTrunc(C, Ty);
1817 case Instruction::ZExt: return getZExt(C, Ty);
1818 case Instruction::SExt: return getSExt(C, Ty);
1819 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1820 case Instruction::FPExt: return getFPExtend(C, Ty);
1821 case Instruction::UIToFP: return getUIToFP(C, Ty);
1822 case Instruction::SIToFP: return getSIToFP(C, Ty);
1823 case Instruction::FPToUI: return getFPToUI(C, Ty);
1824 case Instruction::FPToSI: return getFPToSI(C, Ty);
1825 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1826 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1827 case Instruction::BitCast: return getBitCast(C, Ty);
1832 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1833 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1834 return getCast(Instruction::BitCast, C, Ty);
1835 return getCast(Instruction::ZExt, C, Ty);
1838 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1839 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1840 return getCast(Instruction::BitCast, C, Ty);
1841 return getCast(Instruction::SExt, C, Ty);
1844 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1845 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1846 return getCast(Instruction::BitCast, C, Ty);
1847 return getCast(Instruction::Trunc, C, Ty);
1850 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1851 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1852 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1854 if (Ty->isInteger())
1855 return getCast(Instruction::PtrToInt, S, Ty);
1856 return getCast(Instruction::BitCast, S, Ty);
1859 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1861 assert(C->getType()->isIntOrIntVector() &&
1862 Ty->isIntOrIntVector() && "Invalid cast");
1863 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1864 unsigned DstBits = Ty->getScalarSizeInBits();
1865 Instruction::CastOps opcode =
1866 (SrcBits == DstBits ? Instruction::BitCast :
1867 (SrcBits > DstBits ? Instruction::Trunc :
1868 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1869 return getCast(opcode, C, Ty);
1872 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1873 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1875 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1876 unsigned DstBits = Ty->getScalarSizeInBits();
1877 if (SrcBits == DstBits)
1878 return C; // Avoid a useless cast
1879 Instruction::CastOps opcode =
1880 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1881 return getCast(opcode, C, Ty);
1884 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1886 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1887 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1889 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1890 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1891 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1892 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1893 "SrcTy must be larger than DestTy for Trunc!");
1895 return getFoldedCast(Instruction::Trunc, C, Ty);
1898 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1900 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1901 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1903 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1904 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1905 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1906 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1907 "SrcTy must be smaller than DestTy for SExt!");
1909 return getFoldedCast(Instruction::SExt, C, Ty);
1912 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1914 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1915 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1917 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1918 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1919 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1920 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1921 "SrcTy must be smaller than DestTy for ZExt!");
1923 return getFoldedCast(Instruction::ZExt, C, Ty);
1926 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1928 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1929 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1931 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1932 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1933 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1934 "This is an illegal floating point truncation!");
1935 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1938 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1940 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1941 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1943 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1944 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1945 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1946 "This is an illegal floating point extension!");
1947 return getFoldedCast(Instruction::FPExt, C, Ty);
1950 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1952 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1953 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1955 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1956 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1957 "This is an illegal uint to floating point cast!");
1958 return getFoldedCast(Instruction::UIToFP, C, Ty);
1961 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1963 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1964 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1966 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1967 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1968 "This is an illegal sint to floating point cast!");
1969 return getFoldedCast(Instruction::SIToFP, C, Ty);
1972 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1974 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1975 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1977 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1978 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1979 "This is an illegal floating point to uint cast!");
1980 return getFoldedCast(Instruction::FPToUI, C, Ty);
1983 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1985 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1986 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1988 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1989 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1990 "This is an illegal floating point to sint cast!");
1991 return getFoldedCast(Instruction::FPToSI, C, Ty);
1994 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1995 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1996 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1997 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2000 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2001 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2002 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2003 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2006 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2007 // BitCast implies a no-op cast of type only. No bits change. However, you
2008 // can't cast pointers to anything but pointers.
2010 const Type *SrcTy = C->getType();
2011 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2012 "BitCast cannot cast pointer to non-pointer and vice versa");
2014 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2015 // or nonptr->ptr). For all the other types, the cast is okay if source and
2016 // destination bit widths are identical.
2017 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2018 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2020 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2022 // It is common to ask for a bitcast of a value to its own type, handle this
2024 if (C->getType() == DstTy) return C;
2026 return getFoldedCast(Instruction::BitCast, C, DstTy);
2029 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2030 Constant *C1, Constant *C2) {
2031 // Check the operands for consistency first
2032 assert(Opcode >= Instruction::BinaryOpsBegin &&
2033 Opcode < Instruction::BinaryOpsEnd &&
2034 "Invalid opcode in binary constant expression");
2035 assert(C1->getType() == C2->getType() &&
2036 "Operand types in binary constant expression should match");
2038 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2039 if (Constant *FC = ConstantFoldBinaryInstruction(
2040 getGlobalContext(), Opcode, C1, C2))
2041 return FC; // Fold a few common cases...
2043 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2044 ExprMapKeyType Key(Opcode, argVec);
2046 // Implicitly locked.
2047 return ExprConstants->getOrCreate(ReqTy, Key);
2050 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2051 Constant *C1, Constant *C2) {
2052 switch (predicate) {
2053 default: llvm_unreachable("Invalid CmpInst predicate");
2054 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2055 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2056 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2057 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2058 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2059 case CmpInst::FCMP_TRUE:
2060 return getFCmp(predicate, C1, C2);
2062 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2063 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2064 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2065 case CmpInst::ICMP_SLE:
2066 return getICmp(predicate, C1, C2);
2070 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2071 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2072 if (C1->getType()->isFPOrFPVector()) {
2073 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2074 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2075 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2079 case Instruction::Add:
2080 case Instruction::Sub:
2081 case Instruction::Mul:
2082 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2083 assert(C1->getType()->isIntOrIntVector() &&
2084 "Tried to create an integer operation on a non-integer type!");
2086 case Instruction::FAdd:
2087 case Instruction::FSub:
2088 case Instruction::FMul:
2089 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2090 assert(C1->getType()->isFPOrFPVector() &&
2091 "Tried to create a floating-point operation on a "
2092 "non-floating-point type!");
2094 case Instruction::UDiv:
2095 case Instruction::SDiv:
2096 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2097 assert(C1->getType()->isIntOrIntVector() &&
2098 "Tried to create an arithmetic operation on a non-arithmetic type!");
2100 case Instruction::FDiv:
2101 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2102 assert(C1->getType()->isFPOrFPVector() &&
2103 "Tried to create an arithmetic operation on a non-arithmetic type!");
2105 case Instruction::URem:
2106 case Instruction::SRem:
2107 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2108 assert(C1->getType()->isIntOrIntVector() &&
2109 "Tried to create an arithmetic operation on a non-arithmetic type!");
2111 case Instruction::FRem:
2112 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2113 assert(C1->getType()->isFPOrFPVector() &&
2114 "Tried to create an arithmetic operation on a non-arithmetic type!");
2116 case Instruction::And:
2117 case Instruction::Or:
2118 case Instruction::Xor:
2119 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2120 assert(C1->getType()->isIntOrIntVector() &&
2121 "Tried to create a logical operation on a non-integral type!");
2123 case Instruction::Shl:
2124 case Instruction::LShr:
2125 case Instruction::AShr:
2126 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2127 assert(C1->getType()->isIntOrIntVector() &&
2128 "Tried to create a shift operation on a non-integer type!");
2135 return getTy(C1->getType(), Opcode, C1, C2);
2138 Constant *ConstantExpr::getCompare(unsigned short pred,
2139 Constant *C1, Constant *C2) {
2140 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2141 return getCompareTy(pred, C1, C2);
2144 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2145 Constant *V1, Constant *V2) {
2146 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2148 if (ReqTy == V1->getType())
2149 if (Constant *SC = ConstantFoldSelectInstruction(
2150 getGlobalContext(), C, V1, V2))
2151 return SC; // Fold common cases
2153 std::vector<Constant*> argVec(3, C);
2156 ExprMapKeyType Key(Instruction::Select, argVec);
2158 // Implicitly locked.
2159 return ExprConstants->getOrCreate(ReqTy, Key);
2162 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2165 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2167 cast<PointerType>(ReqTy)->getElementType() &&
2168 "GEP indices invalid!");
2170 if (Constant *FC = ConstantFoldGetElementPtr(
2171 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
2172 return FC; // Fold a few common cases...
2174 assert(isa<PointerType>(C->getType()) &&
2175 "Non-pointer type for constant GetElementPtr expression");
2176 // Look up the constant in the table first to ensure uniqueness
2177 std::vector<Constant*> ArgVec;
2178 ArgVec.reserve(NumIdx+1);
2179 ArgVec.push_back(C);
2180 for (unsigned i = 0; i != NumIdx; ++i)
2181 ArgVec.push_back(cast<Constant>(Idxs[i]));
2182 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2184 // Implicitly locked.
2185 return ExprConstants->getOrCreate(ReqTy, Key);
2188 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2190 // Get the result type of the getelementptr!
2192 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2193 assert(Ty && "GEP indices invalid!");
2194 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2195 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2198 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2200 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2205 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2206 assert(LHS->getType() == RHS->getType());
2207 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2208 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2210 if (Constant *FC = ConstantFoldCompareInstruction(
2211 getGlobalContext(),pred, LHS, RHS))
2212 return FC; // Fold a few common cases...
2214 // Look up the constant in the table first to ensure uniqueness
2215 std::vector<Constant*> ArgVec;
2216 ArgVec.push_back(LHS);
2217 ArgVec.push_back(RHS);
2218 // Get the key type with both the opcode and predicate
2219 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2221 // Implicitly locked.
2222 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2226 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2227 assert(LHS->getType() == RHS->getType());
2228 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2230 if (Constant *FC = ConstantFoldCompareInstruction(
2231 getGlobalContext(), pred, LHS, RHS))
2232 return FC; // Fold a few common cases...
2234 // Look up the constant in the table first to ensure uniqueness
2235 std::vector<Constant*> ArgVec;
2236 ArgVec.push_back(LHS);
2237 ArgVec.push_back(RHS);
2238 // Get the key type with both the opcode and predicate
2239 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2241 // Implicitly locked.
2242 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2245 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2247 if (Constant *FC = ConstantFoldExtractElementInstruction(
2248 getGlobalContext(), Val, Idx))
2249 return FC; // Fold a few common cases...
2250 // Look up the constant in the table first to ensure uniqueness
2251 std::vector<Constant*> ArgVec(1, Val);
2252 ArgVec.push_back(Idx);
2253 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2255 // Implicitly locked.
2256 return ExprConstants->getOrCreate(ReqTy, Key);
2259 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2260 assert(isa<VectorType>(Val->getType()) &&
2261 "Tried to create extractelement operation on non-vector type!");
2262 assert(Idx->getType() == Type::Int32Ty &&
2263 "Extractelement index must be i32 type!");
2264 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2268 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2269 Constant *Elt, Constant *Idx) {
2270 if (Constant *FC = ConstantFoldInsertElementInstruction(
2271 getGlobalContext(), Val, Elt, Idx))
2272 return FC; // Fold a few common cases...
2273 // Look up the constant in the table first to ensure uniqueness
2274 std::vector<Constant*> ArgVec(1, Val);
2275 ArgVec.push_back(Elt);
2276 ArgVec.push_back(Idx);
2277 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2279 // Implicitly locked.
2280 return ExprConstants->getOrCreate(ReqTy, Key);
2283 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2285 assert(isa<VectorType>(Val->getType()) &&
2286 "Tried to create insertelement operation on non-vector type!");
2287 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2288 && "Insertelement types must match!");
2289 assert(Idx->getType() == Type::Int32Ty &&
2290 "Insertelement index must be i32 type!");
2291 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2294 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2295 Constant *V2, Constant *Mask) {
2296 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2297 getGlobalContext(), V1, V2, Mask))
2298 return FC; // Fold a few common cases...
2299 // Look up the constant in the table first to ensure uniqueness
2300 std::vector<Constant*> ArgVec(1, V1);
2301 ArgVec.push_back(V2);
2302 ArgVec.push_back(Mask);
2303 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2305 // Implicitly locked.
2306 return ExprConstants->getOrCreate(ReqTy, Key);
2309 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2311 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2312 "Invalid shuffle vector constant expr operands!");
2314 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2315 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2316 const Type *ShufTy = VectorType::get(EltTy, NElts);
2317 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2320 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2322 const unsigned *Idxs, unsigned NumIdx) {
2323 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2324 Idxs+NumIdx) == Val->getType() &&
2325 "insertvalue indices invalid!");
2326 assert(Agg->getType() == ReqTy &&
2327 "insertvalue type invalid!");
2328 assert(Agg->getType()->isFirstClassType() &&
2329 "Non-first-class type for constant InsertValue expression");
2330 Constant *FC = ConstantFoldInsertValueInstruction(
2331 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2332 assert(FC && "InsertValue constant expr couldn't be folded!");
2336 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2337 const unsigned *IdxList, unsigned NumIdx) {
2338 assert(Agg->getType()->isFirstClassType() &&
2339 "Tried to create insertelement operation on non-first-class type!");
2341 const Type *ReqTy = Agg->getType();
2344 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2346 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2347 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2350 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2351 const unsigned *Idxs, unsigned NumIdx) {
2352 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2353 Idxs+NumIdx) == ReqTy &&
2354 "extractvalue indices invalid!");
2355 assert(Agg->getType()->isFirstClassType() &&
2356 "Non-first-class type for constant extractvalue expression");
2357 Constant *FC = ConstantFoldExtractValueInstruction(
2358 getGlobalContext(), Agg, Idxs, NumIdx);
2359 assert(FC && "ExtractValue constant expr couldn't be folded!");
2363 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2364 const unsigned *IdxList, unsigned NumIdx) {
2365 assert(Agg->getType()->isFirstClassType() &&
2366 "Tried to create extractelement operation on non-first-class type!");
2369 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2370 assert(ReqTy && "extractvalue indices invalid!");
2371 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2374 // destroyConstant - Remove the constant from the constant table...
2376 void ConstantExpr::destroyConstant() {
2377 // Implicitly locked.
2378 ExprConstants->remove(this);
2379 destroyConstantImpl();
2382 const char *ConstantExpr::getOpcodeName() const {
2383 return Instruction::getOpcodeName(getOpcode());
2386 //===----------------------------------------------------------------------===//
2387 // replaceUsesOfWithOnConstant implementations
2389 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2390 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2393 /// Note that we intentionally replace all uses of From with To here. Consider
2394 /// a large array that uses 'From' 1000 times. By handling this case all here,
2395 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2396 /// single invocation handles all 1000 uses. Handling them one at a time would
2397 /// work, but would be really slow because it would have to unique each updated
2399 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2401 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2402 Constant *ToC = cast<Constant>(To);
2404 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2405 Lookup.first.first = getType();
2406 Lookup.second = this;
2408 std::vector<Constant*> &Values = Lookup.first.second;
2409 Values.reserve(getNumOperands()); // Build replacement array.
2411 // Fill values with the modified operands of the constant array. Also,
2412 // compute whether this turns into an all-zeros array.
2413 bool isAllZeros = false;
2414 unsigned NumUpdated = 0;
2415 if (!ToC->isNullValue()) {
2416 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2417 Constant *Val = cast<Constant>(O->get());
2422 Values.push_back(Val);
2426 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2427 Constant *Val = cast<Constant>(O->get());
2432 Values.push_back(Val);
2433 if (isAllZeros) isAllZeros = Val->isNullValue();
2437 Constant *Replacement = 0;
2439 Replacement = ConstantAggregateZero::get(getType());
2441 // Check to see if we have this array type already.
2442 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2444 ArrayConstantsTy::MapTy::iterator I =
2445 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2448 Replacement = I->second;
2450 // Okay, the new shape doesn't exist in the system yet. Instead of
2451 // creating a new constant array, inserting it, replaceallusesof'ing the
2452 // old with the new, then deleting the old... just update the current one
2454 ArrayConstants->MoveConstantToNewSlot(this, I);
2456 // Update to the new value. Optimize for the case when we have a single
2457 // operand that we're changing, but handle bulk updates efficiently.
2458 if (NumUpdated == 1) {
2459 unsigned OperandToUpdate = U-OperandList;
2460 assert(getOperand(OperandToUpdate) == From &&
2461 "ReplaceAllUsesWith broken!");
2462 setOperand(OperandToUpdate, ToC);
2464 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2465 if (getOperand(i) == From)
2472 // Otherwise, I do need to replace this with an existing value.
2473 assert(Replacement != this && "I didn't contain From!");
2475 // Everyone using this now uses the replacement.
2476 uncheckedReplaceAllUsesWith(Replacement);
2478 // Delete the old constant!
2482 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2484 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2485 Constant *ToC = cast<Constant>(To);
2487 unsigned OperandToUpdate = U-OperandList;
2488 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2490 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2491 Lookup.first.first = getType();
2492 Lookup.second = this;
2493 std::vector<Constant*> &Values = Lookup.first.second;
2494 Values.reserve(getNumOperands()); // Build replacement struct.
2497 // Fill values with the modified operands of the constant struct. Also,
2498 // compute whether this turns into an all-zeros struct.
2499 bool isAllZeros = false;
2500 if (!ToC->isNullValue()) {
2501 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2502 Values.push_back(cast<Constant>(O->get()));
2505 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2506 Constant *Val = cast<Constant>(O->get());
2507 Values.push_back(Val);
2508 if (isAllZeros) isAllZeros = Val->isNullValue();
2511 Values[OperandToUpdate] = ToC;
2513 Constant *Replacement = 0;
2515 Replacement = ConstantAggregateZero::get(getType());
2517 // Check to see if we have this array type already.
2518 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2520 StructConstantsTy::MapTy::iterator I =
2521 StructConstants->InsertOrGetItem(Lookup, Exists);
2524 Replacement = I->second;
2526 // Okay, the new shape doesn't exist in the system yet. Instead of
2527 // creating a new constant struct, inserting it, replaceallusesof'ing the
2528 // old with the new, then deleting the old... just update the current one
2530 StructConstants->MoveConstantToNewSlot(this, I);
2532 // Update to the new value.
2533 setOperand(OperandToUpdate, ToC);
2538 assert(Replacement != this && "I didn't contain From!");
2540 // Everyone using this now uses the replacement.
2541 uncheckedReplaceAllUsesWith(Replacement);
2543 // Delete the old constant!
2547 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2549 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2551 std::vector<Constant*> Values;
2552 Values.reserve(getNumOperands()); // Build replacement array...
2553 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2554 Constant *Val = getOperand(i);
2555 if (Val == From) Val = cast<Constant>(To);
2556 Values.push_back(Val);
2559 Constant *Replacement = ConstantVector::get(getType(), Values);
2560 assert(Replacement != this && "I didn't contain From!");
2562 // Everyone using this now uses the replacement.
2563 uncheckedReplaceAllUsesWith(Replacement);
2565 // Delete the old constant!
2569 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2571 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2572 Constant *To = cast<Constant>(ToV);
2574 Constant *Replacement = 0;
2575 if (getOpcode() == Instruction::GetElementPtr) {
2576 SmallVector<Constant*, 8> Indices;
2577 Constant *Pointer = getOperand(0);
2578 Indices.reserve(getNumOperands()-1);
2579 if (Pointer == From) Pointer = To;
2581 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2582 Constant *Val = getOperand(i);
2583 if (Val == From) Val = To;
2584 Indices.push_back(Val);
2586 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2587 &Indices[0], Indices.size());
2588 } else if (getOpcode() == Instruction::ExtractValue) {
2589 Constant *Agg = getOperand(0);
2590 if (Agg == From) Agg = To;
2592 const SmallVector<unsigned, 4> &Indices = getIndices();
2593 Replacement = ConstantExpr::getExtractValue(Agg,
2594 &Indices[0], Indices.size());
2595 } else if (getOpcode() == Instruction::InsertValue) {
2596 Constant *Agg = getOperand(0);
2597 Constant *Val = getOperand(1);
2598 if (Agg == From) Agg = To;
2599 if (Val == From) Val = To;
2601 const SmallVector<unsigned, 4> &Indices = getIndices();
2602 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2603 &Indices[0], Indices.size());
2604 } else if (isCast()) {
2605 assert(getOperand(0) == From && "Cast only has one use!");
2606 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2607 } else if (getOpcode() == Instruction::Select) {
2608 Constant *C1 = getOperand(0);
2609 Constant *C2 = getOperand(1);
2610 Constant *C3 = getOperand(2);
2611 if (C1 == From) C1 = To;
2612 if (C2 == From) C2 = To;
2613 if (C3 == From) C3 = To;
2614 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2615 } else if (getOpcode() == Instruction::ExtractElement) {
2616 Constant *C1 = getOperand(0);
2617 Constant *C2 = getOperand(1);
2618 if (C1 == From) C1 = To;
2619 if (C2 == From) C2 = To;
2620 Replacement = ConstantExpr::getExtractElement(C1, C2);
2621 } else if (getOpcode() == Instruction::InsertElement) {
2622 Constant *C1 = getOperand(0);
2623 Constant *C2 = getOperand(1);
2624 Constant *C3 = getOperand(1);
2625 if (C1 == From) C1 = To;
2626 if (C2 == From) C2 = To;
2627 if (C3 == From) C3 = To;
2628 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2629 } else if (getOpcode() == Instruction::ShuffleVector) {
2630 Constant *C1 = getOperand(0);
2631 Constant *C2 = getOperand(1);
2632 Constant *C3 = getOperand(2);
2633 if (C1 == From) C1 = To;
2634 if (C2 == From) C2 = To;
2635 if (C3 == From) C3 = To;
2636 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2637 } else if (isCompare()) {
2638 Constant *C1 = getOperand(0);
2639 Constant *C2 = getOperand(1);
2640 if (C1 == From) C1 = To;
2641 if (C2 == From) C2 = To;
2642 if (getOpcode() == Instruction::ICmp)
2643 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2645 assert(getOpcode() == Instruction::FCmp);
2646 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2648 } else if (getNumOperands() == 2) {
2649 Constant *C1 = getOperand(0);
2650 Constant *C2 = getOperand(1);
2651 if (C1 == From) C1 = To;
2652 if (C2 == From) C2 = To;
2653 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2655 llvm_unreachable("Unknown ConstantExpr type!");
2659 assert(Replacement != this && "I didn't contain From!");
2661 // Everyone using this now uses the replacement.
2662 uncheckedReplaceAllUsesWith(Replacement);
2664 // Delete the old constant!
2668 void MDNode::replaceElement(Value *From, Value *To) {
2669 SmallVector<Value*, 4> Values;
2670 Values.reserve(getNumElements()); // Build replacement array...
2671 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2672 Value *Val = getElement(i);
2673 if (Val == From) Val = To;
2674 Values.push_back(Val);
2677 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2678 assert(Replacement != this && "I didn't contain From!");
2680 uncheckedReplaceAllUsesWith(Replacement);