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/ManagedStatic.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/Threading.h"
29 #include "llvm/System/RWMutex.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallVector.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 ManagedStatic<sys::RWMutex> ConstantsLock;
42 void Constant::destroyConstantImpl() {
43 // When a Constant is destroyed, there may be lingering
44 // references to the constant by other constants in the constant pool. These
45 // constants are implicitly dependent on the module that is being deleted,
46 // but they don't know that. Because we only find out when the CPV is
47 // deleted, we must now notify all of our users (that should only be
48 // Constants) that they are, in fact, invalid now and should be deleted.
50 while (!use_empty()) {
51 Value *V = use_back();
52 #ifndef NDEBUG // Only in -g mode...
53 if (!isa<Constant>(V))
54 DOUT << "While deleting: " << *this
55 << "\n\nUse still stuck around after Def is destroyed: "
58 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
59 Constant *CV = cast<Constant>(V);
60 CV->destroyConstant();
62 // The constant should remove itself from our use list...
63 assert((use_empty() || use_back() != V) && "Constant not removed!");
66 // Value has no outstanding references it is safe to delete it now...
70 /// canTrap - Return true if evaluation of this constant could trap. This is
71 /// true for things like constant expressions that could divide by zero.
72 bool Constant::canTrap() const {
73 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
74 // The only thing that could possibly trap are constant exprs.
75 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
76 if (!CE) return false;
78 // ConstantExpr traps if any operands can trap.
79 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
80 if (getOperand(i)->canTrap())
83 // Otherwise, only specific operations can trap.
84 switch (CE->getOpcode()) {
87 case Instruction::UDiv:
88 case Instruction::SDiv:
89 case Instruction::FDiv:
90 case Instruction::URem:
91 case Instruction::SRem:
92 case Instruction::FRem:
93 // Div and rem can trap if the RHS is not known to be non-zero.
94 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
100 /// ContainsRelocations - Return true if the constant value contains relocations
101 /// which cannot be resolved at compile time. Kind argument is used to filter
102 /// only 'interesting' sorts of relocations.
103 bool Constant::ContainsRelocations(unsigned Kind) const {
104 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
105 bool isLocal = GV->hasLocalLinkage();
106 if ((Kind & Reloc::Local) && isLocal) {
107 // Global has local linkage and 'local' kind of relocations are
112 if ((Kind & Reloc::Global) && !isLocal) {
113 // Global has non-local linkage and 'global' kind of relocations are
121 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
122 if (getOperand(i)->ContainsRelocations(Kind))
128 // Static constructor to create a '0' constant of arbitrary type...
129 Constant *Constant::getNullValue(const Type *Ty) {
130 static uint64_t zero[2] = {0, 0};
131 switch (Ty->getTypeID()) {
132 case Type::IntegerTyID:
133 return ConstantInt::get(Ty, 0);
134 case Type::FloatTyID:
135 return ConstantFP::get(APFloat(APInt(32, 0)));
136 case Type::DoubleTyID:
137 return ConstantFP::get(APFloat(APInt(64, 0)));
138 case Type::X86_FP80TyID:
139 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
140 case Type::FP128TyID:
141 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
142 case Type::PPC_FP128TyID:
143 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
144 case Type::PointerTyID:
145 return ConstantPointerNull::get(cast<PointerType>(Ty));
146 case Type::StructTyID:
147 case Type::ArrayTyID:
148 case Type::VectorTyID:
149 return ConstantAggregateZero::get(Ty);
151 // Function, Label, or Opaque type?
152 assert(!"Cannot create a null constant of that type!");
157 Constant *Constant::getAllOnesValue(const Type *Ty) {
158 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
159 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
160 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
163 // Static constructor to create an integral constant with all bits set
164 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
165 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
166 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
170 /// @returns the value for a vector integer constant of the given type that
171 /// has all its bits set to true.
172 /// @brief Get the all ones value
173 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
174 std::vector<Constant*> Elts;
175 Elts.resize(Ty->getNumElements(),
176 ConstantInt::getAllOnesValue(Ty->getElementType()));
177 assert(Elts[0] && "Not a vector integer type!");
178 return cast<ConstantVector>(ConstantVector::get(Elts));
182 /// getVectorElements - This method, which is only valid on constant of vector
183 /// type, returns the elements of the vector in the specified smallvector.
184 /// This handles breaking down a vector undef into undef elements, etc. For
185 /// constant exprs and other cases we can't handle, we return an empty vector.
186 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
187 assert(isa<VectorType>(getType()) && "Not a vector constant!");
189 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
190 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
191 Elts.push_back(CV->getOperand(i));
195 const VectorType *VT = cast<VectorType>(getType());
196 if (isa<ConstantAggregateZero>(this)) {
197 Elts.assign(VT->getNumElements(),
198 Constant::getNullValue(VT->getElementType()));
202 if (isa<UndefValue>(this)) {
203 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
207 // Unknown type, must be constant expr etc.
212 //===----------------------------------------------------------------------===//
214 //===----------------------------------------------------------------------===//
216 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
217 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
218 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
221 ConstantInt *ConstantInt::TheTrueVal = 0;
222 ConstantInt *ConstantInt::TheFalseVal = 0;
225 void CleanupTrueFalse(void *) {
226 ConstantInt::ResetTrueFalse();
230 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
232 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
233 assert(TheTrueVal == 0 && TheFalseVal == 0);
234 TheTrueVal = get(Type::Int1Ty, 1);
235 TheFalseVal = get(Type::Int1Ty, 0);
237 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
238 TrueFalseCleanup.Register();
240 return WhichOne ? TheTrueVal : TheFalseVal;
245 struct DenseMapAPIntKeyInfo {
249 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
250 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
251 bool operator==(const KeyTy& that) const {
252 return type == that.type && this->val == that.val;
254 bool operator!=(const KeyTy& that) const {
255 return !this->operator==(that);
258 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
259 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
260 static unsigned getHashValue(const KeyTy &Key) {
261 return DenseMapInfo<void*>::getHashValue(Key.type) ^
262 Key.val.getHashValue();
264 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
267 static bool isPod() { return false; }
272 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
273 DenseMapAPIntKeyInfo> IntMapTy;
274 static ManagedStatic<IntMapTy> IntConstants;
276 ConstantInt *ConstantInt::get(const IntegerType *Ty,
277 uint64_t V, bool isSigned) {
278 return get(APInt(Ty->getBitWidth(), V, isSigned));
281 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
282 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
284 // For vectors, broadcast the value.
285 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
287 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
292 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
293 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
294 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
295 // compare APInt's of different widths, which would violate an APInt class
296 // invariant which generates an assertion.
297 ConstantInt *ConstantInt::get(const APInt& V) {
298 // Get the corresponding integer type for the bit width of the value.
299 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
300 // get an existing value or the insertion position
301 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
303 if (llvm_is_multithreaded()) {
304 ConstantsLock->reader_acquire();
305 ConstantInt *&Slot = (*IntConstants)[Key];
306 ConstantsLock->reader_release();
309 ConstantsLock->writer_acquire();
310 ConstantInt *&Slot = (*IntConstants)[Key];
312 Slot = new ConstantInt(ITy, V);
314 ConstantsLock->writer_release();
319 ConstantInt *&Slot = (*IntConstants)[Key];
320 // if it exists, return it.
323 // otherwise create a new one, insert it, and return it.
324 return Slot = new ConstantInt(ITy, V);
328 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
329 ConstantInt *C = ConstantInt::get(V);
330 assert(C->getType() == Ty->getScalarType() &&
331 "ConstantInt type doesn't match the type implied by its value!");
333 // For vectors, broadcast the value.
334 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
336 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
341 //===----------------------------------------------------------------------===//
343 //===----------------------------------------------------------------------===//
345 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
346 if (Ty == Type::FloatTy)
347 return &APFloat::IEEEsingle;
348 if (Ty == Type::DoubleTy)
349 return &APFloat::IEEEdouble;
350 if (Ty == Type::X86_FP80Ty)
351 return &APFloat::x87DoubleExtended;
352 else if (Ty == Type::FP128Ty)
353 return &APFloat::IEEEquad;
355 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
356 return &APFloat::PPCDoubleDouble;
359 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
360 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
361 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
365 bool ConstantFP::isNullValue() const {
366 return Val.isZero() && !Val.isNegative();
369 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
370 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
372 return ConstantFP::get(apf);
375 bool ConstantFP::isExactlyValue(const APFloat& V) const {
376 return Val.bitwiseIsEqual(V);
380 struct DenseMapAPFloatKeyInfo {
383 KeyTy(const APFloat& V) : val(V){}
384 KeyTy(const KeyTy& that) : val(that.val) {}
385 bool operator==(const KeyTy& that) const {
386 return this->val.bitwiseIsEqual(that.val);
388 bool operator!=(const KeyTy& that) const {
389 return !this->operator==(that);
392 static inline KeyTy getEmptyKey() {
393 return KeyTy(APFloat(APFloat::Bogus,1));
395 static inline KeyTy getTombstoneKey() {
396 return KeyTy(APFloat(APFloat::Bogus,2));
398 static unsigned getHashValue(const KeyTy &Key) {
399 return Key.val.getHashValue();
401 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
404 static bool isPod() { return false; }
408 //---- ConstantFP::get() implementation...
410 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
411 DenseMapAPFloatKeyInfo> FPMapTy;
413 static ManagedStatic<FPMapTy> FPConstants;
415 ConstantFP *ConstantFP::get(const APFloat &V) {
416 DenseMapAPFloatKeyInfo::KeyTy Key(V);
418 if (llvm_is_multithreaded()) {
419 ConstantsLock->reader_acquire();
420 ConstantFP *&Slot = (*FPConstants)[Key];
421 ConstantsLock->reader_release();
424 ConstantsLock->writer_acquire();
425 Slot = (*FPConstants)[Key];
428 if (&V.getSemantics() == &APFloat::IEEEsingle)
430 else if (&V.getSemantics() == &APFloat::IEEEdouble)
432 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
433 Ty = Type::X86_FP80Ty;
434 else if (&V.getSemantics() == &APFloat::IEEEquad)
437 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
438 "Unknown FP format");
439 Ty = Type::PPC_FP128Ty;
442 Slot = new ConstantFP(Ty, V);
444 ConstantsLock->writer_release();
449 ConstantFP *&Slot = (*FPConstants)[Key];
450 if (Slot) return Slot;
453 if (&V.getSemantics() == &APFloat::IEEEsingle)
455 else if (&V.getSemantics() == &APFloat::IEEEdouble)
457 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
458 Ty = Type::X86_FP80Ty;
459 else if (&V.getSemantics() == &APFloat::IEEEquad)
462 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
463 "Unknown FP format");
464 Ty = Type::PPC_FP128Ty;
467 return Slot = new ConstantFP(Ty, V);
471 /// get() - This returns a constant fp for the specified value in the
472 /// specified type. This should only be used for simple constant values like
473 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
474 Constant *ConstantFP::get(const Type *Ty, double V) {
477 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
478 APFloat::rmNearestTiesToEven, &ignored);
479 Constant *C = get(FV);
481 // For vectors, broadcast the value.
482 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
484 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
489 //===----------------------------------------------------------------------===//
490 // ConstantXXX Classes
491 //===----------------------------------------------------------------------===//
494 ConstantArray::ConstantArray(const ArrayType *T,
495 const std::vector<Constant*> &V)
496 : Constant(T, ConstantArrayVal,
497 OperandTraits<ConstantArray>::op_end(this) - V.size(),
499 assert(V.size() == T->getNumElements() &&
500 "Invalid initializer vector for constant array");
501 Use *OL = OperandList;
502 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
505 assert((C->getType() == T->getElementType() ||
507 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
508 "Initializer for array element doesn't match array element type!");
514 ConstantStruct::ConstantStruct(const StructType *T,
515 const std::vector<Constant*> &V)
516 : Constant(T, ConstantStructVal,
517 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
519 assert(V.size() == T->getNumElements() &&
520 "Invalid initializer vector for constant structure");
521 Use *OL = OperandList;
522 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
525 assert((C->getType() == T->getElementType(I-V.begin()) ||
526 ((T->getElementType(I-V.begin())->isAbstract() ||
527 C->getType()->isAbstract()) &&
528 T->getElementType(I-V.begin())->getTypeID() ==
529 C->getType()->getTypeID())) &&
530 "Initializer for struct element doesn't match struct element type!");
536 ConstantVector::ConstantVector(const VectorType *T,
537 const std::vector<Constant*> &V)
538 : Constant(T, ConstantVectorVal,
539 OperandTraits<ConstantVector>::op_end(this) - V.size(),
541 Use *OL = OperandList;
542 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
545 assert((C->getType() == T->getElementType() ||
547 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
548 "Initializer for vector element doesn't match vector element type!");
555 // We declare several classes private to this file, so use an anonymous
559 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
560 /// behind the scenes to implement unary constant exprs.
561 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
562 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
564 // allocate space for exactly one operand
565 void *operator new(size_t s) {
566 return User::operator new(s, 1);
568 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
569 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
572 /// Transparently provide more efficient getOperand methods.
573 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
576 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
577 /// behind the scenes to implement binary constant exprs.
578 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
579 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
581 // allocate space for exactly two operands
582 void *operator new(size_t s) {
583 return User::operator new(s, 2);
585 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
586 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
590 /// Transparently provide more efficient getOperand methods.
591 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
594 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
595 /// behind the scenes to implement select constant exprs.
596 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
597 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
599 // allocate space for exactly three operands
600 void *operator new(size_t s) {
601 return User::operator new(s, 3);
603 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
604 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
609 /// Transparently provide more efficient getOperand methods.
610 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
613 /// ExtractElementConstantExpr - This class is private to
614 /// Constants.cpp, and is used behind the scenes to implement
615 /// extractelement constant exprs.
616 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
617 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
619 // allocate space for exactly two operands
620 void *operator new(size_t s) {
621 return User::operator new(s, 2);
623 ExtractElementConstantExpr(Constant *C1, Constant *C2)
624 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
625 Instruction::ExtractElement, &Op<0>(), 2) {
629 /// Transparently provide more efficient getOperand methods.
630 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
633 /// InsertElementConstantExpr - This class is private to
634 /// Constants.cpp, and is used behind the scenes to implement
635 /// insertelement constant exprs.
636 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
637 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
639 // allocate space for exactly three operands
640 void *operator new(size_t s) {
641 return User::operator new(s, 3);
643 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
644 : ConstantExpr(C1->getType(), Instruction::InsertElement,
650 /// Transparently provide more efficient getOperand methods.
651 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
654 /// ShuffleVectorConstantExpr - This class is private to
655 /// Constants.cpp, and is used behind the scenes to implement
656 /// shufflevector constant exprs.
657 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
658 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
660 // allocate space for exactly three operands
661 void *operator new(size_t s) {
662 return User::operator new(s, 3);
664 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
665 : ConstantExpr(VectorType::get(
666 cast<VectorType>(C1->getType())->getElementType(),
667 cast<VectorType>(C3->getType())->getNumElements()),
668 Instruction::ShuffleVector,
674 /// Transparently provide more efficient getOperand methods.
675 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
678 /// ExtractValueConstantExpr - This class is private to
679 /// Constants.cpp, and is used behind the scenes to implement
680 /// extractvalue constant exprs.
681 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
682 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
684 // allocate space for exactly one operand
685 void *operator new(size_t s) {
686 return User::operator new(s, 1);
688 ExtractValueConstantExpr(Constant *Agg,
689 const SmallVector<unsigned, 4> &IdxList,
691 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
696 /// Indices - These identify which value to extract.
697 const SmallVector<unsigned, 4> Indices;
699 /// Transparently provide more efficient getOperand methods.
700 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
703 /// InsertValueConstantExpr - This class is private to
704 /// Constants.cpp, and is used behind the scenes to implement
705 /// insertvalue constant exprs.
706 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
707 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
709 // allocate space for exactly one operand
710 void *operator new(size_t s) {
711 return User::operator new(s, 2);
713 InsertValueConstantExpr(Constant *Agg, Constant *Val,
714 const SmallVector<unsigned, 4> &IdxList,
716 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
722 /// Indices - These identify the position for the insertion.
723 const SmallVector<unsigned, 4> Indices;
725 /// Transparently provide more efficient getOperand methods.
726 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
730 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
731 /// used behind the scenes to implement getelementpr constant exprs.
732 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
733 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
736 static GetElementPtrConstantExpr *Create(Constant *C,
737 const std::vector<Constant*>&IdxList,
738 const Type *DestTy) {
739 return new(IdxList.size() + 1)
740 GetElementPtrConstantExpr(C, IdxList, DestTy);
742 /// Transparently provide more efficient getOperand methods.
743 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
746 // CompareConstantExpr - This class is private to Constants.cpp, and is used
747 // behind the scenes to implement ICmp and FCmp constant expressions. This is
748 // needed in order to store the predicate value for these instructions.
749 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
750 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
751 // allocate space for exactly two operands
752 void *operator new(size_t s) {
753 return User::operator new(s, 2);
755 unsigned short predicate;
756 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
757 unsigned short pred, Constant* LHS, Constant* RHS)
758 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
762 /// Transparently provide more efficient getOperand methods.
763 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
766 } // end anonymous namespace
769 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
771 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
774 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
776 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
779 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
781 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
784 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
786 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
789 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
791 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
794 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
796 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
799 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
801 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
804 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
806 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
809 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
812 GetElementPtrConstantExpr::GetElementPtrConstantExpr
814 const std::vector<Constant*> &IdxList,
816 : ConstantExpr(DestTy, Instruction::GetElementPtr,
817 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
818 - (IdxList.size()+1),
821 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
822 OperandList[i+1] = IdxList[i];
825 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
829 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
831 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
834 } // End llvm namespace
837 // Utility function for determining if a ConstantExpr is a CastOp or not. This
838 // can't be inline because we don't want to #include Instruction.h into
840 bool ConstantExpr::isCast() const {
841 return Instruction::isCast(getOpcode());
844 bool ConstantExpr::isCompare() const {
845 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
846 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
849 bool ConstantExpr::hasIndices() const {
850 return getOpcode() == Instruction::ExtractValue ||
851 getOpcode() == Instruction::InsertValue;
854 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
855 if (const ExtractValueConstantExpr *EVCE =
856 dyn_cast<ExtractValueConstantExpr>(this))
857 return EVCE->Indices;
859 return cast<InsertValueConstantExpr>(this)->Indices;
862 /// ConstantExpr::get* - Return some common constants without having to
863 /// specify the full Instruction::OPCODE identifier.
865 Constant *ConstantExpr::getNeg(Constant *C) {
866 // API compatibility: Adjust integer opcodes to floating-point opcodes.
867 if (C->getType()->isFPOrFPVector())
869 assert(C->getType()->isIntOrIntVector() &&
870 "Cannot NEG a nonintegral value!");
871 return get(Instruction::Sub,
872 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
875 Constant *ConstantExpr::getFNeg(Constant *C) {
876 assert(C->getType()->isFPOrFPVector() &&
877 "Cannot FNEG a non-floating-point value!");
878 return get(Instruction::FSub,
879 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
882 Constant *ConstantExpr::getNot(Constant *C) {
883 assert(C->getType()->isIntOrIntVector() &&
884 "Cannot NOT a nonintegral value!");
885 return get(Instruction::Xor, C,
886 Constant::getAllOnesValue(C->getType()));
888 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
889 return get(Instruction::Add, C1, C2);
891 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
892 return get(Instruction::FAdd, C1, C2);
894 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
895 return get(Instruction::Sub, C1, C2);
897 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
898 return get(Instruction::FSub, C1, C2);
900 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
901 return get(Instruction::Mul, C1, C2);
903 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
904 return get(Instruction::FMul, C1, C2);
906 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
907 return get(Instruction::UDiv, C1, C2);
909 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
910 return get(Instruction::SDiv, C1, C2);
912 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
913 return get(Instruction::FDiv, C1, C2);
915 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
916 return get(Instruction::URem, C1, C2);
918 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
919 return get(Instruction::SRem, C1, C2);
921 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
922 return get(Instruction::FRem, C1, C2);
924 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
925 return get(Instruction::And, C1, C2);
927 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
928 return get(Instruction::Or, C1, C2);
930 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
931 return get(Instruction::Xor, C1, C2);
933 unsigned ConstantExpr::getPredicate() const {
934 assert(getOpcode() == Instruction::FCmp ||
935 getOpcode() == Instruction::ICmp ||
936 getOpcode() == Instruction::VFCmp ||
937 getOpcode() == Instruction::VICmp);
938 return ((const CompareConstantExpr*)this)->predicate;
940 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
941 return get(Instruction::Shl, C1, C2);
943 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
944 return get(Instruction::LShr, C1, C2);
946 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
947 return get(Instruction::AShr, C1, C2);
950 /// getWithOperandReplaced - Return a constant expression identical to this
951 /// one, but with the specified operand set to the specified value.
953 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
954 assert(OpNo < getNumOperands() && "Operand num is out of range!");
955 assert(Op->getType() == getOperand(OpNo)->getType() &&
956 "Replacing operand with value of different type!");
957 if (getOperand(OpNo) == Op)
958 return const_cast<ConstantExpr*>(this);
960 Constant *Op0, *Op1, *Op2;
961 switch (getOpcode()) {
962 case Instruction::Trunc:
963 case Instruction::ZExt:
964 case Instruction::SExt:
965 case Instruction::FPTrunc:
966 case Instruction::FPExt:
967 case Instruction::UIToFP:
968 case Instruction::SIToFP:
969 case Instruction::FPToUI:
970 case Instruction::FPToSI:
971 case Instruction::PtrToInt:
972 case Instruction::IntToPtr:
973 case Instruction::BitCast:
974 return ConstantExpr::getCast(getOpcode(), Op, getType());
975 case Instruction::Select:
976 Op0 = (OpNo == 0) ? Op : getOperand(0);
977 Op1 = (OpNo == 1) ? Op : getOperand(1);
978 Op2 = (OpNo == 2) ? Op : getOperand(2);
979 return ConstantExpr::getSelect(Op0, Op1, Op2);
980 case Instruction::InsertElement:
981 Op0 = (OpNo == 0) ? Op : getOperand(0);
982 Op1 = (OpNo == 1) ? Op : getOperand(1);
983 Op2 = (OpNo == 2) ? Op : getOperand(2);
984 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
985 case Instruction::ExtractElement:
986 Op0 = (OpNo == 0) ? Op : getOperand(0);
987 Op1 = (OpNo == 1) ? Op : getOperand(1);
988 return ConstantExpr::getExtractElement(Op0, Op1);
989 case Instruction::ShuffleVector:
990 Op0 = (OpNo == 0) ? Op : getOperand(0);
991 Op1 = (OpNo == 1) ? Op : getOperand(1);
992 Op2 = (OpNo == 2) ? Op : getOperand(2);
993 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
994 case Instruction::GetElementPtr: {
995 SmallVector<Constant*, 8> Ops;
996 Ops.resize(getNumOperands()-1);
997 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
998 Ops[i-1] = getOperand(i);
1000 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
1002 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
1005 assert(getNumOperands() == 2 && "Must be binary operator?");
1006 Op0 = (OpNo == 0) ? Op : getOperand(0);
1007 Op1 = (OpNo == 1) ? Op : getOperand(1);
1008 return ConstantExpr::get(getOpcode(), Op0, Op1);
1012 /// getWithOperands - This returns the current constant expression with the
1013 /// operands replaced with the specified values. The specified operands must
1014 /// match count and type with the existing ones.
1015 Constant *ConstantExpr::
1016 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
1017 assert(NumOps == getNumOperands() && "Operand count mismatch!");
1018 bool AnyChange = false;
1019 for (unsigned i = 0; i != NumOps; ++i) {
1020 assert(Ops[i]->getType() == getOperand(i)->getType() &&
1021 "Operand type mismatch!");
1022 AnyChange |= Ops[i] != getOperand(i);
1024 if (!AnyChange) // No operands changed, return self.
1025 return const_cast<ConstantExpr*>(this);
1027 switch (getOpcode()) {
1028 case Instruction::Trunc:
1029 case Instruction::ZExt:
1030 case Instruction::SExt:
1031 case Instruction::FPTrunc:
1032 case Instruction::FPExt:
1033 case Instruction::UIToFP:
1034 case Instruction::SIToFP:
1035 case Instruction::FPToUI:
1036 case Instruction::FPToSI:
1037 case Instruction::PtrToInt:
1038 case Instruction::IntToPtr:
1039 case Instruction::BitCast:
1040 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
1041 case Instruction::Select:
1042 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1043 case Instruction::InsertElement:
1044 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1045 case Instruction::ExtractElement:
1046 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1047 case Instruction::ShuffleVector:
1048 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1049 case Instruction::GetElementPtr:
1050 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
1051 case Instruction::ICmp:
1052 case Instruction::FCmp:
1053 case Instruction::VICmp:
1054 case Instruction::VFCmp:
1055 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1057 assert(getNumOperands() == 2 && "Must be binary operator?");
1058 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
1063 //===----------------------------------------------------------------------===//
1064 // isValueValidForType implementations
1066 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
1067 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1068 if (Ty == Type::Int1Ty)
1069 return Val == 0 || Val == 1;
1071 return true; // always true, has to fit in largest type
1072 uint64_t Max = (1ll << NumBits) - 1;
1076 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
1077 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1078 if (Ty == Type::Int1Ty)
1079 return Val == 0 || Val == 1 || Val == -1;
1081 return true; // always true, has to fit in largest type
1082 int64_t Min = -(1ll << (NumBits-1));
1083 int64_t Max = (1ll << (NumBits-1)) - 1;
1084 return (Val >= Min && Val <= Max);
1087 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1088 // convert modifies in place, so make a copy.
1089 APFloat Val2 = APFloat(Val);
1091 switch (Ty->getTypeID()) {
1093 return false; // These can't be represented as floating point!
1095 // FIXME rounding mode needs to be more flexible
1096 case Type::FloatTyID: {
1097 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1099 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1102 case Type::DoubleTyID: {
1103 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1104 &Val2.getSemantics() == &APFloat::IEEEdouble)
1106 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1109 case Type::X86_FP80TyID:
1110 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1111 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1112 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1113 case Type::FP128TyID:
1114 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1115 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1116 &Val2.getSemantics() == &APFloat::IEEEquad;
1117 case Type::PPC_FP128TyID:
1118 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1119 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1120 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1124 //===----------------------------------------------------------------------===//
1125 // Factory Function Implementation
1128 // The number of operands for each ConstantCreator::create method is
1129 // determined by the ConstantTraits template.
1130 // ConstantCreator - A class that is used to create constants by
1131 // ValueMap*. This class should be partially specialized if there is
1132 // something strange that needs to be done to interface to the ctor for the
1136 template<class ValType>
1137 struct ConstantTraits;
1139 template<typename T, typename Alloc>
1140 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1141 static unsigned uses(const std::vector<T, Alloc>& v) {
1146 template<class ConstantClass, class TypeClass, class ValType>
1147 struct VISIBILITY_HIDDEN ConstantCreator {
1148 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1149 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1153 template<class ConstantClass, class TypeClass>
1154 struct VISIBILITY_HIDDEN ConvertConstantType {
1155 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1156 assert(0 && "This type cannot be converted!\n");
1161 template<class ValType, class TypeClass, class ConstantClass,
1162 bool HasLargeKey = false /*true for arrays and structs*/ >
1163 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1165 typedef std::pair<const Type*, ValType> MapKey;
1166 typedef std::map<MapKey, Constant *> MapTy;
1167 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1168 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1170 /// Map - This is the main map from the element descriptor to the Constants.
1171 /// This is the primary way we avoid creating two of the same shape
1175 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1176 /// from the constants to their element in Map. This is important for
1177 /// removal of constants from the array, which would otherwise have to scan
1178 /// through the map with very large keys.
1179 InverseMapTy InverseMap;
1181 /// AbstractTypeMap - Map for abstract type constants.
1183 AbstractTypeMapTy AbstractTypeMap;
1186 typename MapTy::iterator map_end() { return Map.end(); }
1188 /// InsertOrGetItem - Return an iterator for the specified element.
1189 /// If the element exists in the map, the returned iterator points to the
1190 /// entry and Exists=true. If not, the iterator points to the newly
1191 /// inserted entry and returns Exists=false. Newly inserted entries have
1192 /// I->second == 0, and should be filled in.
1193 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1196 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1197 Exists = !IP.second;
1202 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1204 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1205 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1206 IMI->second->second == CP &&
1207 "InverseMap corrupt!");
1211 typename MapTy::iterator I =
1212 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1214 if (I == Map.end() || I->second != CP) {
1215 // FIXME: This should not use a linear scan. If this gets to be a
1216 // performance problem, someone should look at this.
1217 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1224 /// getOrCreate - Return the specified constant from the map, creating it if
1226 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1227 MapKey Lookup(Ty, V);
1228 typename MapTy::iterator I = Map.find(Lookup);
1229 // Is it in the map?
1231 return static_cast<ConstantClass *>(I->second);
1233 // If no preexisting value, create one now...
1234 ConstantClass *Result =
1235 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1237 assert(Result->getType() == Ty && "Type specified is not correct!");
1238 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1240 if (HasLargeKey) // Remember the reverse mapping if needed.
1241 InverseMap.insert(std::make_pair(Result, I));
1243 // If the type of the constant is abstract, make sure that an entry exists
1244 // for it in the AbstractTypeMap.
1245 if (Ty->isAbstract()) {
1246 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
1248 if (TI == AbstractTypeMap.end()) {
1249 // Add ourselves to the ATU list of the type.
1250 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1252 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1258 void remove(ConstantClass *CP) {
1259 typename MapTy::iterator I = FindExistingElement(CP);
1260 assert(I != Map.end() && "Constant not found in constant table!");
1261 assert(I->second == CP && "Didn't find correct element?");
1263 if (HasLargeKey) // Remember the reverse mapping if needed.
1264 InverseMap.erase(CP);
1266 // Now that we found the entry, make sure this isn't the entry that
1267 // the AbstractTypeMap points to.
1268 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1269 if (Ty->isAbstract()) {
1270 assert(AbstractTypeMap.count(Ty) &&
1271 "Abstract type not in AbstractTypeMap?");
1272 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1273 if (ATMEntryIt == I) {
1274 // Yes, we are removing the representative entry for this type.
1275 // See if there are any other entries of the same type.
1276 typename MapTy::iterator TmpIt = ATMEntryIt;
1278 // First check the entry before this one...
1279 if (TmpIt != Map.begin()) {
1281 if (TmpIt->first.first != Ty) // Not the same type, move back...
1285 // If we didn't find the same type, try to move forward...
1286 if (TmpIt == ATMEntryIt) {
1288 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1289 --TmpIt; // No entry afterwards with the same type
1292 // If there is another entry in the map of the same abstract type,
1293 // update the AbstractTypeMap entry now.
1294 if (TmpIt != ATMEntryIt) {
1297 // Otherwise, we are removing the last instance of this type
1298 // from the table. Remove from the ATM, and from user list.
1299 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1300 AbstractTypeMap.erase(Ty);
1309 /// MoveConstantToNewSlot - If we are about to change C to be the element
1310 /// specified by I, update our internal data structures to reflect this
1312 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1313 // First, remove the old location of the specified constant in the map.
1314 typename MapTy::iterator OldI = FindExistingElement(C);
1315 assert(OldI != Map.end() && "Constant not found in constant table!");
1316 assert(OldI->second == C && "Didn't find correct element?");
1318 // If this constant is the representative element for its abstract type,
1319 // update the AbstractTypeMap so that the representative element is I.
1320 if (C->getType()->isAbstract()) {
1321 typename AbstractTypeMapTy::iterator ATI =
1322 AbstractTypeMap.find(C->getType());
1323 assert(ATI != AbstractTypeMap.end() &&
1324 "Abstract type not in AbstractTypeMap?");
1325 if (ATI->second == OldI)
1329 // Remove the old entry from the map.
1332 // Update the inverse map so that we know that this constant is now
1333 // located at descriptor I.
1335 assert(I->second == C && "Bad inversemap entry!");
1340 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1341 typename AbstractTypeMapTy::iterator I =
1342 AbstractTypeMap.find(cast<Type>(OldTy));
1344 assert(I != AbstractTypeMap.end() &&
1345 "Abstract type not in AbstractTypeMap?");
1347 // Convert a constant at a time until the last one is gone. The last one
1348 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1349 // eliminated eventually.
1351 ConvertConstantType<ConstantClass,
1352 TypeClass>::convert(
1353 static_cast<ConstantClass *>(I->second->second),
1354 cast<TypeClass>(NewTy));
1356 I = AbstractTypeMap.find(cast<Type>(OldTy));
1357 } while (I != AbstractTypeMap.end());
1360 // If the type became concrete without being refined to any other existing
1361 // type, we just remove ourselves from the ATU list.
1362 void typeBecameConcrete(const DerivedType *AbsTy) {
1363 AbsTy->removeAbstractTypeUser(this);
1367 DOUT << "Constant.cpp: ValueMap\n";
1374 //---- ConstantAggregateZero::get() implementation...
1377 // ConstantAggregateZero does not take extra "value" argument...
1378 template<class ValType>
1379 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1380 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1381 return new ConstantAggregateZero(Ty);
1386 struct ConvertConstantType<ConstantAggregateZero, Type> {
1387 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1388 // Make everyone now use a constant of the new type...
1389 Constant *New = ConstantAggregateZero::get(NewTy);
1390 assert(New != OldC && "Didn't replace constant??");
1391 OldC->uncheckedReplaceAllUsesWith(New);
1392 OldC->destroyConstant(); // This constant is now dead, destroy it.
1397 static ManagedStatic<ValueMap<char, Type,
1398 ConstantAggregateZero> > AggZeroConstants;
1400 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1402 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1403 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1404 "Cannot create an aggregate zero of non-aggregate type!");
1405 ConstantAggregateZero* result = 0;
1406 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1407 result = AggZeroConstants->getOrCreate(Ty, 0);
1408 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1412 /// destroyConstant - Remove the constant from the constant table...
1414 void ConstantAggregateZero::destroyConstant() {
1415 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1416 AggZeroConstants->remove(this);
1417 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1418 destroyConstantImpl();
1421 //---- ConstantArray::get() implementation...
1425 struct ConvertConstantType<ConstantArray, ArrayType> {
1426 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1427 // Make everyone now use a constant of the new type...
1428 std::vector<Constant*> C;
1429 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1430 C.push_back(cast<Constant>(OldC->getOperand(i)));
1431 Constant *New = ConstantArray::get(NewTy, C);
1432 assert(New != OldC && "Didn't replace constant??");
1433 OldC->uncheckedReplaceAllUsesWith(New);
1434 OldC->destroyConstant(); // This constant is now dead, destroy it.
1439 static std::vector<Constant*> getValType(ConstantArray *CA) {
1440 std::vector<Constant*> Elements;
1441 Elements.reserve(CA->getNumOperands());
1442 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1443 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1447 typedef ValueMap<std::vector<Constant*>, ArrayType,
1448 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1449 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1451 Constant *ConstantArray::get(const ArrayType *Ty,
1452 const std::vector<Constant*> &V) {
1453 // If this is an all-zero array, return a ConstantAggregateZero object
1454 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1457 if (!C->isNullValue()) {
1458 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1459 return ArrayConstants->getOrCreate(Ty, V);
1461 for (unsigned i = 1, e = V.size(); i != e; ++i)
1463 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1464 return ArrayConstants->getOrCreate(Ty, V);
1467 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1469 return ConstantAggregateZero::get(Ty);
1472 /// destroyConstant - Remove the constant from the constant table...
1474 void ConstantArray::destroyConstant() {
1475 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1476 ArrayConstants->remove(this);
1477 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1478 destroyConstantImpl();
1481 /// ConstantArray::get(const string&) - Return an array that is initialized to
1482 /// contain the specified string. If length is zero then a null terminator is
1483 /// added to the specified string so that it may be used in a natural way.
1484 /// Otherwise, the length parameter specifies how much of the string to use
1485 /// and it won't be null terminated.
1487 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1488 std::vector<Constant*> ElementVals;
1489 for (unsigned i = 0; i < Str.length(); ++i)
1490 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1492 // Add a null terminator to the string...
1494 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1497 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1498 return ConstantArray::get(ATy, ElementVals);
1501 /// isString - This method returns true if the array is an array of i8, and
1502 /// if the elements of the array are all ConstantInt's.
1503 bool ConstantArray::isString() const {
1504 // Check the element type for i8...
1505 if (getType()->getElementType() != Type::Int8Ty)
1507 // Check the elements to make sure they are all integers, not constant
1509 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1510 if (!isa<ConstantInt>(getOperand(i)))
1515 /// isCString - This method returns true if the array is a string (see
1516 /// isString) and it ends in a null byte \\0 and does not contains any other
1517 /// null bytes except its terminator.
1518 bool ConstantArray::isCString() const {
1519 // Check the element type for i8...
1520 if (getType()->getElementType() != Type::Int8Ty)
1522 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1523 // Last element must be a null.
1524 if (getOperand(getNumOperands()-1) != Zero)
1526 // Other elements must be non-null integers.
1527 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1528 if (!isa<ConstantInt>(getOperand(i)))
1530 if (getOperand(i) == Zero)
1537 /// getAsString - If the sub-element type of this array is i8
1538 /// then this method converts the array to an std::string and returns it.
1539 /// Otherwise, it asserts out.
1541 std::string ConstantArray::getAsString() const {
1542 assert(isString() && "Not a string!");
1544 Result.reserve(getNumOperands());
1545 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1546 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1551 //---- ConstantStruct::get() implementation...
1556 struct ConvertConstantType<ConstantStruct, StructType> {
1557 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1558 // Make everyone now use a constant of the new type...
1559 std::vector<Constant*> C;
1560 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1561 C.push_back(cast<Constant>(OldC->getOperand(i)));
1562 Constant *New = ConstantStruct::get(NewTy, C);
1563 assert(New != OldC && "Didn't replace constant??");
1565 OldC->uncheckedReplaceAllUsesWith(New);
1566 OldC->destroyConstant(); // This constant is now dead, destroy it.
1571 typedef ValueMap<std::vector<Constant*>, StructType,
1572 ConstantStruct, true /*largekey*/> StructConstantsTy;
1573 static ManagedStatic<StructConstantsTy> StructConstants;
1575 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1576 std::vector<Constant*> Elements;
1577 Elements.reserve(CS->getNumOperands());
1578 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1579 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1583 Constant *ConstantStruct::get(const StructType *Ty,
1584 const std::vector<Constant*> &V) {
1585 // Create a ConstantAggregateZero value if all elements are zeros...
1586 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1587 for (unsigned i = 0, e = V.size(); i != e; ++i)
1588 if (!V[i]->isNullValue()) {
1589 Constant* result = StructConstants->getOrCreate(Ty, V);
1590 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1593 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1595 return ConstantAggregateZero::get(Ty);
1598 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1599 std::vector<const Type*> StructEls;
1600 StructEls.reserve(V.size());
1601 for (unsigned i = 0, e = V.size(); i != e; ++i)
1602 StructEls.push_back(V[i]->getType());
1603 return get(StructType::get(StructEls, packed), V);
1606 // destroyConstant - Remove the constant from the constant table...
1608 void ConstantStruct::destroyConstant() {
1609 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1610 StructConstants->remove(this);
1611 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1612 destroyConstantImpl();
1615 //---- ConstantVector::get() implementation...
1619 struct ConvertConstantType<ConstantVector, VectorType> {
1620 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1621 // Make everyone now use a constant of the new type...
1622 std::vector<Constant*> C;
1623 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1624 C.push_back(cast<Constant>(OldC->getOperand(i)));
1625 Constant *New = ConstantVector::get(NewTy, C);
1626 assert(New != OldC && "Didn't replace constant??");
1627 OldC->uncheckedReplaceAllUsesWith(New);
1628 OldC->destroyConstant(); // This constant is now dead, destroy it.
1633 static std::vector<Constant*> getValType(ConstantVector *CP) {
1634 std::vector<Constant*> Elements;
1635 Elements.reserve(CP->getNumOperands());
1636 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1637 Elements.push_back(CP->getOperand(i));
1641 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1642 ConstantVector> > VectorConstants;
1644 Constant *ConstantVector::get(const VectorType *Ty,
1645 const std::vector<Constant*> &V) {
1646 assert(!V.empty() && "Vectors can't be empty");
1647 // If this is an all-undef or alll-zero vector, return a
1648 // ConstantAggregateZero or UndefValue.
1650 bool isZero = C->isNullValue();
1651 bool isUndef = isa<UndefValue>(C);
1653 if (isZero || isUndef) {
1654 for (unsigned i = 1, e = V.size(); i != e; ++i)
1656 isZero = isUndef = false;
1662 return ConstantAggregateZero::get(Ty);
1664 return UndefValue::get(Ty);
1665 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1666 Constant* result = VectorConstants->getOrCreate(Ty, V);
1667 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1671 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1672 assert(!V.empty() && "Cannot infer type if V is empty");
1673 return get(VectorType::get(V.front()->getType(),V.size()), V);
1676 // destroyConstant - Remove the constant from the constant table...
1678 void ConstantVector::destroyConstant() {
1679 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1680 VectorConstants->remove(this);
1681 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1682 destroyConstantImpl();
1685 /// This function will return true iff every element in this vector constant
1686 /// is set to all ones.
1687 /// @returns true iff this constant's emements are all set to all ones.
1688 /// @brief Determine if the value is all ones.
1689 bool ConstantVector::isAllOnesValue() const {
1690 // Check out first element.
1691 const Constant *Elt = getOperand(0);
1692 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1693 if (!CI || !CI->isAllOnesValue()) return false;
1694 // Then make sure all remaining elements point to the same value.
1695 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1696 if (getOperand(I) != Elt) return false;
1701 /// getSplatValue - If this is a splat constant, where all of the
1702 /// elements have the same value, return that value. Otherwise return null.
1703 Constant *ConstantVector::getSplatValue() {
1704 // Check out first element.
1705 Constant *Elt = getOperand(0);
1706 // Then make sure all remaining elements point to the same value.
1707 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1708 if (getOperand(I) != Elt) return 0;
1712 //---- ConstantPointerNull::get() implementation...
1716 // ConstantPointerNull does not take extra "value" argument...
1717 template<class ValType>
1718 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1719 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1720 return new ConstantPointerNull(Ty);
1725 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1726 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1727 // Make everyone now use a constant of the new type...
1728 Constant *New = ConstantPointerNull::get(NewTy);
1729 assert(New != OldC && "Didn't replace constant??");
1730 OldC->uncheckedReplaceAllUsesWith(New);
1731 OldC->destroyConstant(); // This constant is now dead, destroy it.
1736 static ManagedStatic<ValueMap<char, PointerType,
1737 ConstantPointerNull> > NullPtrConstants;
1739 static char getValType(ConstantPointerNull *) {
1744 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1745 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1746 ConstantPointerNull* result = NullPtrConstants->getOrCreate(Ty, 0);
1747 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1751 // destroyConstant - Remove the constant from the constant table...
1753 void ConstantPointerNull::destroyConstant() {
1754 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1755 NullPtrConstants->remove(this);
1756 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1757 destroyConstantImpl();
1761 //---- UndefValue::get() implementation...
1765 // UndefValue does not take extra "value" argument...
1766 template<class ValType>
1767 struct ConstantCreator<UndefValue, Type, ValType> {
1768 static UndefValue *create(const Type *Ty, const ValType &V) {
1769 return new UndefValue(Ty);
1774 struct ConvertConstantType<UndefValue, Type> {
1775 static void convert(UndefValue *OldC, const Type *NewTy) {
1776 // Make everyone now use a constant of the new type.
1777 Constant *New = UndefValue::get(NewTy);
1778 assert(New != OldC && "Didn't replace constant??");
1779 OldC->uncheckedReplaceAllUsesWith(New);
1780 OldC->destroyConstant(); // This constant is now dead, destroy it.
1785 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1787 static char getValType(UndefValue *) {
1792 UndefValue *UndefValue::get(const Type *Ty) {
1793 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1794 UndefValue* result = UndefValueConstants->getOrCreate(Ty, 0);
1795 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1799 // destroyConstant - Remove the constant from the constant table.
1801 void UndefValue::destroyConstant() {
1802 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1803 UndefValueConstants->remove(this);
1804 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1805 destroyConstantImpl();
1808 //---- MDString::get() implementation
1811 MDString::MDString(const char *begin, const char *end)
1812 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1813 StrBegin(begin), StrEnd(end) {}
1815 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1817 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1818 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1819 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(StrBegin,
1821 MDString *&S = Entry.getValue();
1822 if (!S) S = new MDString(Entry.getKeyData(),
1823 Entry.getKeyData() + Entry.getKeyLength());
1825 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1829 void MDString::destroyConstant() {
1830 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1831 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1832 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1833 destroyConstantImpl();
1836 //---- MDNode::get() implementation
1839 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1841 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1842 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1843 for (unsigned i = 0; i != NumVals; ++i)
1844 Node.push_back(ElementVH(Vals[i], this));
1847 void MDNode::Profile(FoldingSetNodeID &ID) const {
1848 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1852 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1853 FoldingSetNodeID ID;
1854 for (unsigned i = 0; i != NumVals; ++i)
1855 ID.AddPointer(Vals[i]);
1857 if (llvm_is_multithreaded()) {
1858 ConstantsLock->reader_acquire();
1860 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1861 ConstantsLock->reader_release();
1864 ConstantsLock->writer_acquire();
1865 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1867 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1868 MDNode *N = new(0) MDNode(Vals, NumVals);
1869 MDNodeSet->InsertNode(N, InsertPoint);
1871 ConstantsLock->writer_release();
1877 if (MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint))
1880 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1881 MDNode *N = new(0) MDNode(Vals, NumVals);
1882 MDNodeSet->InsertNode(N, InsertPoint);
1887 void MDNode::destroyConstant() {
1888 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
1889 MDNodeSet->RemoveNode(this);
1890 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
1891 destroyConstantImpl();
1894 //---- ConstantExpr::get() implementations...
1899 struct ExprMapKeyType {
1900 typedef SmallVector<unsigned, 4> IndexList;
1902 ExprMapKeyType(unsigned opc,
1903 const std::vector<Constant*> &ops,
1904 unsigned short pred = 0,
1905 const IndexList &inds = IndexList())
1906 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1909 std::vector<Constant*> operands;
1911 bool operator==(const ExprMapKeyType& that) const {
1912 return this->opcode == that.opcode &&
1913 this->predicate == that.predicate &&
1914 this->operands == that.operands &&
1915 this->indices == that.indices;
1917 bool operator<(const ExprMapKeyType & that) const {
1918 return this->opcode < that.opcode ||
1919 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1920 (this->opcode == that.opcode && this->predicate == that.predicate &&
1921 this->operands < that.operands) ||
1922 (this->opcode == that.opcode && this->predicate == that.predicate &&
1923 this->operands == that.operands && this->indices < that.indices);
1926 bool operator!=(const ExprMapKeyType& that) const {
1927 return !(*this == that);
1935 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1936 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1937 unsigned short pred = 0) {
1938 if (Instruction::isCast(V.opcode))
1939 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1940 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1941 V.opcode < Instruction::BinaryOpsEnd))
1942 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1943 if (V.opcode == Instruction::Select)
1944 return new SelectConstantExpr(V.operands[0], V.operands[1],
1946 if (V.opcode == Instruction::ExtractElement)
1947 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1948 if (V.opcode == Instruction::InsertElement)
1949 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1951 if (V.opcode == Instruction::ShuffleVector)
1952 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1954 if (V.opcode == Instruction::InsertValue)
1955 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1957 if (V.opcode == Instruction::ExtractValue)
1958 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1959 if (V.opcode == Instruction::GetElementPtr) {
1960 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1961 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1964 // The compare instructions are weird. We have to encode the predicate
1965 // value and it is combined with the instruction opcode by multiplying
1966 // the opcode by one hundred. We must decode this to get the predicate.
1967 if (V.opcode == Instruction::ICmp)
1968 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1969 V.operands[0], V.operands[1]);
1970 if (V.opcode == Instruction::FCmp)
1971 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1972 V.operands[0], V.operands[1]);
1973 if (V.opcode == Instruction::VICmp)
1974 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1975 V.operands[0], V.operands[1]);
1976 if (V.opcode == Instruction::VFCmp)
1977 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1978 V.operands[0], V.operands[1]);
1979 assert(0 && "Invalid ConstantExpr!");
1985 struct ConvertConstantType<ConstantExpr, Type> {
1986 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1988 switch (OldC->getOpcode()) {
1989 case Instruction::Trunc:
1990 case Instruction::ZExt:
1991 case Instruction::SExt:
1992 case Instruction::FPTrunc:
1993 case Instruction::FPExt:
1994 case Instruction::UIToFP:
1995 case Instruction::SIToFP:
1996 case Instruction::FPToUI:
1997 case Instruction::FPToSI:
1998 case Instruction::PtrToInt:
1999 case Instruction::IntToPtr:
2000 case Instruction::BitCast:
2001 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
2004 case Instruction::Select:
2005 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
2006 OldC->getOperand(1),
2007 OldC->getOperand(2));
2010 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
2011 OldC->getOpcode() < Instruction::BinaryOpsEnd);
2012 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
2013 OldC->getOperand(1));
2015 case Instruction::GetElementPtr:
2016 // Make everyone now use a constant of the new type...
2017 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
2018 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
2019 &Idx[0], Idx.size());
2023 assert(New != OldC && "Didn't replace constant??");
2024 OldC->uncheckedReplaceAllUsesWith(New);
2025 OldC->destroyConstant(); // This constant is now dead, destroy it.
2028 } // end namespace llvm
2031 static ExprMapKeyType getValType(ConstantExpr *CE) {
2032 std::vector<Constant*> Operands;
2033 Operands.reserve(CE->getNumOperands());
2034 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2035 Operands.push_back(cast<Constant>(CE->getOperand(i)));
2036 return ExprMapKeyType(CE->getOpcode(), Operands,
2037 CE->isCompare() ? CE->getPredicate() : 0,
2039 CE->getIndices() : SmallVector<unsigned, 4>());
2042 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
2043 ConstantExpr> > ExprConstants;
2045 /// This is a utility function to handle folding of casts and lookup of the
2046 /// cast in the ExprConstants map. It is used by the various get* methods below.
2047 static inline Constant *getFoldedCast(
2048 Instruction::CastOps opc, Constant *C, const Type *Ty) {
2049 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2050 // Fold a few common cases
2051 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2054 // Look up the constant in the table first to ensure uniqueness
2055 std::vector<Constant*> argVec(1, C);
2056 ExprMapKeyType Key(opc, argVec);
2058 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2059 Constant* result = ExprConstants->getOrCreate(Ty, Key);
2060 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2064 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
2065 Instruction::CastOps opc = Instruction::CastOps(oc);
2066 assert(Instruction::isCast(opc) && "opcode out of range");
2067 assert(C && Ty && "Null arguments to getCast");
2068 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2072 assert(0 && "Invalid cast opcode");
2074 case Instruction::Trunc: return getTrunc(C, Ty);
2075 case Instruction::ZExt: return getZExt(C, Ty);
2076 case Instruction::SExt: return getSExt(C, Ty);
2077 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
2078 case Instruction::FPExt: return getFPExtend(C, Ty);
2079 case Instruction::UIToFP: return getUIToFP(C, Ty);
2080 case Instruction::SIToFP: return getSIToFP(C, Ty);
2081 case Instruction::FPToUI: return getFPToUI(C, Ty);
2082 case Instruction::FPToSI: return getFPToSI(C, Ty);
2083 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
2084 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
2085 case Instruction::BitCast: return getBitCast(C, Ty);
2090 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
2091 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2092 return getCast(Instruction::BitCast, C, Ty);
2093 return getCast(Instruction::ZExt, C, Ty);
2096 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
2097 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2098 return getCast(Instruction::BitCast, C, Ty);
2099 return getCast(Instruction::SExt, C, Ty);
2102 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
2103 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2104 return getCast(Instruction::BitCast, C, Ty);
2105 return getCast(Instruction::Trunc, C, Ty);
2108 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
2109 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2110 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
2112 if (Ty->isInteger())
2113 return getCast(Instruction::PtrToInt, S, Ty);
2114 return getCast(Instruction::BitCast, S, Ty);
2117 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
2119 assert(C->getType()->isIntOrIntVector() &&
2120 Ty->isIntOrIntVector() && "Invalid cast");
2121 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2122 unsigned DstBits = Ty->getScalarSizeInBits();
2123 Instruction::CastOps opcode =
2124 (SrcBits == DstBits ? Instruction::BitCast :
2125 (SrcBits > DstBits ? Instruction::Trunc :
2126 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2127 return getCast(opcode, C, Ty);
2130 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
2131 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2133 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2134 unsigned DstBits = Ty->getScalarSizeInBits();
2135 if (SrcBits == DstBits)
2136 return C; // Avoid a useless cast
2137 Instruction::CastOps opcode =
2138 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2139 return getCast(opcode, C, Ty);
2142 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
2144 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2145 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2147 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2148 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2149 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2150 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2151 "SrcTy must be larger than DestTy for Trunc!");
2153 return getFoldedCast(Instruction::Trunc, C, Ty);
2156 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
2158 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2159 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2161 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2162 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2163 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2164 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2165 "SrcTy must be smaller than DestTy for SExt!");
2167 return getFoldedCast(Instruction::SExt, C, Ty);
2170 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
2172 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2173 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2175 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2176 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2177 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2178 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2179 "SrcTy must be smaller than DestTy for ZExt!");
2181 return getFoldedCast(Instruction::ZExt, C, Ty);
2184 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
2186 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2187 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2189 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2190 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2191 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2192 "This is an illegal floating point truncation!");
2193 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2196 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2198 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2199 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2201 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2202 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2203 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2204 "This is an illegal floating point extension!");
2205 return getFoldedCast(Instruction::FPExt, C, Ty);
2208 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2210 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2211 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2213 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2214 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2215 "This is an illegal uint to floating point cast!");
2216 return getFoldedCast(Instruction::UIToFP, C, Ty);
2219 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2221 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2222 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2224 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2225 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2226 "This is an illegal sint to floating point cast!");
2227 return getFoldedCast(Instruction::SIToFP, C, Ty);
2230 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2232 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2233 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2235 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2236 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2237 "This is an illegal floating point to uint cast!");
2238 return getFoldedCast(Instruction::FPToUI, C, Ty);
2241 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2243 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2244 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2246 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2247 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2248 "This is an illegal floating point to sint cast!");
2249 return getFoldedCast(Instruction::FPToSI, C, Ty);
2252 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2253 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2254 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2255 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2258 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2259 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2260 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2261 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2264 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2265 // BitCast implies a no-op cast of type only. No bits change. However, you
2266 // can't cast pointers to anything but pointers.
2268 const Type *SrcTy = C->getType();
2269 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2270 "BitCast cannot cast pointer to non-pointer and vice versa");
2272 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2273 // or nonptr->ptr). For all the other types, the cast is okay if source and
2274 // destination bit widths are identical.
2275 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2276 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2278 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2280 // It is common to ask for a bitcast of a value to its own type, handle this
2282 if (C->getType() == DstTy) return C;
2284 return getFoldedCast(Instruction::BitCast, C, DstTy);
2287 Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2288 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2289 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2290 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2291 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2292 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2293 Constant *Indices[2] = { Zero, One };
2294 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2295 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2298 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
2299 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2300 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2302 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2303 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2306 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2307 Constant *C1, Constant *C2) {
2308 // Check the operands for consistency first
2309 assert(Opcode >= Instruction::BinaryOpsBegin &&
2310 Opcode < Instruction::BinaryOpsEnd &&
2311 "Invalid opcode in binary constant expression");
2312 assert(C1->getType() == C2->getType() &&
2313 "Operand types in binary constant expression should match");
2315 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2316 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2317 return FC; // Fold a few common cases...
2319 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2320 ExprMapKeyType Key(Opcode, argVec);
2321 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2322 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2323 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2327 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2328 Constant *C1, Constant *C2) {
2329 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
2330 switch (predicate) {
2331 default: assert(0 && "Invalid CmpInst predicate");
2332 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2333 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2334 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2335 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2336 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2337 case CmpInst::FCMP_TRUE:
2338 return isVectorType ? getVFCmp(predicate, C1, C2)
2339 : getFCmp(predicate, C1, C2);
2340 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2341 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2342 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2343 case CmpInst::ICMP_SLE:
2344 return isVectorType ? getVICmp(predicate, C1, C2)
2345 : getICmp(predicate, C1, C2);
2349 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2350 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2351 if (C1->getType()->isFPOrFPVector()) {
2352 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2353 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2354 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2358 case Instruction::Add:
2359 case Instruction::Sub:
2360 case Instruction::Mul:
2361 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2362 assert(C1->getType()->isIntOrIntVector() &&
2363 "Tried to create an integer operation on a non-integer type!");
2365 case Instruction::FAdd:
2366 case Instruction::FSub:
2367 case Instruction::FMul:
2368 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2369 assert(C1->getType()->isFPOrFPVector() &&
2370 "Tried to create a floating-point operation on a "
2371 "non-floating-point type!");
2373 case Instruction::UDiv:
2374 case Instruction::SDiv:
2375 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2376 assert(C1->getType()->isIntOrIntVector() &&
2377 "Tried to create an arithmetic operation on a non-arithmetic type!");
2379 case Instruction::FDiv:
2380 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2381 assert(C1->getType()->isFPOrFPVector() &&
2382 "Tried to create an arithmetic operation on a non-arithmetic type!");
2384 case Instruction::URem:
2385 case Instruction::SRem:
2386 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2387 assert(C1->getType()->isIntOrIntVector() &&
2388 "Tried to create an arithmetic operation on a non-arithmetic type!");
2390 case Instruction::FRem:
2391 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2392 assert(C1->getType()->isFPOrFPVector() &&
2393 "Tried to create an arithmetic operation on a non-arithmetic type!");
2395 case Instruction::And:
2396 case Instruction::Or:
2397 case Instruction::Xor:
2398 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2399 assert(C1->getType()->isIntOrIntVector() &&
2400 "Tried to create a logical operation on a non-integral type!");
2402 case Instruction::Shl:
2403 case Instruction::LShr:
2404 case Instruction::AShr:
2405 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2406 assert(C1->getType()->isIntOrIntVector() &&
2407 "Tried to create a shift operation on a non-integer type!");
2414 return getTy(C1->getType(), Opcode, C1, C2);
2417 Constant *ConstantExpr::getCompare(unsigned short pred,
2418 Constant *C1, Constant *C2) {
2419 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2420 return getCompareTy(pred, C1, C2);
2423 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2424 Constant *V1, Constant *V2) {
2425 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2427 if (ReqTy == V1->getType())
2428 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2429 return SC; // Fold common cases
2431 std::vector<Constant*> argVec(3, C);
2434 ExprMapKeyType Key(Instruction::Select, argVec);
2435 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2436 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2437 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2441 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2444 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2446 cast<PointerType>(ReqTy)->getElementType() &&
2447 "GEP indices invalid!");
2449 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2450 return FC; // Fold a few common cases...
2452 assert(isa<PointerType>(C->getType()) &&
2453 "Non-pointer type for constant GetElementPtr expression");
2454 // Look up the constant in the table first to ensure uniqueness
2455 std::vector<Constant*> ArgVec;
2456 ArgVec.reserve(NumIdx+1);
2457 ArgVec.push_back(C);
2458 for (unsigned i = 0; i != NumIdx; ++i)
2459 ArgVec.push_back(cast<Constant>(Idxs[i]));
2460 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2461 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2462 Constant *result = ExprConstants->getOrCreate(ReqTy, Key);
2463 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2467 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2469 // Get the result type of the getelementptr!
2471 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2472 assert(Ty && "GEP indices invalid!");
2473 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2474 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2477 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2479 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2484 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2485 assert(LHS->getType() == RHS->getType());
2486 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2487 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2489 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2490 return FC; // Fold a few common cases...
2492 // Look up the constant in the table first to ensure uniqueness
2493 std::vector<Constant*> ArgVec;
2494 ArgVec.push_back(LHS);
2495 ArgVec.push_back(RHS);
2496 // Get the key type with both the opcode and predicate
2497 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2498 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2499 Constant* result = ExprConstants->getOrCreate(Type::Int1Ty, Key);
2500 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2505 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2506 assert(LHS->getType() == RHS->getType());
2507 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2509 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2510 return FC; // Fold a few common cases...
2512 // Look up the constant in the table first to ensure uniqueness
2513 std::vector<Constant*> ArgVec;
2514 ArgVec.push_back(LHS);
2515 ArgVec.push_back(RHS);
2516 // Get the key type with both the opcode and predicate
2517 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2518 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2519 Constant* result = ExprConstants->getOrCreate(Type::Int1Ty, Key);
2520 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2525 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2526 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
2527 "Tried to create vicmp operation on non-vector type!");
2528 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2529 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2531 const VectorType *VTy = cast<VectorType>(LHS->getType());
2532 const Type *EltTy = VTy->getElementType();
2533 unsigned NumElts = VTy->getNumElements();
2535 // See if we can fold the element-wise comparison of the LHS and RHS.
2536 SmallVector<Constant *, 16> LHSElts, RHSElts;
2537 LHS->getVectorElements(LHSElts);
2538 RHS->getVectorElements(RHSElts);
2540 if (!LHSElts.empty() && !RHSElts.empty()) {
2541 SmallVector<Constant *, 16> Elts;
2542 for (unsigned i = 0; i != NumElts; ++i) {
2543 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2545 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2546 if (FCI->getZExtValue())
2547 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2549 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2550 } else if (FC && isa<UndefValue>(FC)) {
2551 Elts.push_back(UndefValue::get(EltTy));
2556 if (Elts.size() == NumElts)
2557 return ConstantVector::get(&Elts[0], Elts.size());
2560 // Look up the constant in the table first to ensure uniqueness
2561 std::vector<Constant*> ArgVec;
2562 ArgVec.push_back(LHS);
2563 ArgVec.push_back(RHS);
2564 // Get the key type with both the opcode and predicate
2565 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2566 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2567 Constant* result = ExprConstants->getOrCreate(LHS->getType(), Key);
2568 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2573 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2574 assert(isa<VectorType>(LHS->getType()) &&
2575 "Tried to create vfcmp operation on non-vector type!");
2576 assert(LHS->getType() == RHS->getType());
2577 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2579 const VectorType *VTy = cast<VectorType>(LHS->getType());
2580 unsigned NumElts = VTy->getNumElements();
2581 const Type *EltTy = VTy->getElementType();
2582 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2583 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2585 // See if we can fold the element-wise comparison of the LHS and RHS.
2586 SmallVector<Constant *, 16> LHSElts, RHSElts;
2587 LHS->getVectorElements(LHSElts);
2588 RHS->getVectorElements(RHSElts);
2590 if (!LHSElts.empty() && !RHSElts.empty()) {
2591 SmallVector<Constant *, 16> Elts;
2592 for (unsigned i = 0; i != NumElts; ++i) {
2593 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2595 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2596 if (FCI->getZExtValue())
2597 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2599 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2600 } else if (FC && isa<UndefValue>(FC)) {
2601 Elts.push_back(UndefValue::get(REltTy));
2606 if (Elts.size() == NumElts)
2607 return ConstantVector::get(&Elts[0], Elts.size());
2610 // Look up the constant in the table first to ensure uniqueness
2611 std::vector<Constant*> ArgVec;
2612 ArgVec.push_back(LHS);
2613 ArgVec.push_back(RHS);
2614 // Get the key type with both the opcode and predicate
2615 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2616 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2617 Constant* result = ExprConstants->getOrCreate(ResultTy, Key);
2618 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2622 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2624 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2625 return FC; // Fold a few common cases...
2626 // Look up the constant in the table first to ensure uniqueness
2627 std::vector<Constant*> ArgVec(1, Val);
2628 ArgVec.push_back(Idx);
2629 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2630 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2631 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2632 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2636 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2637 assert(isa<VectorType>(Val->getType()) &&
2638 "Tried to create extractelement operation on non-vector type!");
2639 assert(Idx->getType() == Type::Int32Ty &&
2640 "Extractelement index must be i32 type!");
2641 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2645 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2646 Constant *Elt, Constant *Idx) {
2647 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2648 return FC; // Fold a few common cases...
2649 // Look up the constant in the table first to ensure uniqueness
2650 std::vector<Constant*> ArgVec(1, Val);
2651 ArgVec.push_back(Elt);
2652 ArgVec.push_back(Idx);
2653 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2654 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2655 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2656 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2660 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2662 assert(isa<VectorType>(Val->getType()) &&
2663 "Tried to create insertelement operation on non-vector type!");
2664 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2665 && "Insertelement types must match!");
2666 assert(Idx->getType() == Type::Int32Ty &&
2667 "Insertelement index must be i32 type!");
2668 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2671 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2672 Constant *V2, Constant *Mask) {
2673 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2674 return FC; // Fold a few common cases...
2675 // Look up the constant in the table first to ensure uniqueness
2676 std::vector<Constant*> ArgVec(1, V1);
2677 ArgVec.push_back(V2);
2678 ArgVec.push_back(Mask);
2679 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2680 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2681 Constant* result = ExprConstants->getOrCreate(ReqTy, Key);
2682 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2686 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2688 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2689 "Invalid shuffle vector constant expr operands!");
2691 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2692 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2693 const Type *ShufTy = VectorType::get(EltTy, NElts);
2694 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2697 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2699 const unsigned *Idxs, unsigned NumIdx) {
2700 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2701 Idxs+NumIdx) == Val->getType() &&
2702 "insertvalue indices invalid!");
2703 assert(Agg->getType() == ReqTy &&
2704 "insertvalue type invalid!");
2705 assert(Agg->getType()->isFirstClassType() &&
2706 "Non-first-class type for constant InsertValue expression");
2707 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2708 assert(FC && "InsertValue constant expr couldn't be folded!");
2712 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2713 const unsigned *IdxList, unsigned NumIdx) {
2714 assert(Agg->getType()->isFirstClassType() &&
2715 "Tried to create insertelement operation on non-first-class type!");
2717 const Type *ReqTy = Agg->getType();
2720 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2722 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2723 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2726 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2727 const unsigned *Idxs, unsigned NumIdx) {
2728 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2729 Idxs+NumIdx) == ReqTy &&
2730 "extractvalue indices invalid!");
2731 assert(Agg->getType()->isFirstClassType() &&
2732 "Non-first-class type for constant extractvalue expression");
2733 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2734 assert(FC && "ExtractValue constant expr couldn't be folded!");
2738 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2739 const unsigned *IdxList, unsigned NumIdx) {
2740 assert(Agg->getType()->isFirstClassType() &&
2741 "Tried to create extractelement operation on non-first-class type!");
2744 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2745 assert(ReqTy && "extractvalue indices invalid!");
2746 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2749 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2750 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2751 if (PTy->getElementType()->isFloatingPoint()) {
2752 std::vector<Constant*> zeros(PTy->getNumElements(),
2753 ConstantFP::getNegativeZero(PTy->getElementType()));
2754 return ConstantVector::get(PTy, zeros);
2757 if (Ty->isFloatingPoint())
2758 return ConstantFP::getNegativeZero(Ty);
2760 return Constant::getNullValue(Ty);
2763 // destroyConstant - Remove the constant from the constant table...
2765 void ConstantExpr::destroyConstant() {
2766 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2767 ExprConstants->remove(this);
2768 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2769 destroyConstantImpl();
2772 const char *ConstantExpr::getOpcodeName() const {
2773 return Instruction::getOpcodeName(getOpcode());
2776 //===----------------------------------------------------------------------===//
2777 // replaceUsesOfWithOnConstant implementations
2779 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2780 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2783 /// Note that we intentionally replace all uses of From with To here. Consider
2784 /// a large array that uses 'From' 1000 times. By handling this case all here,
2785 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2786 /// single invocation handles all 1000 uses. Handling them one at a time would
2787 /// work, but would be really slow because it would have to unique each updated
2789 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2791 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2792 Constant *ToC = cast<Constant>(To);
2794 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2795 Lookup.first.first = getType();
2796 Lookup.second = this;
2798 std::vector<Constant*> &Values = Lookup.first.second;
2799 Values.reserve(getNumOperands()); // Build replacement array.
2801 // Fill values with the modified operands of the constant array. Also,
2802 // compute whether this turns into an all-zeros array.
2803 bool isAllZeros = false;
2804 unsigned NumUpdated = 0;
2805 if (!ToC->isNullValue()) {
2806 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2807 Constant *Val = cast<Constant>(O->get());
2812 Values.push_back(Val);
2816 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2817 Constant *Val = cast<Constant>(O->get());
2822 Values.push_back(Val);
2823 if (isAllZeros) isAllZeros = Val->isNullValue();
2827 Constant *Replacement = 0;
2829 Replacement = ConstantAggregateZero::get(getType());
2831 // Check to see if we have this array type already.
2832 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2834 ArrayConstantsTy::MapTy::iterator I =
2835 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2838 Replacement = I->second;
2840 // Okay, the new shape doesn't exist in the system yet. Instead of
2841 // creating a new constant array, inserting it, replaceallusesof'ing the
2842 // old with the new, then deleting the old... just update the current one
2844 ArrayConstants->MoveConstantToNewSlot(this, I);
2846 // Update to the new value. Optimize for the case when we have a single
2847 // operand that we're changing, but handle bulk updates efficiently.
2848 if (NumUpdated == 1) {
2849 unsigned OperandToUpdate = U-OperandList;
2850 assert(getOperand(OperandToUpdate) == From &&
2851 "ReplaceAllUsesWith broken!");
2852 setOperand(OperandToUpdate, ToC);
2854 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2855 if (getOperand(i) == From)
2858 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2861 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2864 // Otherwise, I do need to replace this with an existing value.
2865 assert(Replacement != this && "I didn't contain From!");
2867 // Everyone using this now uses the replacement.
2868 uncheckedReplaceAllUsesWith(Replacement);
2870 // Delete the old constant!
2874 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2876 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2877 Constant *ToC = cast<Constant>(To);
2879 unsigned OperandToUpdate = U-OperandList;
2880 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2882 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2883 Lookup.first.first = getType();
2884 Lookup.second = this;
2885 std::vector<Constant*> &Values = Lookup.first.second;
2886 Values.reserve(getNumOperands()); // Build replacement struct.
2889 // Fill values with the modified operands of the constant struct. Also,
2890 // compute whether this turns into an all-zeros struct.
2891 bool isAllZeros = false;
2892 if (!ToC->isNullValue()) {
2893 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2894 Values.push_back(cast<Constant>(O->get()));
2897 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2898 Constant *Val = cast<Constant>(O->get());
2899 Values.push_back(Val);
2900 if (isAllZeros) isAllZeros = Val->isNullValue();
2903 Values[OperandToUpdate] = ToC;
2905 Constant *Replacement = 0;
2907 Replacement = ConstantAggregateZero::get(getType());
2909 // Check to see if we have this array type already.
2910 if (llvm_is_multithreaded()) ConstantsLock->writer_acquire();
2912 StructConstantsTy::MapTy::iterator I =
2913 StructConstants->InsertOrGetItem(Lookup, Exists);
2916 Replacement = I->second;
2918 // Okay, the new shape doesn't exist in the system yet. Instead of
2919 // creating a new constant struct, inserting it, replaceallusesof'ing the
2920 // old with the new, then deleting the old... just update the current one
2922 StructConstants->MoveConstantToNewSlot(this, I);
2924 // Update to the new value.
2925 setOperand(OperandToUpdate, ToC);
2926 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2929 if (llvm_is_multithreaded()) ConstantsLock->writer_release();
2932 assert(Replacement != this && "I didn't contain From!");
2934 // Everyone using this now uses the replacement.
2935 uncheckedReplaceAllUsesWith(Replacement);
2937 // Delete the old constant!
2941 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2943 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2945 std::vector<Constant*> Values;
2946 Values.reserve(getNumOperands()); // Build replacement array...
2947 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2948 Constant *Val = getOperand(i);
2949 if (Val == From) Val = cast<Constant>(To);
2950 Values.push_back(Val);
2953 Constant *Replacement = ConstantVector::get(getType(), Values);
2954 assert(Replacement != this && "I didn't contain From!");
2956 // Everyone using this now uses the replacement.
2957 uncheckedReplaceAllUsesWith(Replacement);
2959 // Delete the old constant!
2963 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2965 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2966 Constant *To = cast<Constant>(ToV);
2968 Constant *Replacement = 0;
2969 if (getOpcode() == Instruction::GetElementPtr) {
2970 SmallVector<Constant*, 8> Indices;
2971 Constant *Pointer = getOperand(0);
2972 Indices.reserve(getNumOperands()-1);
2973 if (Pointer == From) Pointer = To;
2975 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2976 Constant *Val = getOperand(i);
2977 if (Val == From) Val = To;
2978 Indices.push_back(Val);
2980 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2981 &Indices[0], Indices.size());
2982 } else if (getOpcode() == Instruction::ExtractValue) {
2983 Constant *Agg = getOperand(0);
2984 if (Agg == From) Agg = To;
2986 const SmallVector<unsigned, 4> &Indices = getIndices();
2987 Replacement = ConstantExpr::getExtractValue(Agg,
2988 &Indices[0], Indices.size());
2989 } else if (getOpcode() == Instruction::InsertValue) {
2990 Constant *Agg = getOperand(0);
2991 Constant *Val = getOperand(1);
2992 if (Agg == From) Agg = To;
2993 if (Val == From) Val = To;
2995 const SmallVector<unsigned, 4> &Indices = getIndices();
2996 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2997 &Indices[0], Indices.size());
2998 } else if (isCast()) {
2999 assert(getOperand(0) == From && "Cast only has one use!");
3000 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
3001 } else if (getOpcode() == Instruction::Select) {
3002 Constant *C1 = getOperand(0);
3003 Constant *C2 = getOperand(1);
3004 Constant *C3 = getOperand(2);
3005 if (C1 == From) C1 = To;
3006 if (C2 == From) C2 = To;
3007 if (C3 == From) C3 = To;
3008 Replacement = ConstantExpr::getSelect(C1, C2, C3);
3009 } else if (getOpcode() == Instruction::ExtractElement) {
3010 Constant *C1 = getOperand(0);
3011 Constant *C2 = getOperand(1);
3012 if (C1 == From) C1 = To;
3013 if (C2 == From) C2 = To;
3014 Replacement = ConstantExpr::getExtractElement(C1, C2);
3015 } else if (getOpcode() == Instruction::InsertElement) {
3016 Constant *C1 = getOperand(0);
3017 Constant *C2 = getOperand(1);
3018 Constant *C3 = getOperand(1);
3019 if (C1 == From) C1 = To;
3020 if (C2 == From) C2 = To;
3021 if (C3 == From) C3 = To;
3022 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
3023 } else if (getOpcode() == Instruction::ShuffleVector) {
3024 Constant *C1 = getOperand(0);
3025 Constant *C2 = getOperand(1);
3026 Constant *C3 = getOperand(2);
3027 if (C1 == From) C1 = To;
3028 if (C2 == From) C2 = To;
3029 if (C3 == From) C3 = To;
3030 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
3031 } else if (isCompare()) {
3032 Constant *C1 = getOperand(0);
3033 Constant *C2 = getOperand(1);
3034 if (C1 == From) C1 = To;
3035 if (C2 == From) C2 = To;
3036 if (getOpcode() == Instruction::ICmp)
3037 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
3038 else if (getOpcode() == Instruction::FCmp)
3039 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
3040 else if (getOpcode() == Instruction::VICmp)
3041 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
3043 assert(getOpcode() == Instruction::VFCmp);
3044 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
3046 } else if (getNumOperands() == 2) {
3047 Constant *C1 = getOperand(0);
3048 Constant *C2 = getOperand(1);
3049 if (C1 == From) C1 = To;
3050 if (C2 == From) C2 = To;
3051 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
3053 assert(0 && "Unknown ConstantExpr type!");
3057 assert(Replacement != this && "I didn't contain From!");
3059 // Everyone using this now uses the replacement.
3060 uncheckedReplaceAllUsesWith(Replacement);
3062 // Delete the old constant!
3066 void MDNode::replaceElement(Value *From, Value *To) {
3067 SmallVector<Value*, 4> Values;
3068 Values.reserve(getNumElements()); // Build replacement array...
3069 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3070 Value *Val = getElement(i);
3071 if (Val == From) Val = To;
3072 Values.push_back(Val);
3075 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
3076 assert(Replacement != this && "I didn't contain From!");
3078 uncheckedReplaceAllUsesWith(Replacement);