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/System/RWMutex.h"
29 #include "llvm/System/Threading.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallVector.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 // Becomes a no-op when multithreading is disabled.
41 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
43 void Constant::destroyConstantImpl() {
44 // When a Constant is destroyed, there may be lingering
45 // references to the constant by other constants in the constant pool. These
46 // constants are implicitly dependent on the module that is being deleted,
47 // but they don't know that. Because we only find out when the CPV is
48 // deleted, we must now notify all of our users (that should only be
49 // Constants) that they are, in fact, invalid now and should be deleted.
51 while (!use_empty()) {
52 Value *V = use_back();
53 #ifndef NDEBUG // Only in -g mode...
54 if (!isa<Constant>(V))
55 DOUT << "While deleting: " << *this
56 << "\n\nUse still stuck around after Def is destroyed: "
59 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
60 Constant *CV = cast<Constant>(V);
61 CV->destroyConstant();
63 // The constant should remove itself from our use list...
64 assert((use_empty() || use_back() != V) && "Constant not removed!");
67 // Value has no outstanding references it is safe to delete it now...
71 /// canTrap - Return true if evaluation of this constant could trap. This is
72 /// true for things like constant expressions that could divide by zero.
73 bool Constant::canTrap() const {
74 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
75 // The only thing that could possibly trap are constant exprs.
76 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
77 if (!CE) return false;
79 // ConstantExpr traps if any operands can trap.
80 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
81 if (getOperand(i)->canTrap())
84 // Otherwise, only specific operations can trap.
85 switch (CE->getOpcode()) {
88 case Instruction::UDiv:
89 case Instruction::SDiv:
90 case Instruction::FDiv:
91 case Instruction::URem:
92 case Instruction::SRem:
93 case Instruction::FRem:
94 // Div and rem can trap if the RHS is not known to be non-zero.
95 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
101 /// ContainsRelocations - Return true if the constant value contains relocations
102 /// which cannot be resolved at compile time. Kind argument is used to filter
103 /// only 'interesting' sorts of relocations.
104 bool Constant::ContainsRelocations(unsigned Kind) const {
105 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
106 bool isLocal = GV->hasLocalLinkage();
107 if ((Kind & Reloc::Local) && isLocal) {
108 // Global has local linkage and 'local' kind of relocations are
113 if ((Kind & Reloc::Global) && !isLocal) {
114 // Global has non-local linkage and 'global' kind of relocations are
122 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
123 if (getOperand(i)->ContainsRelocations(Kind))
129 // Static constructor to create a '0' constant of arbitrary type...
130 Constant *Constant::getNullValue(const Type *Ty) {
131 static uint64_t zero[2] = {0, 0};
132 switch (Ty->getTypeID()) {
133 case Type::IntegerTyID:
134 return ConstantInt::get(Ty, 0);
135 case Type::FloatTyID:
136 return ConstantFP::get(APFloat(APInt(32, 0)));
137 case Type::DoubleTyID:
138 return ConstantFP::get(APFloat(APInt(64, 0)));
139 case Type::X86_FP80TyID:
140 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
141 case Type::FP128TyID:
142 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
143 case Type::PPC_FP128TyID:
144 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
145 case Type::PointerTyID:
146 return ConstantPointerNull::get(cast<PointerType>(Ty));
147 case Type::StructTyID:
148 case Type::ArrayTyID:
149 case Type::VectorTyID:
150 return ConstantAggregateZero::get(Ty);
152 // Function, Label, or Opaque type?
153 assert(!"Cannot create a null constant of that type!");
158 Constant *Constant::getAllOnesValue(const Type *Ty) {
159 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
160 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
161 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
164 // Static constructor to create an integral constant with all bits set
165 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
166 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
167 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
171 /// @returns the value for a vector integer constant of the given type that
172 /// has all its bits set to true.
173 /// @brief Get the all ones value
174 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
175 std::vector<Constant*> Elts;
176 Elts.resize(Ty->getNumElements(),
177 ConstantInt::getAllOnesValue(Ty->getElementType()));
178 assert(Elts[0] && "Not a vector integer type!");
179 return cast<ConstantVector>(ConstantVector::get(Elts));
183 /// getVectorElements - This method, which is only valid on constant of vector
184 /// type, returns the elements of the vector in the specified smallvector.
185 /// This handles breaking down a vector undef into undef elements, etc. For
186 /// constant exprs and other cases we can't handle, we return an empty vector.
187 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
188 assert(isa<VectorType>(getType()) && "Not a vector constant!");
190 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
191 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
192 Elts.push_back(CV->getOperand(i));
196 const VectorType *VT = cast<VectorType>(getType());
197 if (isa<ConstantAggregateZero>(this)) {
198 Elts.assign(VT->getNumElements(),
199 Constant::getNullValue(VT->getElementType()));
203 if (isa<UndefValue>(this)) {
204 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
208 // Unknown type, must be constant expr etc.
213 //===----------------------------------------------------------------------===//
215 //===----------------------------------------------------------------------===//
217 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
218 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
219 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
222 ConstantInt *ConstantInt::TheTrueVal = 0;
223 ConstantInt *ConstantInt::TheFalseVal = 0;
226 void CleanupTrueFalse(void *) {
227 ConstantInt::ResetTrueFalse();
231 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
233 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
234 assert(TheTrueVal == 0 && TheFalseVal == 0);
235 TheTrueVal = get(Type::Int1Ty, 1);
236 TheFalseVal = get(Type::Int1Ty, 0);
238 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
239 TrueFalseCleanup.Register();
241 return WhichOne ? TheTrueVal : TheFalseVal;
246 struct DenseMapAPIntKeyInfo {
250 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
251 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
252 bool operator==(const KeyTy& that) const {
253 return type == that.type && this->val == that.val;
255 bool operator!=(const KeyTy& that) const {
256 return !this->operator==(that);
259 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
260 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
261 static unsigned getHashValue(const KeyTy &Key) {
262 return DenseMapInfo<void*>::getHashValue(Key.type) ^
263 Key.val.getHashValue();
265 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
268 static bool isPod() { return false; }
273 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
274 DenseMapAPIntKeyInfo> IntMapTy;
275 static ManagedStatic<IntMapTy> IntConstants;
277 ConstantInt *ConstantInt::get(const IntegerType *Ty,
278 uint64_t V, bool isSigned) {
279 return get(APInt(Ty->getBitWidth(), V, isSigned));
282 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
283 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
285 // For vectors, broadcast the value.
286 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
288 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
293 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
294 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
295 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
296 // compare APInt's of different widths, which would violate an APInt class
297 // invariant which generates an assertion.
298 ConstantInt *ConstantInt::get(const APInt& V) {
299 // Get the corresponding integer type for the bit width of the value.
300 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
301 // get an existing value or the insertion position
302 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
304 ConstantsLock->reader_acquire();
305 ConstantInt *&Slot = (*IntConstants)[Key];
306 ConstantsLock->reader_release();
309 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
310 ConstantInt *&NewSlot = (*IntConstants)[Key];
312 NewSlot = new ConstantInt(ITy, V);
321 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
322 ConstantInt *C = ConstantInt::get(V);
323 assert(C->getType() == Ty->getScalarType() &&
324 "ConstantInt type doesn't match the type implied by its value!");
326 // For vectors, broadcast the value.
327 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
329 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
334 //===----------------------------------------------------------------------===//
336 //===----------------------------------------------------------------------===//
338 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
339 if (Ty == Type::FloatTy)
340 return &APFloat::IEEEsingle;
341 if (Ty == Type::DoubleTy)
342 return &APFloat::IEEEdouble;
343 if (Ty == Type::X86_FP80Ty)
344 return &APFloat::x87DoubleExtended;
345 else if (Ty == Type::FP128Ty)
346 return &APFloat::IEEEquad;
348 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
349 return &APFloat::PPCDoubleDouble;
352 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
353 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
354 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
358 bool ConstantFP::isNullValue() const {
359 return Val.isZero() && !Val.isNegative();
362 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
363 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
365 return ConstantFP::get(apf);
368 bool ConstantFP::isExactlyValue(const APFloat& V) const {
369 return Val.bitwiseIsEqual(V);
373 struct DenseMapAPFloatKeyInfo {
376 KeyTy(const APFloat& V) : val(V){}
377 KeyTy(const KeyTy& that) : val(that.val) {}
378 bool operator==(const KeyTy& that) const {
379 return this->val.bitwiseIsEqual(that.val);
381 bool operator!=(const KeyTy& that) const {
382 return !this->operator==(that);
385 static inline KeyTy getEmptyKey() {
386 return KeyTy(APFloat(APFloat::Bogus,1));
388 static inline KeyTy getTombstoneKey() {
389 return KeyTy(APFloat(APFloat::Bogus,2));
391 static unsigned getHashValue(const KeyTy &Key) {
392 return Key.val.getHashValue();
394 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
397 static bool isPod() { return false; }
401 //---- ConstantFP::get() implementation...
403 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
404 DenseMapAPFloatKeyInfo> FPMapTy;
406 static ManagedStatic<FPMapTy> FPConstants;
408 ConstantFP *ConstantFP::get(const APFloat &V) {
409 DenseMapAPFloatKeyInfo::KeyTy Key(V);
411 ConstantsLock->reader_acquire();
412 ConstantFP *&Slot = (*FPConstants)[Key];
413 ConstantsLock->reader_release();
416 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
417 ConstantFP *&NewSlot = (*FPConstants)[Key];
420 if (&V.getSemantics() == &APFloat::IEEEsingle)
422 else if (&V.getSemantics() == &APFloat::IEEEdouble)
424 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
425 Ty = Type::X86_FP80Ty;
426 else if (&V.getSemantics() == &APFloat::IEEEquad)
429 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
430 "Unknown FP format");
431 Ty = Type::PPC_FP128Ty;
433 NewSlot = new ConstantFP(Ty, V);
442 /// get() - This returns a constant fp for the specified value in the
443 /// specified type. This should only be used for simple constant values like
444 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
445 Constant *ConstantFP::get(const Type *Ty, double V) {
448 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
449 APFloat::rmNearestTiesToEven, &ignored);
450 Constant *C = get(FV);
452 // For vectors, broadcast the value.
453 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
455 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
460 //===----------------------------------------------------------------------===//
461 // ConstantXXX Classes
462 //===----------------------------------------------------------------------===//
465 ConstantArray::ConstantArray(const ArrayType *T,
466 const std::vector<Constant*> &V)
467 : Constant(T, ConstantArrayVal,
468 OperandTraits<ConstantArray>::op_end(this) - V.size(),
470 assert(V.size() == T->getNumElements() &&
471 "Invalid initializer vector for constant array");
472 Use *OL = OperandList;
473 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
476 assert((C->getType() == T->getElementType() ||
478 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
479 "Initializer for array element doesn't match array element type!");
485 ConstantStruct::ConstantStruct(const StructType *T,
486 const std::vector<Constant*> &V)
487 : Constant(T, ConstantStructVal,
488 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
490 assert(V.size() == T->getNumElements() &&
491 "Invalid initializer vector for constant structure");
492 Use *OL = OperandList;
493 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
496 assert((C->getType() == T->getElementType(I-V.begin()) ||
497 ((T->getElementType(I-V.begin())->isAbstract() ||
498 C->getType()->isAbstract()) &&
499 T->getElementType(I-V.begin())->getTypeID() ==
500 C->getType()->getTypeID())) &&
501 "Initializer for struct element doesn't match struct element type!");
507 ConstantVector::ConstantVector(const VectorType *T,
508 const std::vector<Constant*> &V)
509 : Constant(T, ConstantVectorVal,
510 OperandTraits<ConstantVector>::op_end(this) - V.size(),
512 Use *OL = OperandList;
513 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
516 assert((C->getType() == T->getElementType() ||
518 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
519 "Initializer for vector element doesn't match vector element type!");
526 // We declare several classes private to this file, so use an anonymous
530 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
531 /// behind the scenes to implement unary constant exprs.
532 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
533 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
535 // allocate space for exactly one operand
536 void *operator new(size_t s) {
537 return User::operator new(s, 1);
539 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
540 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
543 /// Transparently provide more efficient getOperand methods.
544 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
547 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
548 /// behind the scenes to implement binary constant exprs.
549 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
550 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
552 // allocate space for exactly two operands
553 void *operator new(size_t s) {
554 return User::operator new(s, 2);
556 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
557 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
561 /// Transparently provide more efficient getOperand methods.
562 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
565 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
566 /// behind the scenes to implement select constant exprs.
567 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
568 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
570 // allocate space for exactly three operands
571 void *operator new(size_t s) {
572 return User::operator new(s, 3);
574 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
575 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
580 /// Transparently provide more efficient getOperand methods.
581 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
584 /// ExtractElementConstantExpr - This class is private to
585 /// Constants.cpp, and is used behind the scenes to implement
586 /// extractelement constant exprs.
587 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
588 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
590 // allocate space for exactly two operands
591 void *operator new(size_t s) {
592 return User::operator new(s, 2);
594 ExtractElementConstantExpr(Constant *C1, Constant *C2)
595 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
596 Instruction::ExtractElement, &Op<0>(), 2) {
600 /// Transparently provide more efficient getOperand methods.
601 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
604 /// InsertElementConstantExpr - This class is private to
605 /// Constants.cpp, and is used behind the scenes to implement
606 /// insertelement constant exprs.
607 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
608 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
610 // allocate space for exactly three operands
611 void *operator new(size_t s) {
612 return User::operator new(s, 3);
614 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
615 : ConstantExpr(C1->getType(), Instruction::InsertElement,
621 /// Transparently provide more efficient getOperand methods.
622 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
625 /// ShuffleVectorConstantExpr - This class is private to
626 /// Constants.cpp, and is used behind the scenes to implement
627 /// shufflevector constant exprs.
628 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
629 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
631 // allocate space for exactly three operands
632 void *operator new(size_t s) {
633 return User::operator new(s, 3);
635 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
636 : ConstantExpr(VectorType::get(
637 cast<VectorType>(C1->getType())->getElementType(),
638 cast<VectorType>(C3->getType())->getNumElements()),
639 Instruction::ShuffleVector,
645 /// Transparently provide more efficient getOperand methods.
646 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
649 /// ExtractValueConstantExpr - This class is private to
650 /// Constants.cpp, and is used behind the scenes to implement
651 /// extractvalue constant exprs.
652 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
653 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
655 // allocate space for exactly one operand
656 void *operator new(size_t s) {
657 return User::operator new(s, 1);
659 ExtractValueConstantExpr(Constant *Agg,
660 const SmallVector<unsigned, 4> &IdxList,
662 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
667 /// Indices - These identify which value to extract.
668 const SmallVector<unsigned, 4> Indices;
670 /// Transparently provide more efficient getOperand methods.
671 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
674 /// InsertValueConstantExpr - This class is private to
675 /// Constants.cpp, and is used behind the scenes to implement
676 /// insertvalue constant exprs.
677 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
678 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
680 // allocate space for exactly one operand
681 void *operator new(size_t s) {
682 return User::operator new(s, 2);
684 InsertValueConstantExpr(Constant *Agg, Constant *Val,
685 const SmallVector<unsigned, 4> &IdxList,
687 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
693 /// Indices - These identify the position for the insertion.
694 const SmallVector<unsigned, 4> Indices;
696 /// Transparently provide more efficient getOperand methods.
697 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
701 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
702 /// used behind the scenes to implement getelementpr constant exprs.
703 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
704 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
707 static GetElementPtrConstantExpr *Create(Constant *C,
708 const std::vector<Constant*>&IdxList,
709 const Type *DestTy) {
710 return new(IdxList.size() + 1)
711 GetElementPtrConstantExpr(C, IdxList, DestTy);
713 /// Transparently provide more efficient getOperand methods.
714 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
717 // CompareConstantExpr - This class is private to Constants.cpp, and is used
718 // behind the scenes to implement ICmp and FCmp constant expressions. This is
719 // needed in order to store the predicate value for these instructions.
720 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
721 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
722 // allocate space for exactly two operands
723 void *operator new(size_t s) {
724 return User::operator new(s, 2);
726 unsigned short predicate;
727 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
728 unsigned short pred, Constant* LHS, Constant* RHS)
729 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
733 /// Transparently provide more efficient getOperand methods.
734 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
737 } // end anonymous namespace
740 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
742 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
745 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
747 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
750 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
752 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
755 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
757 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
760 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
762 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
765 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
767 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
770 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
772 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
775 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
777 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
780 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
783 GetElementPtrConstantExpr::GetElementPtrConstantExpr
785 const std::vector<Constant*> &IdxList,
787 : ConstantExpr(DestTy, Instruction::GetElementPtr,
788 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
789 - (IdxList.size()+1),
792 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
793 OperandList[i+1] = IdxList[i];
796 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
800 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
802 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
805 } // End llvm namespace
808 // Utility function for determining if a ConstantExpr is a CastOp or not. This
809 // can't be inline because we don't want to #include Instruction.h into
811 bool ConstantExpr::isCast() const {
812 return Instruction::isCast(getOpcode());
815 bool ConstantExpr::isCompare() const {
816 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
817 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
820 bool ConstantExpr::hasIndices() const {
821 return getOpcode() == Instruction::ExtractValue ||
822 getOpcode() == Instruction::InsertValue;
825 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
826 if (const ExtractValueConstantExpr *EVCE =
827 dyn_cast<ExtractValueConstantExpr>(this))
828 return EVCE->Indices;
830 return cast<InsertValueConstantExpr>(this)->Indices;
833 /// ConstantExpr::get* - Return some common constants without having to
834 /// specify the full Instruction::OPCODE identifier.
836 Constant *ConstantExpr::getNeg(Constant *C) {
837 // API compatibility: Adjust integer opcodes to floating-point opcodes.
838 if (C->getType()->isFPOrFPVector())
840 assert(C->getType()->isIntOrIntVector() &&
841 "Cannot NEG a nonintegral value!");
842 return get(Instruction::Sub,
843 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
846 Constant *ConstantExpr::getFNeg(Constant *C) {
847 assert(C->getType()->isFPOrFPVector() &&
848 "Cannot FNEG a non-floating-point value!");
849 return get(Instruction::FSub,
850 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
853 Constant *ConstantExpr::getNot(Constant *C) {
854 assert(C->getType()->isIntOrIntVector() &&
855 "Cannot NOT a nonintegral value!");
856 return get(Instruction::Xor, C,
857 Constant::getAllOnesValue(C->getType()));
859 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
860 return get(Instruction::Add, C1, C2);
862 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
863 return get(Instruction::FAdd, C1, C2);
865 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
866 return get(Instruction::Sub, C1, C2);
868 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
869 return get(Instruction::FSub, C1, C2);
871 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
872 return get(Instruction::Mul, C1, C2);
874 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
875 return get(Instruction::FMul, C1, C2);
877 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
878 return get(Instruction::UDiv, C1, C2);
880 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
881 return get(Instruction::SDiv, C1, C2);
883 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
884 return get(Instruction::FDiv, C1, C2);
886 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
887 return get(Instruction::URem, C1, C2);
889 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
890 return get(Instruction::SRem, C1, C2);
892 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
893 return get(Instruction::FRem, C1, C2);
895 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
896 return get(Instruction::And, C1, C2);
898 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
899 return get(Instruction::Or, C1, C2);
901 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
902 return get(Instruction::Xor, C1, C2);
904 unsigned ConstantExpr::getPredicate() const {
905 assert(getOpcode() == Instruction::FCmp ||
906 getOpcode() == Instruction::ICmp ||
907 getOpcode() == Instruction::VFCmp ||
908 getOpcode() == Instruction::VICmp);
909 return ((const CompareConstantExpr*)this)->predicate;
911 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
912 return get(Instruction::Shl, C1, C2);
914 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
915 return get(Instruction::LShr, C1, C2);
917 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
918 return get(Instruction::AShr, C1, C2);
921 /// getWithOperandReplaced - Return a constant expression identical to this
922 /// one, but with the specified operand set to the specified value.
924 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
925 assert(OpNo < getNumOperands() && "Operand num is out of range!");
926 assert(Op->getType() == getOperand(OpNo)->getType() &&
927 "Replacing operand with value of different type!");
928 if (getOperand(OpNo) == Op)
929 return const_cast<ConstantExpr*>(this);
931 Constant *Op0, *Op1, *Op2;
932 switch (getOpcode()) {
933 case Instruction::Trunc:
934 case Instruction::ZExt:
935 case Instruction::SExt:
936 case Instruction::FPTrunc:
937 case Instruction::FPExt:
938 case Instruction::UIToFP:
939 case Instruction::SIToFP:
940 case Instruction::FPToUI:
941 case Instruction::FPToSI:
942 case Instruction::PtrToInt:
943 case Instruction::IntToPtr:
944 case Instruction::BitCast:
945 return ConstantExpr::getCast(getOpcode(), Op, getType());
946 case Instruction::Select:
947 Op0 = (OpNo == 0) ? Op : getOperand(0);
948 Op1 = (OpNo == 1) ? Op : getOperand(1);
949 Op2 = (OpNo == 2) ? Op : getOperand(2);
950 return ConstantExpr::getSelect(Op0, Op1, Op2);
951 case Instruction::InsertElement:
952 Op0 = (OpNo == 0) ? Op : getOperand(0);
953 Op1 = (OpNo == 1) ? Op : getOperand(1);
954 Op2 = (OpNo == 2) ? Op : getOperand(2);
955 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
956 case Instruction::ExtractElement:
957 Op0 = (OpNo == 0) ? Op : getOperand(0);
958 Op1 = (OpNo == 1) ? Op : getOperand(1);
959 return ConstantExpr::getExtractElement(Op0, Op1);
960 case Instruction::ShuffleVector:
961 Op0 = (OpNo == 0) ? Op : getOperand(0);
962 Op1 = (OpNo == 1) ? Op : getOperand(1);
963 Op2 = (OpNo == 2) ? Op : getOperand(2);
964 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
965 case Instruction::GetElementPtr: {
966 SmallVector<Constant*, 8> Ops;
967 Ops.resize(getNumOperands()-1);
968 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
969 Ops[i-1] = getOperand(i);
971 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
973 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
976 assert(getNumOperands() == 2 && "Must be binary operator?");
977 Op0 = (OpNo == 0) ? Op : getOperand(0);
978 Op1 = (OpNo == 1) ? Op : getOperand(1);
979 return ConstantExpr::get(getOpcode(), Op0, Op1);
983 /// getWithOperands - This returns the current constant expression with the
984 /// operands replaced with the specified values. The specified operands must
985 /// match count and type with the existing ones.
986 Constant *ConstantExpr::
987 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
988 assert(NumOps == getNumOperands() && "Operand count mismatch!");
989 bool AnyChange = false;
990 for (unsigned i = 0; i != NumOps; ++i) {
991 assert(Ops[i]->getType() == getOperand(i)->getType() &&
992 "Operand type mismatch!");
993 AnyChange |= Ops[i] != getOperand(i);
995 if (!AnyChange) // No operands changed, return self.
996 return const_cast<ConstantExpr*>(this);
998 switch (getOpcode()) {
999 case Instruction::Trunc:
1000 case Instruction::ZExt:
1001 case Instruction::SExt:
1002 case Instruction::FPTrunc:
1003 case Instruction::FPExt:
1004 case Instruction::UIToFP:
1005 case Instruction::SIToFP:
1006 case Instruction::FPToUI:
1007 case Instruction::FPToSI:
1008 case Instruction::PtrToInt:
1009 case Instruction::IntToPtr:
1010 case Instruction::BitCast:
1011 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
1012 case Instruction::Select:
1013 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1014 case Instruction::InsertElement:
1015 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1016 case Instruction::ExtractElement:
1017 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1018 case Instruction::ShuffleVector:
1019 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1020 case Instruction::GetElementPtr:
1021 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
1022 case Instruction::ICmp:
1023 case Instruction::FCmp:
1024 case Instruction::VICmp:
1025 case Instruction::VFCmp:
1026 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1028 assert(getNumOperands() == 2 && "Must be binary operator?");
1029 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
1034 //===----------------------------------------------------------------------===//
1035 // isValueValidForType implementations
1037 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
1038 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1039 if (Ty == Type::Int1Ty)
1040 return Val == 0 || Val == 1;
1042 return true; // always true, has to fit in largest type
1043 uint64_t Max = (1ll << NumBits) - 1;
1047 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
1048 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1049 if (Ty == Type::Int1Ty)
1050 return Val == 0 || Val == 1 || Val == -1;
1052 return true; // always true, has to fit in largest type
1053 int64_t Min = -(1ll << (NumBits-1));
1054 int64_t Max = (1ll << (NumBits-1)) - 1;
1055 return (Val >= Min && Val <= Max);
1058 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1059 // convert modifies in place, so make a copy.
1060 APFloat Val2 = APFloat(Val);
1062 switch (Ty->getTypeID()) {
1064 return false; // These can't be represented as floating point!
1066 // FIXME rounding mode needs to be more flexible
1067 case Type::FloatTyID: {
1068 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1070 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1073 case Type::DoubleTyID: {
1074 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1075 &Val2.getSemantics() == &APFloat::IEEEdouble)
1077 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1080 case Type::X86_FP80TyID:
1081 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1082 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1083 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1084 case Type::FP128TyID:
1085 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1086 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1087 &Val2.getSemantics() == &APFloat::IEEEquad;
1088 case Type::PPC_FP128TyID:
1089 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1090 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1091 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1095 //===----------------------------------------------------------------------===//
1096 // Factory Function Implementation
1099 // The number of operands for each ConstantCreator::create method is
1100 // determined by the ConstantTraits template.
1101 // ConstantCreator - A class that is used to create constants by
1102 // ValueMap*. This class should be partially specialized if there is
1103 // something strange that needs to be done to interface to the ctor for the
1107 template<class ValType>
1108 struct ConstantTraits;
1110 template<typename T, typename Alloc>
1111 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1112 static unsigned uses(const std::vector<T, Alloc>& v) {
1117 template<class ConstantClass, class TypeClass, class ValType>
1118 struct VISIBILITY_HIDDEN ConstantCreator {
1119 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1120 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1124 template<class ConstantClass, class TypeClass>
1125 struct VISIBILITY_HIDDEN ConvertConstantType {
1126 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1127 assert(0 && "This type cannot be converted!\n");
1132 template<class ValType, class TypeClass, class ConstantClass,
1133 bool HasLargeKey = false /*true for arrays and structs*/ >
1134 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1136 typedef std::pair<const Type*, ValType> MapKey;
1137 typedef std::map<MapKey, Constant *> MapTy;
1138 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1139 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1141 /// Map - This is the main map from the element descriptor to the Constants.
1142 /// This is the primary way we avoid creating two of the same shape
1146 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1147 /// from the constants to their element in Map. This is important for
1148 /// removal of constants from the array, which would otherwise have to scan
1149 /// through the map with very large keys.
1150 InverseMapTy InverseMap;
1152 /// AbstractTypeMap - Map for abstract type constants.
1154 AbstractTypeMapTy AbstractTypeMap;
1157 // NOTE: This function is not locked. It is the caller's responsibility
1158 // to enforce proper synchronization.
1159 typename MapTy::iterator map_end() { return Map.end(); }
1161 /// InsertOrGetItem - Return an iterator for the specified element.
1162 /// If the element exists in the map, the returned iterator points to the
1163 /// entry and Exists=true. If not, the iterator points to the newly
1164 /// inserted entry and returns Exists=false. Newly inserted entries have
1165 /// I->second == 0, and should be filled in.
1166 /// NOTE: This function is not locked. It is the caller's responsibility
1167 // to enforce proper synchronization.
1168 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1171 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1172 Exists = !IP.second;
1177 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1179 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1180 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1181 IMI->second->second == CP &&
1182 "InverseMap corrupt!");
1186 typename MapTy::iterator I =
1187 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1189 if (I == Map.end() || I->second != CP) {
1190 // FIXME: This should not use a linear scan. If this gets to be a
1191 // performance problem, someone should look at this.
1192 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1198 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1199 typename MapTy::iterator I) {
1200 ConstantClass* Result =
1201 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1203 assert(Result->getType() == Ty && "Type specified is not correct!");
1204 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1206 if (HasLargeKey) // Remember the reverse mapping if needed.
1207 InverseMap.insert(std::make_pair(Result, I));
1209 // If the type of the constant is abstract, make sure that an entry
1210 // exists for it in the AbstractTypeMap.
1211 if (Ty->isAbstract()) {
1212 typename AbstractTypeMapTy::iterator TI =
1213 AbstractTypeMap.find(Ty);
1215 if (TI == AbstractTypeMap.end()) {
1216 // Add ourselves to the ATU list of the type.
1217 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1219 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1227 /// getOrCreate - Return the specified constant from the map, creating it if
1229 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1230 MapKey Lookup(Ty, V);
1231 ConstantClass* Result = 0;
1233 ConstantsLock->reader_acquire();
1234 typename MapTy::iterator I = Map.find(Lookup);
1235 // Is it in the map?
1237 Result = static_cast<ConstantClass *>(I->second);
1238 ConstantsLock->reader_release();
1241 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1242 I = Map.find(Lookup);
1243 // Is it in the map?
1245 Result = static_cast<ConstantClass *>(I->second);
1247 // If no preexisting value, create one now...
1248 Result = Create(Ty, V, I);
1255 void remove(ConstantClass *CP) {
1256 ConstantsLock->writer_acquire();
1257 typename MapTy::iterator I = FindExistingElement(CP);
1258 assert(I != Map.end() && "Constant not found in constant table!");
1259 assert(I->second == CP && "Didn't find correct element?");
1261 if (HasLargeKey) // Remember the reverse mapping if needed.
1262 InverseMap.erase(CP);
1264 // Now that we found the entry, make sure this isn't the entry that
1265 // the AbstractTypeMap points to.
1266 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1267 if (Ty->isAbstract()) {
1268 assert(AbstractTypeMap.count(Ty) &&
1269 "Abstract type not in AbstractTypeMap?");
1270 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1271 if (ATMEntryIt == I) {
1272 // Yes, we are removing the representative entry for this type.
1273 // See if there are any other entries of the same type.
1274 typename MapTy::iterator TmpIt = ATMEntryIt;
1276 // First check the entry before this one...
1277 if (TmpIt != Map.begin()) {
1279 if (TmpIt->first.first != Ty) // Not the same type, move back...
1283 // If we didn't find the same type, try to move forward...
1284 if (TmpIt == ATMEntryIt) {
1286 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1287 --TmpIt; // No entry afterwards with the same type
1290 // If there is another entry in the map of the same abstract type,
1291 // update the AbstractTypeMap entry now.
1292 if (TmpIt != ATMEntryIt) {
1295 // Otherwise, we are removing the last instance of this type
1296 // from the table. Remove from the ATM, and from user list.
1297 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1298 AbstractTypeMap.erase(Ty);
1305 ConstantsLock->writer_release();
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 /// NOTE: This function is not locked. It is the responsibility of the
1313 /// caller to enforce proper synchronization if using this method.
1314 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1315 // First, remove the old location of the specified constant in the map.
1316 typename MapTy::iterator OldI = FindExistingElement(C);
1317 assert(OldI != Map.end() && "Constant not found in constant table!");
1318 assert(OldI->second == C && "Didn't find correct element?");
1320 // If this constant is the representative element for its abstract type,
1321 // update the AbstractTypeMap so that the representative element is I.
1322 if (C->getType()->isAbstract()) {
1323 typename AbstractTypeMapTy::iterator ATI =
1324 AbstractTypeMap.find(C->getType());
1325 assert(ATI != AbstractTypeMap.end() &&
1326 "Abstract type not in AbstractTypeMap?");
1327 if (ATI->second == OldI)
1331 // Remove the old entry from the map.
1334 // Update the inverse map so that we know that this constant is now
1335 // located at descriptor I.
1337 assert(I->second == C && "Bad inversemap entry!");
1342 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1343 ConstantsLock->writer_acquire();
1344 typename AbstractTypeMapTy::iterator I =
1345 AbstractTypeMap.find(cast<Type>(OldTy));
1347 assert(I != AbstractTypeMap.end() &&
1348 "Abstract type not in AbstractTypeMap?");
1350 // Convert a constant at a time until the last one is gone. The last one
1351 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1352 // eliminated eventually.
1354 ConvertConstantType<ConstantClass,
1355 TypeClass>::convert(
1356 static_cast<ConstantClass *>(I->second->second),
1357 cast<TypeClass>(NewTy));
1359 I = AbstractTypeMap.find(cast<Type>(OldTy));
1360 } while (I != AbstractTypeMap.end());
1362 ConstantsLock->writer_release();
1365 // If the type became concrete without being refined to any other existing
1366 // type, we just remove ourselves from the ATU list.
1367 void typeBecameConcrete(const DerivedType *AbsTy) {
1368 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1369 AbsTy->removeAbstractTypeUser(this);
1373 DOUT << "Constant.cpp: ValueMap\n";
1380 //---- ConstantAggregateZero::get() implementation...
1383 // ConstantAggregateZero does not take extra "value" argument...
1384 template<class ValType>
1385 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1386 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1387 return new ConstantAggregateZero(Ty);
1392 struct ConvertConstantType<ConstantAggregateZero, Type> {
1393 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1394 // Make everyone now use a constant of the new type...
1395 Constant *New = ConstantAggregateZero::get(NewTy);
1396 assert(New != OldC && "Didn't replace constant??");
1397 OldC->uncheckedReplaceAllUsesWith(New);
1398 OldC->destroyConstant(); // This constant is now dead, destroy it.
1403 static ManagedStatic<ValueMap<char, Type,
1404 ConstantAggregateZero> > AggZeroConstants;
1406 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1408 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1409 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1410 "Cannot create an aggregate zero of non-aggregate type!");
1412 // Implicitly locked.
1413 return AggZeroConstants->getOrCreate(Ty, 0);
1416 /// destroyConstant - Remove the constant from the constant table...
1418 void ConstantAggregateZero::destroyConstant() {
1419 // Implicitly locked.
1420 AggZeroConstants->remove(this);
1421 destroyConstantImpl();
1424 //---- ConstantArray::get() implementation...
1428 struct ConvertConstantType<ConstantArray, ArrayType> {
1429 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1430 // Make everyone now use a constant of the new type...
1431 std::vector<Constant*> C;
1432 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1433 C.push_back(cast<Constant>(OldC->getOperand(i)));
1434 Constant *New = ConstantArray::get(NewTy, C);
1435 assert(New != OldC && "Didn't replace constant??");
1436 OldC->uncheckedReplaceAllUsesWith(New);
1437 OldC->destroyConstant(); // This constant is now dead, destroy it.
1442 static std::vector<Constant*> getValType(ConstantArray *CA) {
1443 std::vector<Constant*> Elements;
1444 Elements.reserve(CA->getNumOperands());
1445 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1446 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1450 typedef ValueMap<std::vector<Constant*>, ArrayType,
1451 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1452 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1454 Constant *ConstantArray::get(const ArrayType *Ty,
1455 const std::vector<Constant*> &V) {
1456 // If this is an all-zero array, return a ConstantAggregateZero object
1459 if (!C->isNullValue()) {
1460 // Implicitly locked.
1461 return ArrayConstants->getOrCreate(Ty, V);
1463 for (unsigned i = 1, e = V.size(); i != e; ++i)
1465 // Implicitly locked.
1466 return ArrayConstants->getOrCreate(Ty, V);
1470 return ConstantAggregateZero::get(Ty);
1473 /// destroyConstant - Remove the constant from the constant table...
1475 void ConstantArray::destroyConstant() {
1476 // Implicitly locked.
1477 ArrayConstants->remove(this);
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 for (unsigned i = 0, e = V.size(); i != e; ++i)
1587 if (!V[i]->isNullValue())
1588 // Implicitly locked.
1589 return StructConstants->getOrCreate(Ty, V);
1591 return ConstantAggregateZero::get(Ty);
1594 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1595 std::vector<const Type*> StructEls;
1596 StructEls.reserve(V.size());
1597 for (unsigned i = 0, e = V.size(); i != e; ++i)
1598 StructEls.push_back(V[i]->getType());
1599 return get(StructType::get(StructEls, packed), V);
1602 // destroyConstant - Remove the constant from the constant table...
1604 void ConstantStruct::destroyConstant() {
1605 // Implicitly locked.
1606 StructConstants->remove(this);
1607 destroyConstantImpl();
1610 //---- ConstantVector::get() implementation...
1614 struct ConvertConstantType<ConstantVector, VectorType> {
1615 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1616 // Make everyone now use a constant of the new type...
1617 std::vector<Constant*> C;
1618 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1619 C.push_back(cast<Constant>(OldC->getOperand(i)));
1620 Constant *New = ConstantVector::get(NewTy, C);
1621 assert(New != OldC && "Didn't replace constant??");
1622 OldC->uncheckedReplaceAllUsesWith(New);
1623 OldC->destroyConstant(); // This constant is now dead, destroy it.
1628 static std::vector<Constant*> getValType(ConstantVector *CP) {
1629 std::vector<Constant*> Elements;
1630 Elements.reserve(CP->getNumOperands());
1631 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1632 Elements.push_back(CP->getOperand(i));
1636 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1637 ConstantVector> > VectorConstants;
1639 Constant *ConstantVector::get(const VectorType *Ty,
1640 const std::vector<Constant*> &V) {
1641 assert(!V.empty() && "Vectors can't be empty");
1642 // If this is an all-undef or alll-zero vector, return a
1643 // ConstantAggregateZero or UndefValue.
1645 bool isZero = C->isNullValue();
1646 bool isUndef = isa<UndefValue>(C);
1648 if (isZero || isUndef) {
1649 for (unsigned i = 1, e = V.size(); i != e; ++i)
1651 isZero = isUndef = false;
1657 return ConstantAggregateZero::get(Ty);
1659 return UndefValue::get(Ty);
1661 // Implicitly locked.
1662 return VectorConstants->getOrCreate(Ty, V);
1665 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1666 assert(!V.empty() && "Cannot infer type if V is empty");
1667 return get(VectorType::get(V.front()->getType(),V.size()), V);
1670 // destroyConstant - Remove the constant from the constant table...
1672 void ConstantVector::destroyConstant() {
1673 // Implicitly locked.
1674 VectorConstants->remove(this);
1675 destroyConstantImpl();
1678 /// This function will return true iff every element in this vector constant
1679 /// is set to all ones.
1680 /// @returns true iff this constant's emements are all set to all ones.
1681 /// @brief Determine if the value is all ones.
1682 bool ConstantVector::isAllOnesValue() const {
1683 // Check out first element.
1684 const Constant *Elt = getOperand(0);
1685 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1686 if (!CI || !CI->isAllOnesValue()) return false;
1687 // Then make sure all remaining elements point to the same value.
1688 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1689 if (getOperand(I) != Elt) return false;
1694 /// getSplatValue - If this is a splat constant, where all of the
1695 /// elements have the same value, return that value. Otherwise return null.
1696 Constant *ConstantVector::getSplatValue() {
1697 // Check out first element.
1698 Constant *Elt = getOperand(0);
1699 // Then make sure all remaining elements point to the same value.
1700 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1701 if (getOperand(I) != Elt) return 0;
1705 //---- ConstantPointerNull::get() implementation...
1709 // ConstantPointerNull does not take extra "value" argument...
1710 template<class ValType>
1711 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1712 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1713 return new ConstantPointerNull(Ty);
1718 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1719 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1720 // Make everyone now use a constant of the new type...
1721 Constant *New = ConstantPointerNull::get(NewTy);
1722 assert(New != OldC && "Didn't replace constant??");
1723 OldC->uncheckedReplaceAllUsesWith(New);
1724 OldC->destroyConstant(); // This constant is now dead, destroy it.
1729 static ManagedStatic<ValueMap<char, PointerType,
1730 ConstantPointerNull> > NullPtrConstants;
1732 static char getValType(ConstantPointerNull *) {
1737 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1738 // Implicitly locked.
1739 return NullPtrConstants->getOrCreate(Ty, 0);
1742 // destroyConstant - Remove the constant from the constant table...
1744 void ConstantPointerNull::destroyConstant() {
1745 // Implicitly locked.
1746 NullPtrConstants->remove(this);
1747 destroyConstantImpl();
1751 //---- UndefValue::get() implementation...
1755 // UndefValue does not take extra "value" argument...
1756 template<class ValType>
1757 struct ConstantCreator<UndefValue, Type, ValType> {
1758 static UndefValue *create(const Type *Ty, const ValType &V) {
1759 return new UndefValue(Ty);
1764 struct ConvertConstantType<UndefValue, Type> {
1765 static void convert(UndefValue *OldC, const Type *NewTy) {
1766 // Make everyone now use a constant of the new type.
1767 Constant *New = UndefValue::get(NewTy);
1768 assert(New != OldC && "Didn't replace constant??");
1769 OldC->uncheckedReplaceAllUsesWith(New);
1770 OldC->destroyConstant(); // This constant is now dead, destroy it.
1775 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1777 static char getValType(UndefValue *) {
1782 UndefValue *UndefValue::get(const Type *Ty) {
1783 // Implicitly locked.
1784 return UndefValueConstants->getOrCreate(Ty, 0);
1787 // destroyConstant - Remove the constant from the constant table.
1789 void UndefValue::destroyConstant() {
1790 // Implicitly locked.
1791 UndefValueConstants->remove(this);
1792 destroyConstantImpl();
1795 //---- MDString::get() implementation
1798 MDString::MDString(const char *begin, const char *end)
1799 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1800 StrBegin(begin), StrEnd(end) {}
1802 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1804 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1805 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1806 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1808 MDString *&S = Entry.getValue();
1809 if (!S) S = new MDString(Entry.getKeyData(),
1810 Entry.getKeyData() + Entry.getKeyLength());
1815 void MDString::destroyConstant() {
1816 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1817 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1818 destroyConstantImpl();
1821 //---- MDNode::get() implementation
1824 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1826 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1827 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1828 for (unsigned i = 0; i != NumVals; ++i)
1829 Node.push_back(ElementVH(Vals[i], this));
1832 void MDNode::Profile(FoldingSetNodeID &ID) const {
1833 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1837 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1838 FoldingSetNodeID ID;
1839 for (unsigned i = 0; i != NumVals; ++i)
1840 ID.AddPointer(Vals[i]);
1842 ConstantsLock->reader_acquire();
1844 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1845 ConstantsLock->reader_release();
1848 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1849 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1851 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1852 N = new(0) MDNode(Vals, NumVals);
1853 MDNodeSet->InsertNode(N, InsertPoint);
1859 void MDNode::destroyConstant() {
1860 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1861 MDNodeSet->RemoveNode(this);
1863 destroyConstantImpl();
1866 //---- ConstantExpr::get() implementations...
1871 struct ExprMapKeyType {
1872 typedef SmallVector<unsigned, 4> IndexList;
1874 ExprMapKeyType(unsigned opc,
1875 const std::vector<Constant*> &ops,
1876 unsigned short pred = 0,
1877 const IndexList &inds = IndexList())
1878 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1881 std::vector<Constant*> operands;
1883 bool operator==(const ExprMapKeyType& that) const {
1884 return this->opcode == that.opcode &&
1885 this->predicate == that.predicate &&
1886 this->operands == that.operands &&
1887 this->indices == that.indices;
1889 bool operator<(const ExprMapKeyType & that) const {
1890 return this->opcode < that.opcode ||
1891 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1892 (this->opcode == that.opcode && this->predicate == that.predicate &&
1893 this->operands < that.operands) ||
1894 (this->opcode == that.opcode && this->predicate == that.predicate &&
1895 this->operands == that.operands && this->indices < that.indices);
1898 bool operator!=(const ExprMapKeyType& that) const {
1899 return !(*this == that);
1907 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1908 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1909 unsigned short pred = 0) {
1910 if (Instruction::isCast(V.opcode))
1911 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1912 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1913 V.opcode < Instruction::BinaryOpsEnd))
1914 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1915 if (V.opcode == Instruction::Select)
1916 return new SelectConstantExpr(V.operands[0], V.operands[1],
1918 if (V.opcode == Instruction::ExtractElement)
1919 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1920 if (V.opcode == Instruction::InsertElement)
1921 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1923 if (V.opcode == Instruction::ShuffleVector)
1924 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1926 if (V.opcode == Instruction::InsertValue)
1927 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1929 if (V.opcode == Instruction::ExtractValue)
1930 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1931 if (V.opcode == Instruction::GetElementPtr) {
1932 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1933 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1936 // The compare instructions are weird. We have to encode the predicate
1937 // value and it is combined with the instruction opcode by multiplying
1938 // the opcode by one hundred. We must decode this to get the predicate.
1939 if (V.opcode == Instruction::ICmp)
1940 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1941 V.operands[0], V.operands[1]);
1942 if (V.opcode == Instruction::FCmp)
1943 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1944 V.operands[0], V.operands[1]);
1945 if (V.opcode == Instruction::VICmp)
1946 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1947 V.operands[0], V.operands[1]);
1948 if (V.opcode == Instruction::VFCmp)
1949 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1950 V.operands[0], V.operands[1]);
1951 assert(0 && "Invalid ConstantExpr!");
1957 struct ConvertConstantType<ConstantExpr, Type> {
1958 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1960 switch (OldC->getOpcode()) {
1961 case Instruction::Trunc:
1962 case Instruction::ZExt:
1963 case Instruction::SExt:
1964 case Instruction::FPTrunc:
1965 case Instruction::FPExt:
1966 case Instruction::UIToFP:
1967 case Instruction::SIToFP:
1968 case Instruction::FPToUI:
1969 case Instruction::FPToSI:
1970 case Instruction::PtrToInt:
1971 case Instruction::IntToPtr:
1972 case Instruction::BitCast:
1973 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1976 case Instruction::Select:
1977 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1978 OldC->getOperand(1),
1979 OldC->getOperand(2));
1982 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1983 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1984 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1985 OldC->getOperand(1));
1987 case Instruction::GetElementPtr:
1988 // Make everyone now use a constant of the new type...
1989 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1990 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1991 &Idx[0], Idx.size());
1995 assert(New != OldC && "Didn't replace constant??");
1996 OldC->uncheckedReplaceAllUsesWith(New);
1997 OldC->destroyConstant(); // This constant is now dead, destroy it.
2000 } // end namespace llvm
2003 static ExprMapKeyType getValType(ConstantExpr *CE) {
2004 std::vector<Constant*> Operands;
2005 Operands.reserve(CE->getNumOperands());
2006 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2007 Operands.push_back(cast<Constant>(CE->getOperand(i)));
2008 return ExprMapKeyType(CE->getOpcode(), Operands,
2009 CE->isCompare() ? CE->getPredicate() : 0,
2011 CE->getIndices() : SmallVector<unsigned, 4>());
2014 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
2015 ConstantExpr> > ExprConstants;
2017 /// This is a utility function to handle folding of casts and lookup of the
2018 /// cast in the ExprConstants map. It is used by the various get* methods below.
2019 static inline Constant *getFoldedCast(
2020 Instruction::CastOps opc, Constant *C, const Type *Ty) {
2021 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2022 // Fold a few common cases
2023 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2026 // Look up the constant in the table first to ensure uniqueness
2027 std::vector<Constant*> argVec(1, C);
2028 ExprMapKeyType Key(opc, argVec);
2030 // Implicitly locked.
2031 return ExprConstants->getOrCreate(Ty, Key);
2034 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
2035 Instruction::CastOps opc = Instruction::CastOps(oc);
2036 assert(Instruction::isCast(opc) && "opcode out of range");
2037 assert(C && Ty && "Null arguments to getCast");
2038 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2042 assert(0 && "Invalid cast opcode");
2044 case Instruction::Trunc: return getTrunc(C, Ty);
2045 case Instruction::ZExt: return getZExt(C, Ty);
2046 case Instruction::SExt: return getSExt(C, Ty);
2047 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
2048 case Instruction::FPExt: return getFPExtend(C, Ty);
2049 case Instruction::UIToFP: return getUIToFP(C, Ty);
2050 case Instruction::SIToFP: return getSIToFP(C, Ty);
2051 case Instruction::FPToUI: return getFPToUI(C, Ty);
2052 case Instruction::FPToSI: return getFPToSI(C, Ty);
2053 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
2054 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
2055 case Instruction::BitCast: return getBitCast(C, Ty);
2060 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
2061 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2062 return getCast(Instruction::BitCast, C, Ty);
2063 return getCast(Instruction::ZExt, C, Ty);
2066 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
2067 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2068 return getCast(Instruction::BitCast, C, Ty);
2069 return getCast(Instruction::SExt, C, Ty);
2072 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
2073 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2074 return getCast(Instruction::BitCast, C, Ty);
2075 return getCast(Instruction::Trunc, C, Ty);
2078 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
2079 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2080 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
2082 if (Ty->isInteger())
2083 return getCast(Instruction::PtrToInt, S, Ty);
2084 return getCast(Instruction::BitCast, S, Ty);
2087 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
2089 assert(C->getType()->isIntOrIntVector() &&
2090 Ty->isIntOrIntVector() && "Invalid cast");
2091 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2092 unsigned DstBits = Ty->getScalarSizeInBits();
2093 Instruction::CastOps opcode =
2094 (SrcBits == DstBits ? Instruction::BitCast :
2095 (SrcBits > DstBits ? Instruction::Trunc :
2096 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2097 return getCast(opcode, C, Ty);
2100 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
2101 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2103 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2104 unsigned DstBits = Ty->getScalarSizeInBits();
2105 if (SrcBits == DstBits)
2106 return C; // Avoid a useless cast
2107 Instruction::CastOps opcode =
2108 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2109 return getCast(opcode, C, Ty);
2112 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
2114 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2115 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2117 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2118 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2119 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2120 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2121 "SrcTy must be larger than DestTy for Trunc!");
2123 return getFoldedCast(Instruction::Trunc, C, Ty);
2126 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
2128 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2129 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2131 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2132 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2133 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2134 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2135 "SrcTy must be smaller than DestTy for SExt!");
2137 return getFoldedCast(Instruction::SExt, C, Ty);
2140 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
2142 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2143 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2145 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2146 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2147 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2148 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2149 "SrcTy must be smaller than DestTy for ZExt!");
2151 return getFoldedCast(Instruction::ZExt, C, Ty);
2154 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
2156 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2157 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2159 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2160 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2161 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2162 "This is an illegal floating point truncation!");
2163 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2166 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2168 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2169 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2171 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2172 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2173 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2174 "This is an illegal floating point extension!");
2175 return getFoldedCast(Instruction::FPExt, C, Ty);
2178 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2180 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2181 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2183 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2184 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2185 "This is an illegal uint to floating point cast!");
2186 return getFoldedCast(Instruction::UIToFP, C, Ty);
2189 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2191 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2192 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2194 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2195 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2196 "This is an illegal sint to floating point cast!");
2197 return getFoldedCast(Instruction::SIToFP, C, Ty);
2200 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2202 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2203 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2205 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2206 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2207 "This is an illegal floating point to uint cast!");
2208 return getFoldedCast(Instruction::FPToUI, C, Ty);
2211 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2213 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2214 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2216 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2217 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2218 "This is an illegal floating point to sint cast!");
2219 return getFoldedCast(Instruction::FPToSI, C, Ty);
2222 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2223 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2224 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2225 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2228 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2229 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2230 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2231 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2234 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2235 // BitCast implies a no-op cast of type only. No bits change. However, you
2236 // can't cast pointers to anything but pointers.
2238 const Type *SrcTy = C->getType();
2239 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2240 "BitCast cannot cast pointer to non-pointer and vice versa");
2242 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2243 // or nonptr->ptr). For all the other types, the cast is okay if source and
2244 // destination bit widths are identical.
2245 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2246 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2248 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2250 // It is common to ask for a bitcast of a value to its own type, handle this
2252 if (C->getType() == DstTy) return C;
2254 return getFoldedCast(Instruction::BitCast, C, DstTy);
2257 Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2258 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2259 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2260 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2261 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2262 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2263 Constant *Indices[2] = { Zero, One };
2264 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2265 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2268 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
2269 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2270 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2272 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2273 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2276 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2277 Constant *C1, Constant *C2) {
2278 // Check the operands for consistency first
2279 assert(Opcode >= Instruction::BinaryOpsBegin &&
2280 Opcode < Instruction::BinaryOpsEnd &&
2281 "Invalid opcode in binary constant expression");
2282 assert(C1->getType() == C2->getType() &&
2283 "Operand types in binary constant expression should match");
2285 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2286 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2287 return FC; // Fold a few common cases...
2289 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2290 ExprMapKeyType Key(Opcode, argVec);
2292 // Implicitly locked.
2293 return ExprConstants->getOrCreate(ReqTy, Key);
2296 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2297 Constant *C1, Constant *C2) {
2298 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
2299 switch (predicate) {
2300 default: assert(0 && "Invalid CmpInst predicate");
2301 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2302 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2303 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2304 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2305 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2306 case CmpInst::FCMP_TRUE:
2307 return isVectorType ? getVFCmp(predicate, C1, C2)
2308 : getFCmp(predicate, C1, C2);
2309 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2310 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2311 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2312 case CmpInst::ICMP_SLE:
2313 return isVectorType ? getVICmp(predicate, C1, C2)
2314 : getICmp(predicate, C1, C2);
2318 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2319 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2320 if (C1->getType()->isFPOrFPVector()) {
2321 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2322 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2323 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2327 case Instruction::Add:
2328 case Instruction::Sub:
2329 case Instruction::Mul:
2330 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2331 assert(C1->getType()->isIntOrIntVector() &&
2332 "Tried to create an integer operation on a non-integer type!");
2334 case Instruction::FAdd:
2335 case Instruction::FSub:
2336 case Instruction::FMul:
2337 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2338 assert(C1->getType()->isFPOrFPVector() &&
2339 "Tried to create a floating-point operation on a "
2340 "non-floating-point type!");
2342 case Instruction::UDiv:
2343 case Instruction::SDiv:
2344 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2345 assert(C1->getType()->isIntOrIntVector() &&
2346 "Tried to create an arithmetic operation on a non-arithmetic type!");
2348 case Instruction::FDiv:
2349 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2350 assert(C1->getType()->isFPOrFPVector() &&
2351 "Tried to create an arithmetic operation on a non-arithmetic type!");
2353 case Instruction::URem:
2354 case Instruction::SRem:
2355 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2356 assert(C1->getType()->isIntOrIntVector() &&
2357 "Tried to create an arithmetic operation on a non-arithmetic type!");
2359 case Instruction::FRem:
2360 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2361 assert(C1->getType()->isFPOrFPVector() &&
2362 "Tried to create an arithmetic operation on a non-arithmetic type!");
2364 case Instruction::And:
2365 case Instruction::Or:
2366 case Instruction::Xor:
2367 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2368 assert(C1->getType()->isIntOrIntVector() &&
2369 "Tried to create a logical operation on a non-integral type!");
2371 case Instruction::Shl:
2372 case Instruction::LShr:
2373 case Instruction::AShr:
2374 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2375 assert(C1->getType()->isIntOrIntVector() &&
2376 "Tried to create a shift operation on a non-integer type!");
2383 return getTy(C1->getType(), Opcode, C1, C2);
2386 Constant *ConstantExpr::getCompare(unsigned short pred,
2387 Constant *C1, Constant *C2) {
2388 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2389 return getCompareTy(pred, C1, C2);
2392 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2393 Constant *V1, Constant *V2) {
2394 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2396 if (ReqTy == V1->getType())
2397 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2398 return SC; // Fold common cases
2400 std::vector<Constant*> argVec(3, C);
2403 ExprMapKeyType Key(Instruction::Select, argVec);
2405 // Implicitly locked.
2406 return ExprConstants->getOrCreate(ReqTy, Key);
2409 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2412 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2414 cast<PointerType>(ReqTy)->getElementType() &&
2415 "GEP indices invalid!");
2417 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2418 return FC; // Fold a few common cases...
2420 assert(isa<PointerType>(C->getType()) &&
2421 "Non-pointer type for constant GetElementPtr expression");
2422 // Look up the constant in the table first to ensure uniqueness
2423 std::vector<Constant*> ArgVec;
2424 ArgVec.reserve(NumIdx+1);
2425 ArgVec.push_back(C);
2426 for (unsigned i = 0; i != NumIdx; ++i)
2427 ArgVec.push_back(cast<Constant>(Idxs[i]));
2428 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2430 // Implicitly locked.
2431 return ExprConstants->getOrCreate(ReqTy, Key);
2434 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2436 // Get the result type of the getelementptr!
2438 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2439 assert(Ty && "GEP indices invalid!");
2440 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2441 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2444 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2446 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2451 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2452 assert(LHS->getType() == RHS->getType());
2453 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2454 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2456 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2457 return FC; // Fold a few common cases...
2459 // Look up the constant in the table first to ensure uniqueness
2460 std::vector<Constant*> ArgVec;
2461 ArgVec.push_back(LHS);
2462 ArgVec.push_back(RHS);
2463 // Get the key type with both the opcode and predicate
2464 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2466 // Implicitly locked.
2467 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2471 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2472 assert(LHS->getType() == RHS->getType());
2473 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2475 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2476 return FC; // Fold a few common cases...
2478 // Look up the constant in the table first to ensure uniqueness
2479 std::vector<Constant*> ArgVec;
2480 ArgVec.push_back(LHS);
2481 ArgVec.push_back(RHS);
2482 // Get the key type with both the opcode and predicate
2483 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2485 // Implicitly locked.
2486 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2490 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2491 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
2492 "Tried to create vicmp operation on non-vector type!");
2493 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2494 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2496 const VectorType *VTy = cast<VectorType>(LHS->getType());
2497 const Type *EltTy = VTy->getElementType();
2498 unsigned NumElts = VTy->getNumElements();
2500 // See if we can fold the element-wise comparison of the LHS and RHS.
2501 SmallVector<Constant *, 16> LHSElts, RHSElts;
2502 LHS->getVectorElements(LHSElts);
2503 RHS->getVectorElements(RHSElts);
2505 if (!LHSElts.empty() && !RHSElts.empty()) {
2506 SmallVector<Constant *, 16> Elts;
2507 for (unsigned i = 0; i != NumElts; ++i) {
2508 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2510 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2511 if (FCI->getZExtValue())
2512 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2514 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2515 } else if (FC && isa<UndefValue>(FC)) {
2516 Elts.push_back(UndefValue::get(EltTy));
2521 if (Elts.size() == NumElts)
2522 return ConstantVector::get(&Elts[0], Elts.size());
2525 // Look up the constant in the table first to ensure uniqueness
2526 std::vector<Constant*> ArgVec;
2527 ArgVec.push_back(LHS);
2528 ArgVec.push_back(RHS);
2529 // Get the key type with both the opcode and predicate
2530 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2532 // Implicitly locked.
2533 return ExprConstants->getOrCreate(LHS->getType(), Key);
2537 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2538 assert(isa<VectorType>(LHS->getType()) &&
2539 "Tried to create vfcmp operation on non-vector type!");
2540 assert(LHS->getType() == RHS->getType());
2541 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2543 const VectorType *VTy = cast<VectorType>(LHS->getType());
2544 unsigned NumElts = VTy->getNumElements();
2545 const Type *EltTy = VTy->getElementType();
2546 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2547 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2549 // See if we can fold the element-wise comparison of the LHS and RHS.
2550 SmallVector<Constant *, 16> LHSElts, RHSElts;
2551 LHS->getVectorElements(LHSElts);
2552 RHS->getVectorElements(RHSElts);
2554 if (!LHSElts.empty() && !RHSElts.empty()) {
2555 SmallVector<Constant *, 16> Elts;
2556 for (unsigned i = 0; i != NumElts; ++i) {
2557 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2559 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2560 if (FCI->getZExtValue())
2561 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2563 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2564 } else if (FC && isa<UndefValue>(FC)) {
2565 Elts.push_back(UndefValue::get(REltTy));
2570 if (Elts.size() == NumElts)
2571 return ConstantVector::get(&Elts[0], Elts.size());
2574 // Look up the constant in the table first to ensure uniqueness
2575 std::vector<Constant*> ArgVec;
2576 ArgVec.push_back(LHS);
2577 ArgVec.push_back(RHS);
2578 // Get the key type with both the opcode and predicate
2579 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2581 // Implicitly locked.
2582 return ExprConstants->getOrCreate(ResultTy, Key);
2585 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2587 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2588 return FC; // Fold a few common cases...
2589 // Look up the constant in the table first to ensure uniqueness
2590 std::vector<Constant*> ArgVec(1, Val);
2591 ArgVec.push_back(Idx);
2592 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2594 // Implicitly locked.
2595 return ExprConstants->getOrCreate(ReqTy, Key);
2598 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2599 assert(isa<VectorType>(Val->getType()) &&
2600 "Tried to create extractelement operation on non-vector type!");
2601 assert(Idx->getType() == Type::Int32Ty &&
2602 "Extractelement index must be i32 type!");
2603 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2607 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2608 Constant *Elt, Constant *Idx) {
2609 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2610 return FC; // Fold a few common cases...
2611 // Look up the constant in the table first to ensure uniqueness
2612 std::vector<Constant*> ArgVec(1, Val);
2613 ArgVec.push_back(Elt);
2614 ArgVec.push_back(Idx);
2615 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2617 // Implicitly locked.
2618 return ExprConstants->getOrCreate(ReqTy, Key);
2621 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2623 assert(isa<VectorType>(Val->getType()) &&
2624 "Tried to create insertelement operation on non-vector type!");
2625 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2626 && "Insertelement types must match!");
2627 assert(Idx->getType() == Type::Int32Ty &&
2628 "Insertelement index must be i32 type!");
2629 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2632 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2633 Constant *V2, Constant *Mask) {
2634 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2635 return FC; // Fold a few common cases...
2636 // Look up the constant in the table first to ensure uniqueness
2637 std::vector<Constant*> ArgVec(1, V1);
2638 ArgVec.push_back(V2);
2639 ArgVec.push_back(Mask);
2640 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2642 // Implicitly locked.
2643 return ExprConstants->getOrCreate(ReqTy, Key);
2646 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2648 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2649 "Invalid shuffle vector constant expr operands!");
2651 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2652 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2653 const Type *ShufTy = VectorType::get(EltTy, NElts);
2654 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2657 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2659 const unsigned *Idxs, unsigned NumIdx) {
2660 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2661 Idxs+NumIdx) == Val->getType() &&
2662 "insertvalue indices invalid!");
2663 assert(Agg->getType() == ReqTy &&
2664 "insertvalue type invalid!");
2665 assert(Agg->getType()->isFirstClassType() &&
2666 "Non-first-class type for constant InsertValue expression");
2667 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2668 assert(FC && "InsertValue constant expr couldn't be folded!");
2672 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2673 const unsigned *IdxList, unsigned NumIdx) {
2674 assert(Agg->getType()->isFirstClassType() &&
2675 "Tried to create insertelement operation on non-first-class type!");
2677 const Type *ReqTy = Agg->getType();
2680 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2682 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2683 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2686 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2687 const unsigned *Idxs, unsigned NumIdx) {
2688 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2689 Idxs+NumIdx) == ReqTy &&
2690 "extractvalue indices invalid!");
2691 assert(Agg->getType()->isFirstClassType() &&
2692 "Non-first-class type for constant extractvalue expression");
2693 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2694 assert(FC && "ExtractValue constant expr couldn't be folded!");
2698 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2699 const unsigned *IdxList, unsigned NumIdx) {
2700 assert(Agg->getType()->isFirstClassType() &&
2701 "Tried to create extractelement operation on non-first-class type!");
2704 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2705 assert(ReqTy && "extractvalue indices invalid!");
2706 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2709 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2710 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2711 if (PTy->getElementType()->isFloatingPoint()) {
2712 std::vector<Constant*> zeros(PTy->getNumElements(),
2713 ConstantFP::getNegativeZero(PTy->getElementType()));
2714 return ConstantVector::get(PTy, zeros);
2717 if (Ty->isFloatingPoint())
2718 return ConstantFP::getNegativeZero(Ty);
2720 return Constant::getNullValue(Ty);
2723 // destroyConstant - Remove the constant from the constant table...
2725 void ConstantExpr::destroyConstant() {
2726 // Implicitly locked.
2727 ExprConstants->remove(this);
2728 destroyConstantImpl();
2731 const char *ConstantExpr::getOpcodeName() const {
2732 return Instruction::getOpcodeName(getOpcode());
2735 //===----------------------------------------------------------------------===//
2736 // replaceUsesOfWithOnConstant implementations
2738 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2739 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2742 /// Note that we intentionally replace all uses of From with To here. Consider
2743 /// a large array that uses 'From' 1000 times. By handling this case all here,
2744 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2745 /// single invocation handles all 1000 uses. Handling them one at a time would
2746 /// work, but would be really slow because it would have to unique each updated
2748 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2750 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2751 Constant *ToC = cast<Constant>(To);
2753 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2754 Lookup.first.first = getType();
2755 Lookup.second = this;
2757 std::vector<Constant*> &Values = Lookup.first.second;
2758 Values.reserve(getNumOperands()); // Build replacement array.
2760 // Fill values with the modified operands of the constant array. Also,
2761 // compute whether this turns into an all-zeros array.
2762 bool isAllZeros = false;
2763 unsigned NumUpdated = 0;
2764 if (!ToC->isNullValue()) {
2765 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2766 Constant *Val = cast<Constant>(O->get());
2771 Values.push_back(Val);
2775 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2776 Constant *Val = cast<Constant>(O->get());
2781 Values.push_back(Val);
2782 if (isAllZeros) isAllZeros = Val->isNullValue();
2786 Constant *Replacement = 0;
2788 Replacement = ConstantAggregateZero::get(getType());
2790 // Check to see if we have this array type already.
2791 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
2793 ArrayConstantsTy::MapTy::iterator I =
2794 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2797 Replacement = I->second;
2799 // Okay, the new shape doesn't exist in the system yet. Instead of
2800 // creating a new constant array, inserting it, replaceallusesof'ing the
2801 // old with the new, then deleting the old... just update the current one
2803 ArrayConstants->MoveConstantToNewSlot(this, I);
2805 // Update to the new value. Optimize for the case when we have a single
2806 // operand that we're changing, but handle bulk updates efficiently.
2807 if (NumUpdated == 1) {
2808 unsigned OperandToUpdate = U-OperandList;
2809 assert(getOperand(OperandToUpdate) == From &&
2810 "ReplaceAllUsesWith broken!");
2811 setOperand(OperandToUpdate, ToC);
2813 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2814 if (getOperand(i) == From)
2821 // Otherwise, I do need to replace this with an existing value.
2822 assert(Replacement != this && "I didn't contain From!");
2824 // Everyone using this now uses the replacement.
2825 uncheckedReplaceAllUsesWith(Replacement);
2827 // Delete the old constant!
2831 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2833 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2834 Constant *ToC = cast<Constant>(To);
2836 unsigned OperandToUpdate = U-OperandList;
2837 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2839 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2840 Lookup.first.first = getType();
2841 Lookup.second = this;
2842 std::vector<Constant*> &Values = Lookup.first.second;
2843 Values.reserve(getNumOperands()); // Build replacement struct.
2846 // Fill values with the modified operands of the constant struct. Also,
2847 // compute whether this turns into an all-zeros struct.
2848 bool isAllZeros = false;
2849 if (!ToC->isNullValue()) {
2850 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2851 Values.push_back(cast<Constant>(O->get()));
2854 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2855 Constant *Val = cast<Constant>(O->get());
2856 Values.push_back(Val);
2857 if (isAllZeros) isAllZeros = Val->isNullValue();
2860 Values[OperandToUpdate] = ToC;
2862 Constant *Replacement = 0;
2864 Replacement = ConstantAggregateZero::get(getType());
2866 // Check to see if we have this array type already.
2867 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
2869 StructConstantsTy::MapTy::iterator I =
2870 StructConstants->InsertOrGetItem(Lookup, Exists);
2873 Replacement = I->second;
2875 // Okay, the new shape doesn't exist in the system yet. Instead of
2876 // creating a new constant struct, inserting it, replaceallusesof'ing the
2877 // old with the new, then deleting the old... just update the current one
2879 StructConstants->MoveConstantToNewSlot(this, I);
2881 // Update to the new value.
2882 setOperand(OperandToUpdate, ToC);
2887 assert(Replacement != this && "I didn't contain From!");
2889 // Everyone using this now uses the replacement.
2890 uncheckedReplaceAllUsesWith(Replacement);
2892 // Delete the old constant!
2896 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2898 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2900 std::vector<Constant*> Values;
2901 Values.reserve(getNumOperands()); // Build replacement array...
2902 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2903 Constant *Val = getOperand(i);
2904 if (Val == From) Val = cast<Constant>(To);
2905 Values.push_back(Val);
2908 Constant *Replacement = ConstantVector::get(getType(), Values);
2909 assert(Replacement != this && "I didn't contain From!");
2911 // Everyone using this now uses the replacement.
2912 uncheckedReplaceAllUsesWith(Replacement);
2914 // Delete the old constant!
2918 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2920 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2921 Constant *To = cast<Constant>(ToV);
2923 Constant *Replacement = 0;
2924 if (getOpcode() == Instruction::GetElementPtr) {
2925 SmallVector<Constant*, 8> Indices;
2926 Constant *Pointer = getOperand(0);
2927 Indices.reserve(getNumOperands()-1);
2928 if (Pointer == From) Pointer = To;
2930 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2931 Constant *Val = getOperand(i);
2932 if (Val == From) Val = To;
2933 Indices.push_back(Val);
2935 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2936 &Indices[0], Indices.size());
2937 } else if (getOpcode() == Instruction::ExtractValue) {
2938 Constant *Agg = getOperand(0);
2939 if (Agg == From) Agg = To;
2941 const SmallVector<unsigned, 4> &Indices = getIndices();
2942 Replacement = ConstantExpr::getExtractValue(Agg,
2943 &Indices[0], Indices.size());
2944 } else if (getOpcode() == Instruction::InsertValue) {
2945 Constant *Agg = getOperand(0);
2946 Constant *Val = getOperand(1);
2947 if (Agg == From) Agg = To;
2948 if (Val == From) Val = To;
2950 const SmallVector<unsigned, 4> &Indices = getIndices();
2951 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2952 &Indices[0], Indices.size());
2953 } else if (isCast()) {
2954 assert(getOperand(0) == From && "Cast only has one use!");
2955 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2956 } else if (getOpcode() == Instruction::Select) {
2957 Constant *C1 = getOperand(0);
2958 Constant *C2 = getOperand(1);
2959 Constant *C3 = getOperand(2);
2960 if (C1 == From) C1 = To;
2961 if (C2 == From) C2 = To;
2962 if (C3 == From) C3 = To;
2963 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2964 } else if (getOpcode() == Instruction::ExtractElement) {
2965 Constant *C1 = getOperand(0);
2966 Constant *C2 = getOperand(1);
2967 if (C1 == From) C1 = To;
2968 if (C2 == From) C2 = To;
2969 Replacement = ConstantExpr::getExtractElement(C1, C2);
2970 } else if (getOpcode() == Instruction::InsertElement) {
2971 Constant *C1 = getOperand(0);
2972 Constant *C2 = getOperand(1);
2973 Constant *C3 = getOperand(1);
2974 if (C1 == From) C1 = To;
2975 if (C2 == From) C2 = To;
2976 if (C3 == From) C3 = To;
2977 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2978 } else if (getOpcode() == Instruction::ShuffleVector) {
2979 Constant *C1 = getOperand(0);
2980 Constant *C2 = getOperand(1);
2981 Constant *C3 = getOperand(2);
2982 if (C1 == From) C1 = To;
2983 if (C2 == From) C2 = To;
2984 if (C3 == From) C3 = To;
2985 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2986 } else if (isCompare()) {
2987 Constant *C1 = getOperand(0);
2988 Constant *C2 = getOperand(1);
2989 if (C1 == From) C1 = To;
2990 if (C2 == From) C2 = To;
2991 if (getOpcode() == Instruction::ICmp)
2992 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2993 else if (getOpcode() == Instruction::FCmp)
2994 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2995 else if (getOpcode() == Instruction::VICmp)
2996 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2998 assert(getOpcode() == Instruction::VFCmp);
2999 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
3001 } else if (getNumOperands() == 2) {
3002 Constant *C1 = getOperand(0);
3003 Constant *C2 = getOperand(1);
3004 if (C1 == From) C1 = To;
3005 if (C2 == From) C2 = To;
3006 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
3008 assert(0 && "Unknown ConstantExpr type!");
3012 assert(Replacement != this && "I didn't contain From!");
3014 // Everyone using this now uses the replacement.
3015 uncheckedReplaceAllUsesWith(Replacement);
3017 // Delete the old constant!
3021 void MDNode::replaceElement(Value *From, Value *To) {
3022 SmallVector<Value*, 4> Values;
3023 Values.reserve(getNumElements()); // Build replacement array...
3024 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3025 Value *Val = getElement(i);
3026 if (Val == From) Val = To;
3027 Values.push_back(Val);
3030 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
3031 assert(Replacement != this && "I didn't contain From!");
3033 uncheckedReplaceAllUsesWith(Replacement);