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 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
259 if (Ty == Type::FloatTy)
260 return &APFloat::IEEEsingle;
261 if (Ty == Type::DoubleTy)
262 return &APFloat::IEEEdouble;
263 if (Ty == Type::X86_FP80Ty)
264 return &APFloat::x87DoubleExtended;
265 else if (Ty == Type::FP128Ty)
266 return &APFloat::IEEEquad;
268 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
269 return &APFloat::PPCDoubleDouble;
272 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
273 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
274 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
278 bool ConstantFP::isNullValue() const {
279 return Val.isZero() && !Val.isNegative();
282 bool ConstantFP::isExactlyValue(const APFloat& V) const {
283 return Val.bitwiseIsEqual(V);
287 struct DenseMapAPFloatKeyInfo {
290 KeyTy(const APFloat& V) : val(V){}
291 KeyTy(const KeyTy& that) : val(that.val) {}
292 bool operator==(const KeyTy& that) const {
293 return this->val.bitwiseIsEqual(that.val);
295 bool operator!=(const KeyTy& that) const {
296 return !this->operator==(that);
299 static inline KeyTy getEmptyKey() {
300 return KeyTy(APFloat(APFloat::Bogus,1));
302 static inline KeyTy getTombstoneKey() {
303 return KeyTy(APFloat(APFloat::Bogus,2));
305 static unsigned getHashValue(const KeyTy &Key) {
306 return Key.val.getHashValue();
308 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
311 static bool isPod() { return false; }
315 //---- ConstantFP::get() implementation...
317 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
318 DenseMapAPFloatKeyInfo> FPMapTy;
320 static ManagedStatic<FPMapTy> FPConstants;
322 ConstantFP *ConstantFP::get(const APFloat &V) {
323 DenseMapAPFloatKeyInfo::KeyTy Key(V);
325 ConstantsLock->reader_acquire();
326 ConstantFP *&Slot = (*FPConstants)[Key];
327 ConstantsLock->reader_release();
330 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
331 ConstantFP *&NewSlot = (*FPConstants)[Key];
334 if (&V.getSemantics() == &APFloat::IEEEsingle)
336 else if (&V.getSemantics() == &APFloat::IEEEdouble)
338 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
339 Ty = Type::X86_FP80Ty;
340 else if (&V.getSemantics() == &APFloat::IEEEquad)
343 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
344 "Unknown FP format");
345 Ty = Type::PPC_FP128Ty;
347 NewSlot = new ConstantFP(Ty, V);
356 //===----------------------------------------------------------------------===//
357 // ConstantXXX Classes
358 //===----------------------------------------------------------------------===//
361 ConstantArray::ConstantArray(const ArrayType *T,
362 const std::vector<Constant*> &V)
363 : Constant(T, ConstantArrayVal,
364 OperandTraits<ConstantArray>::op_end(this) - V.size(),
366 assert(V.size() == T->getNumElements() &&
367 "Invalid initializer vector for constant array");
368 Use *OL = OperandList;
369 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
372 assert((C->getType() == T->getElementType() ||
374 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
375 "Initializer for array element doesn't match array element type!");
381 ConstantStruct::ConstantStruct(const StructType *T,
382 const std::vector<Constant*> &V)
383 : Constant(T, ConstantStructVal,
384 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
386 assert(V.size() == T->getNumElements() &&
387 "Invalid initializer vector for constant structure");
388 Use *OL = OperandList;
389 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
392 assert((C->getType() == T->getElementType(I-V.begin()) ||
393 ((T->getElementType(I-V.begin())->isAbstract() ||
394 C->getType()->isAbstract()) &&
395 T->getElementType(I-V.begin())->getTypeID() ==
396 C->getType()->getTypeID())) &&
397 "Initializer for struct element doesn't match struct element type!");
403 ConstantVector::ConstantVector(const VectorType *T,
404 const std::vector<Constant*> &V)
405 : Constant(T, ConstantVectorVal,
406 OperandTraits<ConstantVector>::op_end(this) - V.size(),
408 Use *OL = OperandList;
409 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
412 assert((C->getType() == T->getElementType() ||
414 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
415 "Initializer for vector element doesn't match vector element type!");
422 // We declare several classes private to this file, so use an anonymous
426 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
427 /// behind the scenes to implement unary constant exprs.
428 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
429 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
431 // allocate space for exactly one operand
432 void *operator new(size_t s) {
433 return User::operator new(s, 1);
435 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
436 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
439 /// Transparently provide more efficient getOperand methods.
440 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
443 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
444 /// behind the scenes to implement binary constant exprs.
445 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
446 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
448 // allocate space for exactly two operands
449 void *operator new(size_t s) {
450 return User::operator new(s, 2);
452 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
453 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
457 /// Transparently provide more efficient getOperand methods.
458 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
461 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
462 /// behind the scenes to implement select constant exprs.
463 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
464 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
466 // allocate space for exactly three operands
467 void *operator new(size_t s) {
468 return User::operator new(s, 3);
470 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
471 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
476 /// Transparently provide more efficient getOperand methods.
477 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
480 /// ExtractElementConstantExpr - This class is private to
481 /// Constants.cpp, and is used behind the scenes to implement
482 /// extractelement constant exprs.
483 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
484 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
486 // allocate space for exactly two operands
487 void *operator new(size_t s) {
488 return User::operator new(s, 2);
490 ExtractElementConstantExpr(Constant *C1, Constant *C2)
491 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
492 Instruction::ExtractElement, &Op<0>(), 2) {
496 /// Transparently provide more efficient getOperand methods.
497 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
500 /// InsertElementConstantExpr - This class is private to
501 /// Constants.cpp, and is used behind the scenes to implement
502 /// insertelement constant exprs.
503 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
504 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
506 // allocate space for exactly three operands
507 void *operator new(size_t s) {
508 return User::operator new(s, 3);
510 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
511 : ConstantExpr(C1->getType(), Instruction::InsertElement,
517 /// Transparently provide more efficient getOperand methods.
518 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
521 /// ShuffleVectorConstantExpr - This class is private to
522 /// Constants.cpp, and is used behind the scenes to implement
523 /// shufflevector constant exprs.
524 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
525 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
527 // allocate space for exactly three operands
528 void *operator new(size_t s) {
529 return User::operator new(s, 3);
531 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
532 : ConstantExpr(VectorType::get(
533 cast<VectorType>(C1->getType())->getElementType(),
534 cast<VectorType>(C3->getType())->getNumElements()),
535 Instruction::ShuffleVector,
541 /// Transparently provide more efficient getOperand methods.
542 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
545 /// ExtractValueConstantExpr - This class is private to
546 /// Constants.cpp, and is used behind the scenes to implement
547 /// extractvalue constant exprs.
548 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
549 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
551 // allocate space for exactly one operand
552 void *operator new(size_t s) {
553 return User::operator new(s, 1);
555 ExtractValueConstantExpr(Constant *Agg,
556 const SmallVector<unsigned, 4> &IdxList,
558 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
563 /// Indices - These identify which value to extract.
564 const SmallVector<unsigned, 4> Indices;
566 /// Transparently provide more efficient getOperand methods.
567 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
570 /// InsertValueConstantExpr - This class is private to
571 /// Constants.cpp, and is used behind the scenes to implement
572 /// insertvalue constant exprs.
573 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
574 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
576 // allocate space for exactly one operand
577 void *operator new(size_t s) {
578 return User::operator new(s, 2);
580 InsertValueConstantExpr(Constant *Agg, Constant *Val,
581 const SmallVector<unsigned, 4> &IdxList,
583 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
589 /// Indices - These identify the position for the insertion.
590 const SmallVector<unsigned, 4> Indices;
592 /// Transparently provide more efficient getOperand methods.
593 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
597 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
598 /// used behind the scenes to implement getelementpr constant exprs.
599 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
600 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
603 static GetElementPtrConstantExpr *Create(Constant *C,
604 const std::vector<Constant*>&IdxList,
605 const Type *DestTy) {
606 return new(IdxList.size() + 1)
607 GetElementPtrConstantExpr(C, IdxList, DestTy);
609 /// Transparently provide more efficient getOperand methods.
610 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
613 // CompareConstantExpr - This class is private to Constants.cpp, and is used
614 // behind the scenes to implement ICmp and FCmp constant expressions. This is
615 // needed in order to store the predicate value for these instructions.
616 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
617 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
618 // allocate space for exactly two operands
619 void *operator new(size_t s) {
620 return User::operator new(s, 2);
622 unsigned short predicate;
623 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
624 unsigned short pred, Constant* LHS, Constant* RHS)
625 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
629 /// Transparently provide more efficient getOperand methods.
630 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
633 } // end anonymous namespace
636 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
638 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
641 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
643 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
646 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
648 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
651 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
653 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
656 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
658 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
661 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
663 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
666 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
668 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
671 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
673 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
676 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
679 GetElementPtrConstantExpr::GetElementPtrConstantExpr
681 const std::vector<Constant*> &IdxList,
683 : ConstantExpr(DestTy, Instruction::GetElementPtr,
684 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
685 - (IdxList.size()+1),
688 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
689 OperandList[i+1] = IdxList[i];
692 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
696 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
698 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
701 } // End llvm namespace
704 // Utility function for determining if a ConstantExpr is a CastOp or not. This
705 // can't be inline because we don't want to #include Instruction.h into
707 bool ConstantExpr::isCast() const {
708 return Instruction::isCast(getOpcode());
711 bool ConstantExpr::isCompare() const {
712 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
715 bool ConstantExpr::hasIndices() const {
716 return getOpcode() == Instruction::ExtractValue ||
717 getOpcode() == Instruction::InsertValue;
720 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
721 if (const ExtractValueConstantExpr *EVCE =
722 dyn_cast<ExtractValueConstantExpr>(this))
723 return EVCE->Indices;
725 return cast<InsertValueConstantExpr>(this)->Indices;
728 unsigned ConstantExpr::getPredicate() const {
729 assert(getOpcode() == Instruction::FCmp ||
730 getOpcode() == Instruction::ICmp);
731 return ((const CompareConstantExpr*)this)->predicate;
734 /// getWithOperandReplaced - Return a constant expression identical to this
735 /// one, but with the specified operand set to the specified value.
737 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
738 assert(OpNo < getNumOperands() && "Operand num is out of range!");
739 assert(Op->getType() == getOperand(OpNo)->getType() &&
740 "Replacing operand with value of different type!");
741 if (getOperand(OpNo) == Op)
742 return const_cast<ConstantExpr*>(this);
744 Constant *Op0, *Op1, *Op2;
745 switch (getOpcode()) {
746 case Instruction::Trunc:
747 case Instruction::ZExt:
748 case Instruction::SExt:
749 case Instruction::FPTrunc:
750 case Instruction::FPExt:
751 case Instruction::UIToFP:
752 case Instruction::SIToFP:
753 case Instruction::FPToUI:
754 case Instruction::FPToSI:
755 case Instruction::PtrToInt:
756 case Instruction::IntToPtr:
757 case Instruction::BitCast:
758 return ConstantExpr::getCast(getOpcode(), Op, getType());
759 case Instruction::Select:
760 Op0 = (OpNo == 0) ? Op : getOperand(0);
761 Op1 = (OpNo == 1) ? Op : getOperand(1);
762 Op2 = (OpNo == 2) ? Op : getOperand(2);
763 return ConstantExpr::getSelect(Op0, Op1, Op2);
764 case Instruction::InsertElement:
765 Op0 = (OpNo == 0) ? Op : getOperand(0);
766 Op1 = (OpNo == 1) ? Op : getOperand(1);
767 Op2 = (OpNo == 2) ? Op : getOperand(2);
768 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
769 case Instruction::ExtractElement:
770 Op0 = (OpNo == 0) ? Op : getOperand(0);
771 Op1 = (OpNo == 1) ? Op : getOperand(1);
772 return ConstantExpr::getExtractElement(Op0, Op1);
773 case Instruction::ShuffleVector:
774 Op0 = (OpNo == 0) ? Op : getOperand(0);
775 Op1 = (OpNo == 1) ? Op : getOperand(1);
776 Op2 = (OpNo == 2) ? Op : getOperand(2);
777 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
778 case Instruction::GetElementPtr: {
779 SmallVector<Constant*, 8> Ops;
780 Ops.resize(getNumOperands()-1);
781 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
782 Ops[i-1] = getOperand(i);
784 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
786 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
789 assert(getNumOperands() == 2 && "Must be binary operator?");
790 Op0 = (OpNo == 0) ? Op : getOperand(0);
791 Op1 = (OpNo == 1) ? Op : getOperand(1);
792 return ConstantExpr::get(getOpcode(), Op0, Op1);
796 /// getWithOperands - This returns the current constant expression with the
797 /// operands replaced with the specified values. The specified operands must
798 /// match count and type with the existing ones.
799 Constant *ConstantExpr::
800 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
801 assert(NumOps == getNumOperands() && "Operand count mismatch!");
802 bool AnyChange = false;
803 for (unsigned i = 0; i != NumOps; ++i) {
804 assert(Ops[i]->getType() == getOperand(i)->getType() &&
805 "Operand type mismatch!");
806 AnyChange |= Ops[i] != getOperand(i);
808 if (!AnyChange) // No operands changed, return self.
809 return const_cast<ConstantExpr*>(this);
811 switch (getOpcode()) {
812 case Instruction::Trunc:
813 case Instruction::ZExt:
814 case Instruction::SExt:
815 case Instruction::FPTrunc:
816 case Instruction::FPExt:
817 case Instruction::UIToFP:
818 case Instruction::SIToFP:
819 case Instruction::FPToUI:
820 case Instruction::FPToSI:
821 case Instruction::PtrToInt:
822 case Instruction::IntToPtr:
823 case Instruction::BitCast:
824 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
825 case Instruction::Select:
826 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
827 case Instruction::InsertElement:
828 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
829 case Instruction::ExtractElement:
830 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
831 case Instruction::ShuffleVector:
832 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
833 case Instruction::GetElementPtr:
834 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
835 case Instruction::ICmp:
836 case Instruction::FCmp:
837 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
839 assert(getNumOperands() == 2 && "Must be binary operator?");
840 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
845 //===----------------------------------------------------------------------===//
846 // isValueValidForType implementations
848 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
849 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
850 if (Ty == Type::Int1Ty)
851 return Val == 0 || Val == 1;
853 return true; // always true, has to fit in largest type
854 uint64_t Max = (1ll << NumBits) - 1;
858 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
859 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
860 if (Ty == Type::Int1Ty)
861 return Val == 0 || Val == 1 || Val == -1;
863 return true; // always true, has to fit in largest type
864 int64_t Min = -(1ll << (NumBits-1));
865 int64_t Max = (1ll << (NumBits-1)) - 1;
866 return (Val >= Min && Val <= Max);
869 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
870 // convert modifies in place, so make a copy.
871 APFloat Val2 = APFloat(Val);
873 switch (Ty->getTypeID()) {
875 return false; // These can't be represented as floating point!
877 // FIXME rounding mode needs to be more flexible
878 case Type::FloatTyID: {
879 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
881 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
884 case Type::DoubleTyID: {
885 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
886 &Val2.getSemantics() == &APFloat::IEEEdouble)
888 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
891 case Type::X86_FP80TyID:
892 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
893 &Val2.getSemantics() == &APFloat::IEEEdouble ||
894 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
895 case Type::FP128TyID:
896 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
897 &Val2.getSemantics() == &APFloat::IEEEdouble ||
898 &Val2.getSemantics() == &APFloat::IEEEquad;
899 case Type::PPC_FP128TyID:
900 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
901 &Val2.getSemantics() == &APFloat::IEEEdouble ||
902 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
906 //===----------------------------------------------------------------------===//
907 // Factory Function Implementation
910 // The number of operands for each ConstantCreator::create method is
911 // determined by the ConstantTraits template.
912 // ConstantCreator - A class that is used to create constants by
913 // ValueMap*. This class should be partially specialized if there is
914 // something strange that needs to be done to interface to the ctor for the
918 template<class ValType>
919 struct ConstantTraits;
921 template<typename T, typename Alloc>
922 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
923 static unsigned uses(const std::vector<T, Alloc>& v) {
928 template<class ConstantClass, class TypeClass, class ValType>
929 struct VISIBILITY_HIDDEN ConstantCreator {
930 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
931 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
935 template<class ConstantClass, class TypeClass>
936 struct VISIBILITY_HIDDEN ConvertConstantType {
937 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
938 llvm_unreachable("This type cannot be converted!");
942 template<class ValType, class TypeClass, class ConstantClass,
943 bool HasLargeKey = false /*true for arrays and structs*/ >
944 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
946 typedef std::pair<const Type*, ValType> MapKey;
947 typedef std::map<MapKey, Constant *> MapTy;
948 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
949 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
951 /// Map - This is the main map from the element descriptor to the Constants.
952 /// This is the primary way we avoid creating two of the same shape
956 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
957 /// from the constants to their element in Map. This is important for
958 /// removal of constants from the array, which would otherwise have to scan
959 /// through the map with very large keys.
960 InverseMapTy InverseMap;
962 /// AbstractTypeMap - Map for abstract type constants.
964 AbstractTypeMapTy AbstractTypeMap;
966 /// ValueMapLock - Mutex for this map.
967 sys::SmartMutex<true> ValueMapLock;
970 // NOTE: This function is not locked. It is the caller's responsibility
971 // to enforce proper synchronization.
972 typename MapTy::iterator map_end() { return Map.end(); }
974 /// InsertOrGetItem - Return an iterator for the specified element.
975 /// If the element exists in the map, the returned iterator points to the
976 /// entry and Exists=true. If not, the iterator points to the newly
977 /// inserted entry and returns Exists=false. Newly inserted entries have
978 /// I->second == 0, and should be filled in.
979 /// NOTE: This function is not locked. It is the caller's responsibility
980 // to enforce proper synchronization.
981 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
984 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
990 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
992 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
993 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
994 IMI->second->second == CP &&
995 "InverseMap corrupt!");
999 typename MapTy::iterator I =
1000 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1002 if (I == Map.end() || I->second != CP) {
1003 // FIXME: This should not use a linear scan. If this gets to be a
1004 // performance problem, someone should look at this.
1005 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1011 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1012 typename MapTy::iterator I) {
1013 ConstantClass* Result =
1014 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1016 assert(Result->getType() == Ty && "Type specified is not correct!");
1017 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1019 if (HasLargeKey) // Remember the reverse mapping if needed.
1020 InverseMap.insert(std::make_pair(Result, I));
1022 // If the type of the constant is abstract, make sure that an entry
1023 // exists for it in the AbstractTypeMap.
1024 if (Ty->isAbstract()) {
1025 typename AbstractTypeMapTy::iterator TI =
1026 AbstractTypeMap.find(Ty);
1028 if (TI == AbstractTypeMap.end()) {
1029 // Add ourselves to the ATU list of the type.
1030 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1032 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1040 /// getOrCreate - Return the specified constant from the map, creating it if
1042 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1043 sys::SmartScopedLock<true> Lock(ValueMapLock);
1044 MapKey Lookup(Ty, V);
1045 ConstantClass* Result = 0;
1047 typename MapTy::iterator I = Map.find(Lookup);
1048 // Is it in the map?
1050 Result = static_cast<ConstantClass *>(I->second);
1053 // If no preexisting value, create one now...
1054 Result = Create(Ty, V, I);
1060 void remove(ConstantClass *CP) {
1061 sys::SmartScopedLock<true> Lock(ValueMapLock);
1062 typename MapTy::iterator I = FindExistingElement(CP);
1063 assert(I != Map.end() && "Constant not found in constant table!");
1064 assert(I->second == CP && "Didn't find correct element?");
1066 if (HasLargeKey) // Remember the reverse mapping if needed.
1067 InverseMap.erase(CP);
1069 // Now that we found the entry, make sure this isn't the entry that
1070 // the AbstractTypeMap points to.
1071 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1072 if (Ty->isAbstract()) {
1073 assert(AbstractTypeMap.count(Ty) &&
1074 "Abstract type not in AbstractTypeMap?");
1075 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1076 if (ATMEntryIt == I) {
1077 // Yes, we are removing the representative entry for this type.
1078 // See if there are any other entries of the same type.
1079 typename MapTy::iterator TmpIt = ATMEntryIt;
1081 // First check the entry before this one...
1082 if (TmpIt != Map.begin()) {
1084 if (TmpIt->first.first != Ty) // Not the same type, move back...
1088 // If we didn't find the same type, try to move forward...
1089 if (TmpIt == ATMEntryIt) {
1091 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1092 --TmpIt; // No entry afterwards with the same type
1095 // If there is another entry in the map of the same abstract type,
1096 // update the AbstractTypeMap entry now.
1097 if (TmpIt != ATMEntryIt) {
1100 // Otherwise, we are removing the last instance of this type
1101 // from the table. Remove from the ATM, and from user list.
1102 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1103 AbstractTypeMap.erase(Ty);
1112 /// MoveConstantToNewSlot - If we are about to change C to be the element
1113 /// specified by I, update our internal data structures to reflect this
1115 /// NOTE: This function is not locked. It is the responsibility of the
1116 /// caller to enforce proper synchronization if using this method.
1117 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1118 // First, remove the old location of the specified constant in the map.
1119 typename MapTy::iterator OldI = FindExistingElement(C);
1120 assert(OldI != Map.end() && "Constant not found in constant table!");
1121 assert(OldI->second == C && "Didn't find correct element?");
1123 // If this constant is the representative element for its abstract type,
1124 // update the AbstractTypeMap so that the representative element is I.
1125 if (C->getType()->isAbstract()) {
1126 typename AbstractTypeMapTy::iterator ATI =
1127 AbstractTypeMap.find(C->getType());
1128 assert(ATI != AbstractTypeMap.end() &&
1129 "Abstract type not in AbstractTypeMap?");
1130 if (ATI->second == OldI)
1134 // Remove the old entry from the map.
1137 // Update the inverse map so that we know that this constant is now
1138 // located at descriptor I.
1140 assert(I->second == C && "Bad inversemap entry!");
1145 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1146 sys::SmartScopedLock<true> Lock(ValueMapLock);
1147 typename AbstractTypeMapTy::iterator I =
1148 AbstractTypeMap.find(cast<Type>(OldTy));
1150 assert(I != AbstractTypeMap.end() &&
1151 "Abstract type not in AbstractTypeMap?");
1153 // Convert a constant at a time until the last one is gone. The last one
1154 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1155 // eliminated eventually.
1157 ConvertConstantType<ConstantClass,
1158 TypeClass>::convert(
1159 static_cast<ConstantClass *>(I->second->second),
1160 cast<TypeClass>(NewTy));
1162 I = AbstractTypeMap.find(cast<Type>(OldTy));
1163 } while (I != AbstractTypeMap.end());
1166 // If the type became concrete without being refined to any other existing
1167 // type, we just remove ourselves from the ATU list.
1168 void typeBecameConcrete(const DerivedType *AbsTy) {
1169 AbsTy->removeAbstractTypeUser(this);
1173 DOUT << "Constant.cpp: ValueMap\n";
1180 //---- ConstantAggregateZero::get() implementation...
1183 // ConstantAggregateZero does not take extra "value" argument...
1184 template<class ValType>
1185 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1186 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1187 return new ConstantAggregateZero(Ty);
1192 struct ConvertConstantType<ConstantAggregateZero, Type> {
1193 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1194 // Make everyone now use a constant of the new type...
1195 Constant *New = ConstantAggregateZero::get(NewTy);
1196 assert(New != OldC && "Didn't replace constant??");
1197 OldC->uncheckedReplaceAllUsesWith(New);
1198 OldC->destroyConstant(); // This constant is now dead, destroy it.
1203 static ManagedStatic<ValueMap<char, Type,
1204 ConstantAggregateZero> > AggZeroConstants;
1206 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1208 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1209 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1210 "Cannot create an aggregate zero of non-aggregate type!");
1212 // Implicitly locked.
1213 return AggZeroConstants->getOrCreate(Ty, 0);
1216 /// destroyConstant - Remove the constant from the constant table...
1218 void ConstantAggregateZero::destroyConstant() {
1219 // Implicitly locked.
1220 AggZeroConstants->remove(this);
1221 destroyConstantImpl();
1224 //---- ConstantArray::get() implementation...
1228 struct ConvertConstantType<ConstantArray, ArrayType> {
1229 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1230 // Make everyone now use a constant of the new type...
1231 std::vector<Constant*> C;
1232 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1233 C.push_back(cast<Constant>(OldC->getOperand(i)));
1234 Constant *New = ConstantArray::get(NewTy, C);
1235 assert(New != OldC && "Didn't replace constant??");
1236 OldC->uncheckedReplaceAllUsesWith(New);
1237 OldC->destroyConstant(); // This constant is now dead, destroy it.
1242 static std::vector<Constant*> getValType(ConstantArray *CA) {
1243 std::vector<Constant*> Elements;
1244 Elements.reserve(CA->getNumOperands());
1245 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1246 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1250 typedef ValueMap<std::vector<Constant*>, ArrayType,
1251 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1252 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1254 Constant *ConstantArray::get(const ArrayType *Ty,
1255 const std::vector<Constant*> &V) {
1256 // If this is an all-zero array, return a ConstantAggregateZero object
1259 if (!C->isNullValue()) {
1260 // Implicitly locked.
1261 return ArrayConstants->getOrCreate(Ty, V);
1263 for (unsigned i = 1, e = V.size(); i != e; ++i)
1265 // Implicitly locked.
1266 return ArrayConstants->getOrCreate(Ty, V);
1270 return ConstantAggregateZero::get(Ty);
1273 /// destroyConstant - Remove the constant from the constant table...
1275 void ConstantArray::destroyConstant() {
1276 // Implicitly locked.
1277 ArrayConstants->remove(this);
1278 destroyConstantImpl();
1281 /// isString - This method returns true if the array is an array of i8, and
1282 /// if the elements of the array are all ConstantInt's.
1283 bool ConstantArray::isString() const {
1284 // Check the element type for i8...
1285 if (getType()->getElementType() != Type::Int8Ty)
1287 // Check the elements to make sure they are all integers, not constant
1289 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1290 if (!isa<ConstantInt>(getOperand(i)))
1295 /// isCString - This method returns true if the array is a string (see
1296 /// isString) and it ends in a null byte \\0 and does not contains any other
1297 /// null bytes except its terminator.
1298 bool ConstantArray::isCString() const {
1299 // Check the element type for i8...
1300 if (getType()->getElementType() != Type::Int8Ty)
1303 // Last element must be a null.
1304 if (!getOperand(getNumOperands()-1)->isNullValue())
1306 // Other elements must be non-null integers.
1307 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1308 if (!isa<ConstantInt>(getOperand(i)))
1310 if (getOperand(i)->isNullValue())
1317 /// getAsString - If the sub-element type of this array is i8
1318 /// then this method converts the array to an std::string and returns it.
1319 /// Otherwise, it asserts out.
1321 std::string ConstantArray::getAsString() const {
1322 assert(isString() && "Not a string!");
1324 Result.reserve(getNumOperands());
1325 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1326 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1331 //---- ConstantStruct::get() implementation...
1336 struct ConvertConstantType<ConstantStruct, StructType> {
1337 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1338 // Make everyone now use a constant of the new type...
1339 std::vector<Constant*> C;
1340 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1341 C.push_back(cast<Constant>(OldC->getOperand(i)));
1342 Constant *New = ConstantStruct::get(NewTy, C);
1343 assert(New != OldC && "Didn't replace constant??");
1345 OldC->uncheckedReplaceAllUsesWith(New);
1346 OldC->destroyConstant(); // This constant is now dead, destroy it.
1351 typedef ValueMap<std::vector<Constant*>, StructType,
1352 ConstantStruct, true /*largekey*/> StructConstantsTy;
1353 static ManagedStatic<StructConstantsTy> StructConstants;
1355 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1356 std::vector<Constant*> Elements;
1357 Elements.reserve(CS->getNumOperands());
1358 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1359 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1363 Constant *ConstantStruct::get(const StructType *Ty,
1364 const std::vector<Constant*> &V) {
1365 // Create a ConstantAggregateZero value if all elements are zeros...
1366 for (unsigned i = 0, e = V.size(); i != e; ++i)
1367 if (!V[i]->isNullValue())
1368 // Implicitly locked.
1369 return StructConstants->getOrCreate(Ty, V);
1371 return ConstantAggregateZero::get(Ty);
1374 // destroyConstant - Remove the constant from the constant table...
1376 void ConstantStruct::destroyConstant() {
1377 // Implicitly locked.
1378 StructConstants->remove(this);
1379 destroyConstantImpl();
1382 //---- ConstantVector::get() implementation...
1386 struct ConvertConstantType<ConstantVector, VectorType> {
1387 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1388 // Make everyone now use a constant of the new type...
1389 std::vector<Constant*> C;
1390 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1391 C.push_back(cast<Constant>(OldC->getOperand(i)));
1392 Constant *New = ConstantVector::get(NewTy, C);
1393 assert(New != OldC && "Didn't replace constant??");
1394 OldC->uncheckedReplaceAllUsesWith(New);
1395 OldC->destroyConstant(); // This constant is now dead, destroy it.
1400 static std::vector<Constant*> getValType(ConstantVector *CP) {
1401 std::vector<Constant*> Elements;
1402 Elements.reserve(CP->getNumOperands());
1403 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1404 Elements.push_back(CP->getOperand(i));
1408 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1409 ConstantVector> > VectorConstants;
1411 Constant *ConstantVector::get(const VectorType *Ty,
1412 const std::vector<Constant*> &V) {
1413 assert(!V.empty() && "Vectors can't be empty");
1414 // If this is an all-undef or alll-zero vector, return a
1415 // ConstantAggregateZero or UndefValue.
1417 bool isZero = C->isNullValue();
1418 bool isUndef = isa<UndefValue>(C);
1420 if (isZero || isUndef) {
1421 for (unsigned i = 1, e = V.size(); i != e; ++i)
1423 isZero = isUndef = false;
1429 return ConstantAggregateZero::get(Ty);
1431 return UndefValue::get(Ty);
1433 // Implicitly locked.
1434 return VectorConstants->getOrCreate(Ty, V);
1437 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1438 assert(!V.empty() && "Cannot infer type if V is empty");
1439 return get(VectorType::get(V.front()->getType(),V.size()), V);
1442 // destroyConstant - Remove the constant from the constant table...
1444 void ConstantVector::destroyConstant() {
1445 // Implicitly locked.
1446 VectorConstants->remove(this);
1447 destroyConstantImpl();
1450 /// This function will return true iff every element in this vector constant
1451 /// is set to all ones.
1452 /// @returns true iff this constant's emements are all set to all ones.
1453 /// @brief Determine if the value is all ones.
1454 bool ConstantVector::isAllOnesValue() const {
1455 // Check out first element.
1456 const Constant *Elt = getOperand(0);
1457 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1458 if (!CI || !CI->isAllOnesValue()) return false;
1459 // Then make sure all remaining elements point to the same value.
1460 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1461 if (getOperand(I) != Elt) return false;
1466 /// getSplatValue - If this is a splat constant, where all of the
1467 /// elements have the same value, return that value. Otherwise return null.
1468 Constant *ConstantVector::getSplatValue() {
1469 // Check out first element.
1470 Constant *Elt = getOperand(0);
1471 // Then make sure all remaining elements point to the same value.
1472 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1473 if (getOperand(I) != Elt) return 0;
1477 //---- ConstantPointerNull::get() implementation...
1481 // ConstantPointerNull does not take extra "value" argument...
1482 template<class ValType>
1483 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1484 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1485 return new ConstantPointerNull(Ty);
1490 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1491 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1492 // Make everyone now use a constant of the new type...
1493 Constant *New = ConstantPointerNull::get(NewTy);
1494 assert(New != OldC && "Didn't replace constant??");
1495 OldC->uncheckedReplaceAllUsesWith(New);
1496 OldC->destroyConstant(); // This constant is now dead, destroy it.
1501 static ManagedStatic<ValueMap<char, PointerType,
1502 ConstantPointerNull> > NullPtrConstants;
1504 static char getValType(ConstantPointerNull *) {
1509 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1510 // Implicitly locked.
1511 return NullPtrConstants->getOrCreate(Ty, 0);
1514 // destroyConstant - Remove the constant from the constant table...
1516 void ConstantPointerNull::destroyConstant() {
1517 // Implicitly locked.
1518 NullPtrConstants->remove(this);
1519 destroyConstantImpl();
1523 //---- UndefValue::get() implementation...
1527 // UndefValue does not take extra "value" argument...
1528 template<class ValType>
1529 struct ConstantCreator<UndefValue, Type, ValType> {
1530 static UndefValue *create(const Type *Ty, const ValType &V) {
1531 return new UndefValue(Ty);
1536 struct ConvertConstantType<UndefValue, Type> {
1537 static void convert(UndefValue *OldC, const Type *NewTy) {
1538 // Make everyone now use a constant of the new type.
1539 Constant *New = UndefValue::get(NewTy);
1540 assert(New != OldC && "Didn't replace constant??");
1541 OldC->uncheckedReplaceAllUsesWith(New);
1542 OldC->destroyConstant(); // This constant is now dead, destroy it.
1547 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1549 static char getValType(UndefValue *) {
1554 UndefValue *UndefValue::get(const Type *Ty) {
1555 // Implicitly locked.
1556 return UndefValueConstants->getOrCreate(Ty, 0);
1559 // destroyConstant - Remove the constant from the constant table.
1561 void UndefValue::destroyConstant() {
1562 // Implicitly locked.
1563 UndefValueConstants->remove(this);
1564 destroyConstantImpl();
1567 //---- MDString::get() implementation
1570 MDString::MDString(const char *begin, const char *end)
1571 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1572 StrBegin(begin), StrEnd(end) {}
1574 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1576 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1577 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1578 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1580 MDString *&S = Entry.getValue();
1581 if (!S) S = new MDString(Entry.getKeyData(),
1582 Entry.getKeyData() + Entry.getKeyLength());
1587 MDString *MDString::get(const std::string &Str) {
1588 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1589 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1590 Str.data(), Str.data() + Str.size());
1591 MDString *&S = Entry.getValue();
1592 if (!S) S = new MDString(Entry.getKeyData(),
1593 Entry.getKeyData() + Entry.getKeyLength());
1598 void MDString::destroyConstant() {
1599 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1600 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1601 destroyConstantImpl();
1604 //---- MDNode::get() implementation
1607 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1609 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1610 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1611 for (unsigned i = 0; i != NumVals; ++i)
1612 Node.push_back(ElementVH(Vals[i], this));
1615 void MDNode::Profile(FoldingSetNodeID &ID) const {
1616 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1620 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1621 FoldingSetNodeID ID;
1622 for (unsigned i = 0; i != NumVals; ++i)
1623 ID.AddPointer(Vals[i]);
1625 ConstantsLock->reader_acquire();
1627 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1628 ConstantsLock->reader_release();
1631 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1632 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1634 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1635 N = new(0) MDNode(Vals, NumVals);
1636 MDNodeSet->InsertNode(N, InsertPoint);
1642 void MDNode::destroyConstant() {
1643 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1644 MDNodeSet->RemoveNode(this);
1646 destroyConstantImpl();
1649 //---- ConstantExpr::get() implementations...
1654 struct ExprMapKeyType {
1655 typedef SmallVector<unsigned, 4> IndexList;
1657 ExprMapKeyType(unsigned opc,
1658 const std::vector<Constant*> &ops,
1659 unsigned short pred = 0,
1660 const IndexList &inds = IndexList())
1661 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1664 std::vector<Constant*> operands;
1666 bool operator==(const ExprMapKeyType& that) const {
1667 return this->opcode == that.opcode &&
1668 this->predicate == that.predicate &&
1669 this->operands == that.operands &&
1670 this->indices == that.indices;
1672 bool operator<(const ExprMapKeyType & that) const {
1673 return this->opcode < that.opcode ||
1674 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1675 (this->opcode == that.opcode && this->predicate == that.predicate &&
1676 this->operands < that.operands) ||
1677 (this->opcode == that.opcode && this->predicate == that.predicate &&
1678 this->operands == that.operands && this->indices < that.indices);
1681 bool operator!=(const ExprMapKeyType& that) const {
1682 return !(*this == that);
1690 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1691 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1692 unsigned short pred = 0) {
1693 if (Instruction::isCast(V.opcode))
1694 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1695 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1696 V.opcode < Instruction::BinaryOpsEnd))
1697 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1698 if (V.opcode == Instruction::Select)
1699 return new SelectConstantExpr(V.operands[0], V.operands[1],
1701 if (V.opcode == Instruction::ExtractElement)
1702 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1703 if (V.opcode == Instruction::InsertElement)
1704 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1706 if (V.opcode == Instruction::ShuffleVector)
1707 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1709 if (V.opcode == Instruction::InsertValue)
1710 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1712 if (V.opcode == Instruction::ExtractValue)
1713 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1714 if (V.opcode == Instruction::GetElementPtr) {
1715 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1716 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1719 // The compare instructions are weird. We have to encode the predicate
1720 // value and it is combined with the instruction opcode by multiplying
1721 // the opcode by one hundred. We must decode this to get the predicate.
1722 if (V.opcode == Instruction::ICmp)
1723 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1724 V.operands[0], V.operands[1]);
1725 if (V.opcode == Instruction::FCmp)
1726 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1727 V.operands[0], V.operands[1]);
1728 llvm_unreachable("Invalid ConstantExpr!");
1734 struct ConvertConstantType<ConstantExpr, Type> {
1735 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1737 switch (OldC->getOpcode()) {
1738 case Instruction::Trunc:
1739 case Instruction::ZExt:
1740 case Instruction::SExt:
1741 case Instruction::FPTrunc:
1742 case Instruction::FPExt:
1743 case Instruction::UIToFP:
1744 case Instruction::SIToFP:
1745 case Instruction::FPToUI:
1746 case Instruction::FPToSI:
1747 case Instruction::PtrToInt:
1748 case Instruction::IntToPtr:
1749 case Instruction::BitCast:
1750 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1753 case Instruction::Select:
1754 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1755 OldC->getOperand(1),
1756 OldC->getOperand(2));
1759 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1760 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1761 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1762 OldC->getOperand(1));
1764 case Instruction::GetElementPtr:
1765 // Make everyone now use a constant of the new type...
1766 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1767 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1768 &Idx[0], Idx.size());
1772 assert(New != OldC && "Didn't replace constant??");
1773 OldC->uncheckedReplaceAllUsesWith(New);
1774 OldC->destroyConstant(); // This constant is now dead, destroy it.
1777 } // end namespace llvm
1780 static ExprMapKeyType getValType(ConstantExpr *CE) {
1781 std::vector<Constant*> Operands;
1782 Operands.reserve(CE->getNumOperands());
1783 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1784 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1785 return ExprMapKeyType(CE->getOpcode(), Operands,
1786 CE->isCompare() ? CE->getPredicate() : 0,
1788 CE->getIndices() : SmallVector<unsigned, 4>());
1791 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1792 ConstantExpr> > ExprConstants;
1794 /// This is a utility function to handle folding of casts and lookup of the
1795 /// cast in the ExprConstants map. It is used by the various get* methods below.
1796 static inline Constant *getFoldedCast(
1797 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1798 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1799 // Fold a few common cases
1801 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1804 // Look up the constant in the table first to ensure uniqueness
1805 std::vector<Constant*> argVec(1, C);
1806 ExprMapKeyType Key(opc, argVec);
1808 // Implicitly locked.
1809 return ExprConstants->getOrCreate(Ty, Key);
1812 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1813 Instruction::CastOps opc = Instruction::CastOps(oc);
1814 assert(Instruction::isCast(opc) && "opcode out of range");
1815 assert(C && Ty && "Null arguments to getCast");
1816 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1820 llvm_unreachable("Invalid cast opcode");
1822 case Instruction::Trunc: return getTrunc(C, Ty);
1823 case Instruction::ZExt: return getZExt(C, Ty);
1824 case Instruction::SExt: return getSExt(C, Ty);
1825 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1826 case Instruction::FPExt: return getFPExtend(C, Ty);
1827 case Instruction::UIToFP: return getUIToFP(C, Ty);
1828 case Instruction::SIToFP: return getSIToFP(C, Ty);
1829 case Instruction::FPToUI: return getFPToUI(C, Ty);
1830 case Instruction::FPToSI: return getFPToSI(C, Ty);
1831 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1832 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1833 case Instruction::BitCast: return getBitCast(C, Ty);
1838 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1839 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1840 return getCast(Instruction::BitCast, C, Ty);
1841 return getCast(Instruction::ZExt, C, Ty);
1844 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1845 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1846 return getCast(Instruction::BitCast, C, Ty);
1847 return getCast(Instruction::SExt, C, Ty);
1850 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1851 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1852 return getCast(Instruction::BitCast, C, Ty);
1853 return getCast(Instruction::Trunc, C, Ty);
1856 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1857 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1858 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1860 if (Ty->isInteger())
1861 return getCast(Instruction::PtrToInt, S, Ty);
1862 return getCast(Instruction::BitCast, S, Ty);
1865 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1867 assert(C->getType()->isIntOrIntVector() &&
1868 Ty->isIntOrIntVector() && "Invalid cast");
1869 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1870 unsigned DstBits = Ty->getScalarSizeInBits();
1871 Instruction::CastOps opcode =
1872 (SrcBits == DstBits ? Instruction::BitCast :
1873 (SrcBits > DstBits ? Instruction::Trunc :
1874 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1875 return getCast(opcode, C, Ty);
1878 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1879 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1881 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1882 unsigned DstBits = Ty->getScalarSizeInBits();
1883 if (SrcBits == DstBits)
1884 return C; // Avoid a useless cast
1885 Instruction::CastOps opcode =
1886 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1887 return getCast(opcode, C, Ty);
1890 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1892 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1893 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1895 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1896 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1897 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1898 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1899 "SrcTy must be larger than DestTy for Trunc!");
1901 return getFoldedCast(Instruction::Trunc, C, Ty);
1904 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1906 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1907 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1909 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1910 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1911 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1912 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1913 "SrcTy must be smaller than DestTy for SExt!");
1915 return getFoldedCast(Instruction::SExt, C, Ty);
1918 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1920 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1921 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1923 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1924 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1925 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1926 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1927 "SrcTy must be smaller than DestTy for ZExt!");
1929 return getFoldedCast(Instruction::ZExt, C, Ty);
1932 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1934 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1935 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1937 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1938 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1939 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1940 "This is an illegal floating point truncation!");
1941 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1944 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1946 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1947 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1949 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1950 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1951 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1952 "This is an illegal floating point extension!");
1953 return getFoldedCast(Instruction::FPExt, C, Ty);
1956 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1958 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1959 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1961 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1962 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1963 "This is an illegal uint to floating point cast!");
1964 return getFoldedCast(Instruction::UIToFP, C, Ty);
1967 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1969 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1970 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1972 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1973 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1974 "This is an illegal sint to floating point cast!");
1975 return getFoldedCast(Instruction::SIToFP, C, Ty);
1978 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1980 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1981 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1983 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1984 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1985 "This is an illegal floating point to uint cast!");
1986 return getFoldedCast(Instruction::FPToUI, C, Ty);
1989 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1991 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1992 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1994 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1995 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1996 "This is an illegal floating point to sint cast!");
1997 return getFoldedCast(Instruction::FPToSI, C, Ty);
2000 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2001 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2002 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2003 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2006 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2007 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2008 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2009 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2012 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2013 // BitCast implies a no-op cast of type only. No bits change. However, you
2014 // can't cast pointers to anything but pointers.
2016 const Type *SrcTy = C->getType();
2017 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2018 "BitCast cannot cast pointer to non-pointer and vice versa");
2020 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2021 // or nonptr->ptr). For all the other types, the cast is okay if source and
2022 // destination bit widths are identical.
2023 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2024 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2026 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2028 // It is common to ask for a bitcast of a value to its own type, handle this
2030 if (C->getType() == DstTy) return C;
2032 return getFoldedCast(Instruction::BitCast, C, DstTy);
2035 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2036 Constant *C1, Constant *C2) {
2037 // Check the operands for consistency first
2038 assert(Opcode >= Instruction::BinaryOpsBegin &&
2039 Opcode < Instruction::BinaryOpsEnd &&
2040 "Invalid opcode in binary constant expression");
2041 assert(C1->getType() == C2->getType() &&
2042 "Operand types in binary constant expression should match");
2044 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2045 if (Constant *FC = ConstantFoldBinaryInstruction(
2046 getGlobalContext(), Opcode, C1, C2))
2047 return FC; // Fold a few common cases...
2049 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2050 ExprMapKeyType Key(Opcode, argVec);
2052 // Implicitly locked.
2053 return ExprConstants->getOrCreate(ReqTy, Key);
2056 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2057 Constant *C1, Constant *C2) {
2058 switch (predicate) {
2059 default: llvm_unreachable("Invalid CmpInst predicate");
2060 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2061 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2062 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2063 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2064 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2065 case CmpInst::FCMP_TRUE:
2066 return getFCmp(predicate, C1, C2);
2068 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2069 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2070 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2071 case CmpInst::ICMP_SLE:
2072 return getICmp(predicate, C1, C2);
2076 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2077 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2078 if (C1->getType()->isFPOrFPVector()) {
2079 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2080 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2081 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2085 case Instruction::Add:
2086 case Instruction::Sub:
2087 case Instruction::Mul:
2088 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2089 assert(C1->getType()->isIntOrIntVector() &&
2090 "Tried to create an integer operation on a non-integer type!");
2092 case Instruction::FAdd:
2093 case Instruction::FSub:
2094 case Instruction::FMul:
2095 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2096 assert(C1->getType()->isFPOrFPVector() &&
2097 "Tried to create a floating-point operation on a "
2098 "non-floating-point type!");
2100 case Instruction::UDiv:
2101 case Instruction::SDiv:
2102 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2103 assert(C1->getType()->isIntOrIntVector() &&
2104 "Tried to create an arithmetic operation on a non-arithmetic type!");
2106 case Instruction::FDiv:
2107 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2108 assert(C1->getType()->isFPOrFPVector() &&
2109 "Tried to create an arithmetic operation on a non-arithmetic type!");
2111 case Instruction::URem:
2112 case Instruction::SRem:
2113 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2114 assert(C1->getType()->isIntOrIntVector() &&
2115 "Tried to create an arithmetic operation on a non-arithmetic type!");
2117 case Instruction::FRem:
2118 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2119 assert(C1->getType()->isFPOrFPVector() &&
2120 "Tried to create an arithmetic operation on a non-arithmetic type!");
2122 case Instruction::And:
2123 case Instruction::Or:
2124 case Instruction::Xor:
2125 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2126 assert(C1->getType()->isIntOrIntVector() &&
2127 "Tried to create a logical operation on a non-integral type!");
2129 case Instruction::Shl:
2130 case Instruction::LShr:
2131 case Instruction::AShr:
2132 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2133 assert(C1->getType()->isIntOrIntVector() &&
2134 "Tried to create a shift operation on a non-integer type!");
2141 return getTy(C1->getType(), Opcode, C1, C2);
2144 Constant *ConstantExpr::getCompare(unsigned short pred,
2145 Constant *C1, Constant *C2) {
2146 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2147 return getCompareTy(pred, C1, C2);
2150 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2151 Constant *V1, Constant *V2) {
2152 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2154 if (ReqTy == V1->getType())
2155 if (Constant *SC = ConstantFoldSelectInstruction(
2156 getGlobalContext(), C, V1, V2))
2157 return SC; // Fold common cases
2159 std::vector<Constant*> argVec(3, C);
2162 ExprMapKeyType Key(Instruction::Select, argVec);
2164 // Implicitly locked.
2165 return ExprConstants->getOrCreate(ReqTy, Key);
2168 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2171 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2173 cast<PointerType>(ReqTy)->getElementType() &&
2174 "GEP indices invalid!");
2176 if (Constant *FC = ConstantFoldGetElementPtr(
2177 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
2178 return FC; // Fold a few common cases...
2180 assert(isa<PointerType>(C->getType()) &&
2181 "Non-pointer type for constant GetElementPtr expression");
2182 // Look up the constant in the table first to ensure uniqueness
2183 std::vector<Constant*> ArgVec;
2184 ArgVec.reserve(NumIdx+1);
2185 ArgVec.push_back(C);
2186 for (unsigned i = 0; i != NumIdx; ++i)
2187 ArgVec.push_back(cast<Constant>(Idxs[i]));
2188 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2190 // Implicitly locked.
2191 return ExprConstants->getOrCreate(ReqTy, Key);
2194 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2196 // Get the result type of the getelementptr!
2198 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2199 assert(Ty && "GEP indices invalid!");
2200 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2201 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2204 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2206 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2211 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2212 assert(LHS->getType() == RHS->getType());
2213 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2214 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2216 if (Constant *FC = ConstantFoldCompareInstruction(
2217 getGlobalContext(),pred, LHS, RHS))
2218 return FC; // Fold a few common cases...
2220 // Look up the constant in the table first to ensure uniqueness
2221 std::vector<Constant*> ArgVec;
2222 ArgVec.push_back(LHS);
2223 ArgVec.push_back(RHS);
2224 // Get the key type with both the opcode and predicate
2225 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2227 // Implicitly locked.
2228 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2232 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2233 assert(LHS->getType() == RHS->getType());
2234 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2236 if (Constant *FC = ConstantFoldCompareInstruction(
2237 getGlobalContext(), pred, LHS, RHS))
2238 return FC; // Fold a few common cases...
2240 // Look up the constant in the table first to ensure uniqueness
2241 std::vector<Constant*> ArgVec;
2242 ArgVec.push_back(LHS);
2243 ArgVec.push_back(RHS);
2244 // Get the key type with both the opcode and predicate
2245 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2247 // Implicitly locked.
2248 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2251 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2253 if (Constant *FC = ConstantFoldExtractElementInstruction(
2254 getGlobalContext(), Val, Idx))
2255 return FC; // Fold a few common cases...
2256 // Look up the constant in the table first to ensure uniqueness
2257 std::vector<Constant*> ArgVec(1, Val);
2258 ArgVec.push_back(Idx);
2259 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2261 // Implicitly locked.
2262 return ExprConstants->getOrCreate(ReqTy, Key);
2265 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2266 assert(isa<VectorType>(Val->getType()) &&
2267 "Tried to create extractelement operation on non-vector type!");
2268 assert(Idx->getType() == Type::Int32Ty &&
2269 "Extractelement index must be i32 type!");
2270 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2274 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2275 Constant *Elt, Constant *Idx) {
2276 if (Constant *FC = ConstantFoldInsertElementInstruction(
2277 getGlobalContext(), Val, Elt, Idx))
2278 return FC; // Fold a few common cases...
2279 // Look up the constant in the table first to ensure uniqueness
2280 std::vector<Constant*> ArgVec(1, Val);
2281 ArgVec.push_back(Elt);
2282 ArgVec.push_back(Idx);
2283 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2285 // Implicitly locked.
2286 return ExprConstants->getOrCreate(ReqTy, Key);
2289 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2291 assert(isa<VectorType>(Val->getType()) &&
2292 "Tried to create insertelement operation on non-vector type!");
2293 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2294 && "Insertelement types must match!");
2295 assert(Idx->getType() == Type::Int32Ty &&
2296 "Insertelement index must be i32 type!");
2297 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2300 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2301 Constant *V2, Constant *Mask) {
2302 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2303 getGlobalContext(), V1, V2, Mask))
2304 return FC; // Fold a few common cases...
2305 // Look up the constant in the table first to ensure uniqueness
2306 std::vector<Constant*> ArgVec(1, V1);
2307 ArgVec.push_back(V2);
2308 ArgVec.push_back(Mask);
2309 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2311 // Implicitly locked.
2312 return ExprConstants->getOrCreate(ReqTy, Key);
2315 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2317 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2318 "Invalid shuffle vector constant expr operands!");
2320 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2321 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2322 const Type *ShufTy = VectorType::get(EltTy, NElts);
2323 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2326 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2328 const unsigned *Idxs, unsigned NumIdx) {
2329 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2330 Idxs+NumIdx) == Val->getType() &&
2331 "insertvalue indices invalid!");
2332 assert(Agg->getType() == ReqTy &&
2333 "insertvalue type invalid!");
2334 assert(Agg->getType()->isFirstClassType() &&
2335 "Non-first-class type for constant InsertValue expression");
2336 Constant *FC = ConstantFoldInsertValueInstruction(
2337 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2338 assert(FC && "InsertValue constant expr couldn't be folded!");
2342 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2343 const unsigned *IdxList, unsigned NumIdx) {
2344 assert(Agg->getType()->isFirstClassType() &&
2345 "Tried to create insertelement operation on non-first-class type!");
2347 const Type *ReqTy = Agg->getType();
2350 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2352 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2353 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2356 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2357 const unsigned *Idxs, unsigned NumIdx) {
2358 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2359 Idxs+NumIdx) == ReqTy &&
2360 "extractvalue indices invalid!");
2361 assert(Agg->getType()->isFirstClassType() &&
2362 "Non-first-class type for constant extractvalue expression");
2363 Constant *FC = ConstantFoldExtractValueInstruction(
2364 getGlobalContext(), Agg, Idxs, NumIdx);
2365 assert(FC && "ExtractValue constant expr couldn't be folded!");
2369 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2370 const unsigned *IdxList, unsigned NumIdx) {
2371 assert(Agg->getType()->isFirstClassType() &&
2372 "Tried to create extractelement operation on non-first-class type!");
2375 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2376 assert(ReqTy && "extractvalue indices invalid!");
2377 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2380 // destroyConstant - Remove the constant from the constant table...
2382 void ConstantExpr::destroyConstant() {
2383 // Implicitly locked.
2384 ExprConstants->remove(this);
2385 destroyConstantImpl();
2388 const char *ConstantExpr::getOpcodeName() const {
2389 return Instruction::getOpcodeName(getOpcode());
2392 //===----------------------------------------------------------------------===//
2393 // replaceUsesOfWithOnConstant implementations
2395 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2396 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2399 /// Note that we intentionally replace all uses of From with To here. Consider
2400 /// a large array that uses 'From' 1000 times. By handling this case all here,
2401 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2402 /// single invocation handles all 1000 uses. Handling them one at a time would
2403 /// work, but would be really slow because it would have to unique each updated
2405 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2407 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2408 Constant *ToC = cast<Constant>(To);
2410 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2411 Lookup.first.first = getType();
2412 Lookup.second = this;
2414 std::vector<Constant*> &Values = Lookup.first.second;
2415 Values.reserve(getNumOperands()); // Build replacement array.
2417 // Fill values with the modified operands of the constant array. Also,
2418 // compute whether this turns into an all-zeros array.
2419 bool isAllZeros = false;
2420 unsigned NumUpdated = 0;
2421 if (!ToC->isNullValue()) {
2422 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2423 Constant *Val = cast<Constant>(O->get());
2428 Values.push_back(Val);
2432 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2433 Constant *Val = cast<Constant>(O->get());
2438 Values.push_back(Val);
2439 if (isAllZeros) isAllZeros = Val->isNullValue();
2443 Constant *Replacement = 0;
2445 Replacement = ConstantAggregateZero::get(getType());
2447 // Check to see if we have this array type already.
2448 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2450 ArrayConstantsTy::MapTy::iterator I =
2451 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2454 Replacement = I->second;
2456 // Okay, the new shape doesn't exist in the system yet. Instead of
2457 // creating a new constant array, inserting it, replaceallusesof'ing the
2458 // old with the new, then deleting the old... just update the current one
2460 ArrayConstants->MoveConstantToNewSlot(this, I);
2462 // Update to the new value. Optimize for the case when we have a single
2463 // operand that we're changing, but handle bulk updates efficiently.
2464 if (NumUpdated == 1) {
2465 unsigned OperandToUpdate = U-OperandList;
2466 assert(getOperand(OperandToUpdate) == From &&
2467 "ReplaceAllUsesWith broken!");
2468 setOperand(OperandToUpdate, ToC);
2470 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2471 if (getOperand(i) == From)
2478 // Otherwise, I do need to replace this with an existing value.
2479 assert(Replacement != this && "I didn't contain From!");
2481 // Everyone using this now uses the replacement.
2482 uncheckedReplaceAllUsesWith(Replacement);
2484 // Delete the old constant!
2488 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2490 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2491 Constant *ToC = cast<Constant>(To);
2493 unsigned OperandToUpdate = U-OperandList;
2494 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2496 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2497 Lookup.first.first = getType();
2498 Lookup.second = this;
2499 std::vector<Constant*> &Values = Lookup.first.second;
2500 Values.reserve(getNumOperands()); // Build replacement struct.
2503 // Fill values with the modified operands of the constant struct. Also,
2504 // compute whether this turns into an all-zeros struct.
2505 bool isAllZeros = false;
2506 if (!ToC->isNullValue()) {
2507 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2508 Values.push_back(cast<Constant>(O->get()));
2511 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2512 Constant *Val = cast<Constant>(O->get());
2513 Values.push_back(Val);
2514 if (isAllZeros) isAllZeros = Val->isNullValue();
2517 Values[OperandToUpdate] = ToC;
2519 Constant *Replacement = 0;
2521 Replacement = ConstantAggregateZero::get(getType());
2523 // Check to see if we have this array type already.
2524 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2526 StructConstantsTy::MapTy::iterator I =
2527 StructConstants->InsertOrGetItem(Lookup, Exists);
2530 Replacement = I->second;
2532 // Okay, the new shape doesn't exist in the system yet. Instead of
2533 // creating a new constant struct, inserting it, replaceallusesof'ing the
2534 // old with the new, then deleting the old... just update the current one
2536 StructConstants->MoveConstantToNewSlot(this, I);
2538 // Update to the new value.
2539 setOperand(OperandToUpdate, ToC);
2544 assert(Replacement != this && "I didn't contain From!");
2546 // Everyone using this now uses the replacement.
2547 uncheckedReplaceAllUsesWith(Replacement);
2549 // Delete the old constant!
2553 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2555 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2557 std::vector<Constant*> Values;
2558 Values.reserve(getNumOperands()); // Build replacement array...
2559 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2560 Constant *Val = getOperand(i);
2561 if (Val == From) Val = cast<Constant>(To);
2562 Values.push_back(Val);
2565 Constant *Replacement = ConstantVector::get(getType(), Values);
2566 assert(Replacement != this && "I didn't contain From!");
2568 // Everyone using this now uses the replacement.
2569 uncheckedReplaceAllUsesWith(Replacement);
2571 // Delete the old constant!
2575 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2577 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2578 Constant *To = cast<Constant>(ToV);
2580 Constant *Replacement = 0;
2581 if (getOpcode() == Instruction::GetElementPtr) {
2582 SmallVector<Constant*, 8> Indices;
2583 Constant *Pointer = getOperand(0);
2584 Indices.reserve(getNumOperands()-1);
2585 if (Pointer == From) Pointer = To;
2587 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2588 Constant *Val = getOperand(i);
2589 if (Val == From) Val = To;
2590 Indices.push_back(Val);
2592 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2593 &Indices[0], Indices.size());
2594 } else if (getOpcode() == Instruction::ExtractValue) {
2595 Constant *Agg = getOperand(0);
2596 if (Agg == From) Agg = To;
2598 const SmallVector<unsigned, 4> &Indices = getIndices();
2599 Replacement = ConstantExpr::getExtractValue(Agg,
2600 &Indices[0], Indices.size());
2601 } else if (getOpcode() == Instruction::InsertValue) {
2602 Constant *Agg = getOperand(0);
2603 Constant *Val = getOperand(1);
2604 if (Agg == From) Agg = To;
2605 if (Val == From) Val = To;
2607 const SmallVector<unsigned, 4> &Indices = getIndices();
2608 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2609 &Indices[0], Indices.size());
2610 } else if (isCast()) {
2611 assert(getOperand(0) == From && "Cast only has one use!");
2612 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2613 } else if (getOpcode() == Instruction::Select) {
2614 Constant *C1 = getOperand(0);
2615 Constant *C2 = getOperand(1);
2616 Constant *C3 = getOperand(2);
2617 if (C1 == From) C1 = To;
2618 if (C2 == From) C2 = To;
2619 if (C3 == From) C3 = To;
2620 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2621 } else if (getOpcode() == Instruction::ExtractElement) {
2622 Constant *C1 = getOperand(0);
2623 Constant *C2 = getOperand(1);
2624 if (C1 == From) C1 = To;
2625 if (C2 == From) C2 = To;
2626 Replacement = ConstantExpr::getExtractElement(C1, C2);
2627 } else if (getOpcode() == Instruction::InsertElement) {
2628 Constant *C1 = getOperand(0);
2629 Constant *C2 = getOperand(1);
2630 Constant *C3 = getOperand(1);
2631 if (C1 == From) C1 = To;
2632 if (C2 == From) C2 = To;
2633 if (C3 == From) C3 = To;
2634 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2635 } else if (getOpcode() == Instruction::ShuffleVector) {
2636 Constant *C1 = getOperand(0);
2637 Constant *C2 = getOperand(1);
2638 Constant *C3 = getOperand(2);
2639 if (C1 == From) C1 = To;
2640 if (C2 == From) C2 = To;
2641 if (C3 == From) C3 = To;
2642 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2643 } else if (isCompare()) {
2644 Constant *C1 = getOperand(0);
2645 Constant *C2 = getOperand(1);
2646 if (C1 == From) C1 = To;
2647 if (C2 == From) C2 = To;
2648 if (getOpcode() == Instruction::ICmp)
2649 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2651 assert(getOpcode() == Instruction::FCmp);
2652 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2654 } else if (getNumOperands() == 2) {
2655 Constant *C1 = getOperand(0);
2656 Constant *C2 = getOperand(1);
2657 if (C1 == From) C1 = To;
2658 if (C2 == From) C2 = To;
2659 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2661 llvm_unreachable("Unknown ConstantExpr type!");
2665 assert(Replacement != this && "I didn't contain From!");
2667 // Everyone using this now uses the replacement.
2668 uncheckedReplaceAllUsesWith(Replacement);
2670 // Delete the old constant!
2674 void MDNode::replaceElement(Value *From, Value *To) {
2675 SmallVector<Value*, 4> Values;
2676 Values.reserve(getNumElements()); // Build replacement array...
2677 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2678 Value *Val = getElement(i);
2679 if (Val == From) Val = To;
2680 Values.push_back(Val);
2683 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2684 assert(Replacement != this && "I didn't contain From!");
2686 uncheckedReplaceAllUsesWith(Replacement);