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/Mutex.h"
29 #include "llvm/System/RWMutex.h"
30 #include "llvm/System/Threading.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallVector.h"
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 // Becomes a no-op when multithreading is disabled.
42 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
44 void Constant::destroyConstantImpl() {
45 // When a Constant is destroyed, there may be lingering
46 // references to the constant by other constants in the constant pool. These
47 // constants are implicitly dependent on the module that is being deleted,
48 // but they don't know that. Because we only find out when the CPV is
49 // deleted, we must now notify all of our users (that should only be
50 // Constants) that they are, in fact, invalid now and should be deleted.
52 while (!use_empty()) {
53 Value *V = use_back();
54 #ifndef NDEBUG // Only in -g mode...
55 if (!isa<Constant>(V))
56 DOUT << "While deleting: " << *this
57 << "\n\nUse still stuck around after Def is destroyed: "
60 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
61 Constant *CV = cast<Constant>(V);
62 CV->destroyConstant();
64 // The constant should remove itself from our use list...
65 assert((use_empty() || use_back() != V) && "Constant not removed!");
68 // Value has no outstanding references it is safe to delete it now...
72 /// canTrap - Return true if evaluation of this constant could trap. This is
73 /// true for things like constant expressions that could divide by zero.
74 bool Constant::canTrap() const {
75 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
76 // The only thing that could possibly trap are constant exprs.
77 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
78 if (!CE) return false;
80 // ConstantExpr traps if any operands can trap.
81 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
82 if (getOperand(i)->canTrap())
85 // Otherwise, only specific operations can trap.
86 switch (CE->getOpcode()) {
89 case Instruction::UDiv:
90 case Instruction::SDiv:
91 case Instruction::FDiv:
92 case Instruction::URem:
93 case Instruction::SRem:
94 case Instruction::FRem:
95 // Div and rem can trap if the RHS is not known to be non-zero.
96 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
102 /// ContainsRelocations - Return true if the constant value contains relocations
103 /// which cannot be resolved at compile time. Kind argument is used to filter
104 /// only 'interesting' sorts of relocations.
105 bool Constant::ContainsRelocations(unsigned Kind) const {
106 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
107 bool isLocal = GV->hasLocalLinkage();
108 if ((Kind & Reloc::Local) && isLocal) {
109 // Global has local linkage and 'local' kind of relocations are
114 if ((Kind & Reloc::Global) && !isLocal) {
115 // Global has non-local linkage and 'global' kind of relocations are
123 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
124 if (getOperand(i)->ContainsRelocations(Kind))
130 // Static constructor to create a '0' constant of arbitrary type...
131 Constant *Constant::getNullValue(const Type *Ty) {
132 static uint64_t zero[2] = {0, 0};
133 switch (Ty->getTypeID()) {
134 case Type::IntegerTyID:
135 return ConstantInt::get(Ty, 0);
136 case Type::FloatTyID:
137 return ConstantFP::get(APFloat(APInt(32, 0)));
138 case Type::DoubleTyID:
139 return ConstantFP::get(APFloat(APInt(64, 0)));
140 case Type::X86_FP80TyID:
141 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
142 case Type::FP128TyID:
143 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
144 case Type::PPC_FP128TyID:
145 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
146 case Type::PointerTyID:
147 return ConstantPointerNull::get(cast<PointerType>(Ty));
148 case Type::StructTyID:
149 case Type::ArrayTyID:
150 case Type::VectorTyID:
151 return ConstantAggregateZero::get(Ty);
153 // Function, Label, or Opaque type?
154 assert(!"Cannot create a null constant of that type!");
159 Constant *Constant::getAllOnesValue(const Type *Ty) {
160 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
161 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
162 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
165 // Static constructor to create an integral constant with all bits set
166 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
167 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
168 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
172 /// @returns the value for a vector integer constant of the given type that
173 /// has all its bits set to true.
174 /// @brief Get the all ones value
175 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
176 std::vector<Constant*> Elts;
177 Elts.resize(Ty->getNumElements(),
178 ConstantInt::getAllOnesValue(Ty->getElementType()));
179 assert(Elts[0] && "Not a vector integer type!");
180 return cast<ConstantVector>(ConstantVector::get(Elts));
184 /// getVectorElements - This method, which is only valid on constant of vector
185 /// type, returns the elements of the vector in the specified smallvector.
186 /// This handles breaking down a vector undef into undef elements, etc. For
187 /// constant exprs and other cases we can't handle, we return an empty vector.
188 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
189 assert(isa<VectorType>(getType()) && "Not a vector constant!");
191 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
192 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
193 Elts.push_back(CV->getOperand(i));
197 const VectorType *VT = cast<VectorType>(getType());
198 if (isa<ConstantAggregateZero>(this)) {
199 Elts.assign(VT->getNumElements(),
200 Constant::getNullValue(VT->getElementType()));
204 if (isa<UndefValue>(this)) {
205 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
209 // Unknown type, must be constant expr etc.
214 //===----------------------------------------------------------------------===//
216 //===----------------------------------------------------------------------===//
218 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
219 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
220 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
223 ConstantInt *ConstantInt::TheTrueVal = 0;
224 ConstantInt *ConstantInt::TheFalseVal = 0;
227 void CleanupTrueFalse(void *) {
228 ConstantInt::ResetTrueFalse();
232 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
234 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
235 assert(TheTrueVal == 0 && TheFalseVal == 0);
236 TheTrueVal = get(Type::Int1Ty, 1);
237 TheFalseVal = get(Type::Int1Ty, 0);
239 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
240 TrueFalseCleanup.Register();
242 return WhichOne ? TheTrueVal : TheFalseVal;
247 struct DenseMapAPIntKeyInfo {
251 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
252 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
253 bool operator==(const KeyTy& that) const {
254 return type == that.type && this->val == that.val;
256 bool operator!=(const KeyTy& that) const {
257 return !this->operator==(that);
260 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
261 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
262 static unsigned getHashValue(const KeyTy &Key) {
263 return DenseMapInfo<void*>::getHashValue(Key.type) ^
264 Key.val.getHashValue();
266 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
269 static bool isPod() { return false; }
274 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
275 DenseMapAPIntKeyInfo> IntMapTy;
276 static ManagedStatic<IntMapTy> IntConstants;
278 ConstantInt *ConstantInt::get(const IntegerType *Ty,
279 uint64_t V, bool isSigned) {
280 return get(APInt(Ty->getBitWidth(), V, isSigned));
283 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
284 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
286 // For vectors, broadcast the value.
287 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
289 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
294 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
295 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
296 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
297 // compare APInt's of different widths, which would violate an APInt class
298 // invariant which generates an assertion.
299 ConstantInt *ConstantInt::get(const APInt& V) {
300 // Get the corresponding integer type for the bit width of the value.
301 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
302 // get an existing value or the insertion position
303 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
305 ConstantsLock->reader_acquire();
306 ConstantInt *&Slot = (*IntConstants)[Key];
307 ConstantsLock->reader_release();
310 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
311 ConstantInt *&NewSlot = (*IntConstants)[Key];
313 NewSlot = new ConstantInt(ITy, V);
322 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
323 ConstantInt *C = ConstantInt::get(V);
324 assert(C->getType() == Ty->getScalarType() &&
325 "ConstantInt type doesn't match the type implied by its value!");
327 // For vectors, broadcast the value.
328 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
330 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
335 //===----------------------------------------------------------------------===//
337 //===----------------------------------------------------------------------===//
339 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
340 if (Ty == Type::FloatTy)
341 return &APFloat::IEEEsingle;
342 if (Ty == Type::DoubleTy)
343 return &APFloat::IEEEdouble;
344 if (Ty == Type::X86_FP80Ty)
345 return &APFloat::x87DoubleExtended;
346 else if (Ty == Type::FP128Ty)
347 return &APFloat::IEEEquad;
349 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
350 return &APFloat::PPCDoubleDouble;
353 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
354 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
355 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
359 bool ConstantFP::isNullValue() const {
360 return Val.isZero() && !Val.isNegative();
363 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
364 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
366 return ConstantFP::get(apf);
369 bool ConstantFP::isExactlyValue(const APFloat& V) const {
370 return Val.bitwiseIsEqual(V);
374 struct DenseMapAPFloatKeyInfo {
377 KeyTy(const APFloat& V) : val(V){}
378 KeyTy(const KeyTy& that) : val(that.val) {}
379 bool operator==(const KeyTy& that) const {
380 return this->val.bitwiseIsEqual(that.val);
382 bool operator!=(const KeyTy& that) const {
383 return !this->operator==(that);
386 static inline KeyTy getEmptyKey() {
387 return KeyTy(APFloat(APFloat::Bogus,1));
389 static inline KeyTy getTombstoneKey() {
390 return KeyTy(APFloat(APFloat::Bogus,2));
392 static unsigned getHashValue(const KeyTy &Key) {
393 return Key.val.getHashValue();
395 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
398 static bool isPod() { return false; }
402 //---- ConstantFP::get() implementation...
404 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
405 DenseMapAPFloatKeyInfo> FPMapTy;
407 static ManagedStatic<FPMapTy> FPConstants;
409 ConstantFP *ConstantFP::get(const APFloat &V) {
410 DenseMapAPFloatKeyInfo::KeyTy Key(V);
412 ConstantsLock->reader_acquire();
413 ConstantFP *&Slot = (*FPConstants)[Key];
414 ConstantsLock->reader_release();
417 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
418 ConstantFP *&NewSlot = (*FPConstants)[Key];
421 if (&V.getSemantics() == &APFloat::IEEEsingle)
423 else if (&V.getSemantics() == &APFloat::IEEEdouble)
425 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
426 Ty = Type::X86_FP80Ty;
427 else if (&V.getSemantics() == &APFloat::IEEEquad)
430 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
431 "Unknown FP format");
432 Ty = Type::PPC_FP128Ty;
434 NewSlot = new ConstantFP(Ty, V);
443 /// get() - This returns a constant fp for the specified value in the
444 /// specified type. This should only be used for simple constant values like
445 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
446 Constant *ConstantFP::get(const Type *Ty, double V) {
449 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
450 APFloat::rmNearestTiesToEven, &ignored);
451 Constant *C = get(FV);
453 // For vectors, broadcast the value.
454 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
456 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
461 //===----------------------------------------------------------------------===//
462 // ConstantXXX Classes
463 //===----------------------------------------------------------------------===//
466 ConstantArray::ConstantArray(const ArrayType *T,
467 const std::vector<Constant*> &V)
468 : Constant(T, ConstantArrayVal,
469 OperandTraits<ConstantArray>::op_end(this) - V.size(),
471 assert(V.size() == T->getNumElements() &&
472 "Invalid initializer vector for constant array");
473 Use *OL = OperandList;
474 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
477 assert((C->getType() == T->getElementType() ||
479 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
480 "Initializer for array element doesn't match array element type!");
486 ConstantStruct::ConstantStruct(const StructType *T,
487 const std::vector<Constant*> &V)
488 : Constant(T, ConstantStructVal,
489 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
491 assert(V.size() == T->getNumElements() &&
492 "Invalid initializer vector for constant structure");
493 Use *OL = OperandList;
494 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
497 assert((C->getType() == T->getElementType(I-V.begin()) ||
498 ((T->getElementType(I-V.begin())->isAbstract() ||
499 C->getType()->isAbstract()) &&
500 T->getElementType(I-V.begin())->getTypeID() ==
501 C->getType()->getTypeID())) &&
502 "Initializer for struct element doesn't match struct element type!");
508 ConstantVector::ConstantVector(const VectorType *T,
509 const std::vector<Constant*> &V)
510 : Constant(T, ConstantVectorVal,
511 OperandTraits<ConstantVector>::op_end(this) - V.size(),
513 Use *OL = OperandList;
514 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
517 assert((C->getType() == T->getElementType() ||
519 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
520 "Initializer for vector element doesn't match vector element type!");
527 // We declare several classes private to this file, so use an anonymous
531 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
532 /// behind the scenes to implement unary constant exprs.
533 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
534 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
536 // allocate space for exactly one operand
537 void *operator new(size_t s) {
538 return User::operator new(s, 1);
540 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
541 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
544 /// Transparently provide more efficient getOperand methods.
545 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
548 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
549 /// behind the scenes to implement binary constant exprs.
550 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
551 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
553 // allocate space for exactly two operands
554 void *operator new(size_t s) {
555 return User::operator new(s, 2);
557 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
558 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
562 /// Transparently provide more efficient getOperand methods.
563 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
566 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
567 /// behind the scenes to implement select constant exprs.
568 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
569 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
571 // allocate space for exactly three operands
572 void *operator new(size_t s) {
573 return User::operator new(s, 3);
575 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
576 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
581 /// Transparently provide more efficient getOperand methods.
582 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
585 /// ExtractElementConstantExpr - This class is private to
586 /// Constants.cpp, and is used behind the scenes to implement
587 /// extractelement constant exprs.
588 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
589 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
591 // allocate space for exactly two operands
592 void *operator new(size_t s) {
593 return User::operator new(s, 2);
595 ExtractElementConstantExpr(Constant *C1, Constant *C2)
596 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
597 Instruction::ExtractElement, &Op<0>(), 2) {
601 /// Transparently provide more efficient getOperand methods.
602 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
605 /// InsertElementConstantExpr - This class is private to
606 /// Constants.cpp, and is used behind the scenes to implement
607 /// insertelement constant exprs.
608 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
609 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
611 // allocate space for exactly three operands
612 void *operator new(size_t s) {
613 return User::operator new(s, 3);
615 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
616 : ConstantExpr(C1->getType(), Instruction::InsertElement,
622 /// Transparently provide more efficient getOperand methods.
623 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
626 /// ShuffleVectorConstantExpr - This class is private to
627 /// Constants.cpp, and is used behind the scenes to implement
628 /// shufflevector constant exprs.
629 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
630 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
632 // allocate space for exactly three operands
633 void *operator new(size_t s) {
634 return User::operator new(s, 3);
636 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
637 : ConstantExpr(VectorType::get(
638 cast<VectorType>(C1->getType())->getElementType(),
639 cast<VectorType>(C3->getType())->getNumElements()),
640 Instruction::ShuffleVector,
646 /// Transparently provide more efficient getOperand methods.
647 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
650 /// ExtractValueConstantExpr - This class is private to
651 /// Constants.cpp, and is used behind the scenes to implement
652 /// extractvalue constant exprs.
653 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
654 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
656 // allocate space for exactly one operand
657 void *operator new(size_t s) {
658 return User::operator new(s, 1);
660 ExtractValueConstantExpr(Constant *Agg,
661 const SmallVector<unsigned, 4> &IdxList,
663 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
668 /// Indices - These identify which value to extract.
669 const SmallVector<unsigned, 4> Indices;
671 /// Transparently provide more efficient getOperand methods.
672 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
675 /// InsertValueConstantExpr - This class is private to
676 /// Constants.cpp, and is used behind the scenes to implement
677 /// insertvalue constant exprs.
678 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
679 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
681 // allocate space for exactly one operand
682 void *operator new(size_t s) {
683 return User::operator new(s, 2);
685 InsertValueConstantExpr(Constant *Agg, Constant *Val,
686 const SmallVector<unsigned, 4> &IdxList,
688 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
694 /// Indices - These identify the position for the insertion.
695 const SmallVector<unsigned, 4> Indices;
697 /// Transparently provide more efficient getOperand methods.
698 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
702 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
703 /// used behind the scenes to implement getelementpr constant exprs.
704 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
705 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
708 static GetElementPtrConstantExpr *Create(Constant *C,
709 const std::vector<Constant*>&IdxList,
710 const Type *DestTy) {
711 return new(IdxList.size() + 1)
712 GetElementPtrConstantExpr(C, IdxList, DestTy);
714 /// Transparently provide more efficient getOperand methods.
715 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
718 // CompareConstantExpr - This class is private to Constants.cpp, and is used
719 // behind the scenes to implement ICmp and FCmp constant expressions. This is
720 // needed in order to store the predicate value for these instructions.
721 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
722 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
723 // allocate space for exactly two operands
724 void *operator new(size_t s) {
725 return User::operator new(s, 2);
727 unsigned short predicate;
728 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
729 unsigned short pred, Constant* LHS, Constant* RHS)
730 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
734 /// Transparently provide more efficient getOperand methods.
735 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
738 } // end anonymous namespace
741 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
743 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
746 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
748 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
751 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
753 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
756 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
758 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
761 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
763 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
766 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
768 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
771 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
773 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
776 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
778 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
781 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
784 GetElementPtrConstantExpr::GetElementPtrConstantExpr
786 const std::vector<Constant*> &IdxList,
788 : ConstantExpr(DestTy, Instruction::GetElementPtr,
789 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
790 - (IdxList.size()+1),
793 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
794 OperandList[i+1] = IdxList[i];
797 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
801 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
803 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
806 } // End llvm namespace
809 // Utility function for determining if a ConstantExpr is a CastOp or not. This
810 // can't be inline because we don't want to #include Instruction.h into
812 bool ConstantExpr::isCast() const {
813 return Instruction::isCast(getOpcode());
816 bool ConstantExpr::isCompare() const {
817 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
818 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
821 bool ConstantExpr::hasIndices() const {
822 return getOpcode() == Instruction::ExtractValue ||
823 getOpcode() == Instruction::InsertValue;
826 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
827 if (const ExtractValueConstantExpr *EVCE =
828 dyn_cast<ExtractValueConstantExpr>(this))
829 return EVCE->Indices;
831 return cast<InsertValueConstantExpr>(this)->Indices;
834 /// ConstantExpr::get* - Return some common constants without having to
835 /// specify the full Instruction::OPCODE identifier.
837 Constant *ConstantExpr::getNeg(Constant *C) {
838 // API compatibility: Adjust integer opcodes to floating-point opcodes.
839 if (C->getType()->isFPOrFPVector())
841 assert(C->getType()->isIntOrIntVector() &&
842 "Cannot NEG a nonintegral value!");
843 return get(Instruction::Sub,
844 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
847 Constant *ConstantExpr::getFNeg(Constant *C) {
848 assert(C->getType()->isFPOrFPVector() &&
849 "Cannot FNEG a non-floating-point value!");
850 return get(Instruction::FSub,
851 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
854 Constant *ConstantExpr::getNot(Constant *C) {
855 assert(C->getType()->isIntOrIntVector() &&
856 "Cannot NOT a nonintegral value!");
857 return get(Instruction::Xor, C,
858 Constant::getAllOnesValue(C->getType()));
860 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
861 return get(Instruction::Add, C1, C2);
863 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
864 return get(Instruction::FAdd, C1, C2);
866 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
867 return get(Instruction::Sub, C1, C2);
869 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
870 return get(Instruction::FSub, C1, C2);
872 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
873 return get(Instruction::Mul, C1, C2);
875 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
876 return get(Instruction::FMul, C1, C2);
878 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
879 return get(Instruction::UDiv, C1, C2);
881 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
882 return get(Instruction::SDiv, C1, C2);
884 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
885 return get(Instruction::FDiv, C1, C2);
887 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
888 return get(Instruction::URem, C1, C2);
890 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
891 return get(Instruction::SRem, C1, C2);
893 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
894 return get(Instruction::FRem, C1, C2);
896 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
897 return get(Instruction::And, C1, C2);
899 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
900 return get(Instruction::Or, C1, C2);
902 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
903 return get(Instruction::Xor, C1, C2);
905 unsigned ConstantExpr::getPredicate() const {
906 assert(getOpcode() == Instruction::FCmp ||
907 getOpcode() == Instruction::ICmp ||
908 getOpcode() == Instruction::VFCmp ||
909 getOpcode() == Instruction::VICmp);
910 return ((const CompareConstantExpr*)this)->predicate;
912 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
913 return get(Instruction::Shl, C1, C2);
915 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
916 return get(Instruction::LShr, C1, C2);
918 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
919 return get(Instruction::AShr, C1, C2);
922 /// getWithOperandReplaced - Return a constant expression identical to this
923 /// one, but with the specified operand set to the specified value.
925 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
926 assert(OpNo < getNumOperands() && "Operand num is out of range!");
927 assert(Op->getType() == getOperand(OpNo)->getType() &&
928 "Replacing operand with value of different type!");
929 if (getOperand(OpNo) == Op)
930 return const_cast<ConstantExpr*>(this);
932 Constant *Op0, *Op1, *Op2;
933 switch (getOpcode()) {
934 case Instruction::Trunc:
935 case Instruction::ZExt:
936 case Instruction::SExt:
937 case Instruction::FPTrunc:
938 case Instruction::FPExt:
939 case Instruction::UIToFP:
940 case Instruction::SIToFP:
941 case Instruction::FPToUI:
942 case Instruction::FPToSI:
943 case Instruction::PtrToInt:
944 case Instruction::IntToPtr:
945 case Instruction::BitCast:
946 return ConstantExpr::getCast(getOpcode(), Op, getType());
947 case Instruction::Select:
948 Op0 = (OpNo == 0) ? Op : getOperand(0);
949 Op1 = (OpNo == 1) ? Op : getOperand(1);
950 Op2 = (OpNo == 2) ? Op : getOperand(2);
951 return ConstantExpr::getSelect(Op0, Op1, Op2);
952 case Instruction::InsertElement:
953 Op0 = (OpNo == 0) ? Op : getOperand(0);
954 Op1 = (OpNo == 1) ? Op : getOperand(1);
955 Op2 = (OpNo == 2) ? Op : getOperand(2);
956 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
957 case Instruction::ExtractElement:
958 Op0 = (OpNo == 0) ? Op : getOperand(0);
959 Op1 = (OpNo == 1) ? Op : getOperand(1);
960 return ConstantExpr::getExtractElement(Op0, Op1);
961 case Instruction::ShuffleVector:
962 Op0 = (OpNo == 0) ? Op : getOperand(0);
963 Op1 = (OpNo == 1) ? Op : getOperand(1);
964 Op2 = (OpNo == 2) ? Op : getOperand(2);
965 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
966 case Instruction::GetElementPtr: {
967 SmallVector<Constant*, 8> Ops;
968 Ops.resize(getNumOperands()-1);
969 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
970 Ops[i-1] = getOperand(i);
972 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
974 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
977 assert(getNumOperands() == 2 && "Must be binary operator?");
978 Op0 = (OpNo == 0) ? Op : getOperand(0);
979 Op1 = (OpNo == 1) ? Op : getOperand(1);
980 return ConstantExpr::get(getOpcode(), Op0, Op1);
984 /// getWithOperands - This returns the current constant expression with the
985 /// operands replaced with the specified values. The specified operands must
986 /// match count and type with the existing ones.
987 Constant *ConstantExpr::
988 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
989 assert(NumOps == getNumOperands() && "Operand count mismatch!");
990 bool AnyChange = false;
991 for (unsigned i = 0; i != NumOps; ++i) {
992 assert(Ops[i]->getType() == getOperand(i)->getType() &&
993 "Operand type mismatch!");
994 AnyChange |= Ops[i] != getOperand(i);
996 if (!AnyChange) // No operands changed, return self.
997 return const_cast<ConstantExpr*>(this);
999 switch (getOpcode()) {
1000 case Instruction::Trunc:
1001 case Instruction::ZExt:
1002 case Instruction::SExt:
1003 case Instruction::FPTrunc:
1004 case Instruction::FPExt:
1005 case Instruction::UIToFP:
1006 case Instruction::SIToFP:
1007 case Instruction::FPToUI:
1008 case Instruction::FPToSI:
1009 case Instruction::PtrToInt:
1010 case Instruction::IntToPtr:
1011 case Instruction::BitCast:
1012 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
1013 case Instruction::Select:
1014 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1015 case Instruction::InsertElement:
1016 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1017 case Instruction::ExtractElement:
1018 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1019 case Instruction::ShuffleVector:
1020 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1021 case Instruction::GetElementPtr:
1022 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
1023 case Instruction::ICmp:
1024 case Instruction::FCmp:
1025 case Instruction::VICmp:
1026 case Instruction::VFCmp:
1027 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1029 assert(getNumOperands() == 2 && "Must be binary operator?");
1030 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
1035 //===----------------------------------------------------------------------===//
1036 // isValueValidForType implementations
1038 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
1039 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1040 if (Ty == Type::Int1Ty)
1041 return Val == 0 || Val == 1;
1043 return true; // always true, has to fit in largest type
1044 uint64_t Max = (1ll << NumBits) - 1;
1048 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
1049 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1050 if (Ty == Type::Int1Ty)
1051 return Val == 0 || Val == 1 || Val == -1;
1053 return true; // always true, has to fit in largest type
1054 int64_t Min = -(1ll << (NumBits-1));
1055 int64_t Max = (1ll << (NumBits-1)) - 1;
1056 return (Val >= Min && Val <= Max);
1059 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1060 // convert modifies in place, so make a copy.
1061 APFloat Val2 = APFloat(Val);
1063 switch (Ty->getTypeID()) {
1065 return false; // These can't be represented as floating point!
1067 // FIXME rounding mode needs to be more flexible
1068 case Type::FloatTyID: {
1069 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1071 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1074 case Type::DoubleTyID: {
1075 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1076 &Val2.getSemantics() == &APFloat::IEEEdouble)
1078 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1081 case Type::X86_FP80TyID:
1082 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1083 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1084 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1085 case Type::FP128TyID:
1086 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1087 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1088 &Val2.getSemantics() == &APFloat::IEEEquad;
1089 case Type::PPC_FP128TyID:
1090 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1091 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1092 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1096 //===----------------------------------------------------------------------===//
1097 // Factory Function Implementation
1100 // The number of operands for each ConstantCreator::create method is
1101 // determined by the ConstantTraits template.
1102 // ConstantCreator - A class that is used to create constants by
1103 // ValueMap*. This class should be partially specialized if there is
1104 // something strange that needs to be done to interface to the ctor for the
1108 template<class ValType>
1109 struct ConstantTraits;
1111 template<typename T, typename Alloc>
1112 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1113 static unsigned uses(const std::vector<T, Alloc>& v) {
1118 template<class ConstantClass, class TypeClass, class ValType>
1119 struct VISIBILITY_HIDDEN ConstantCreator {
1120 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1121 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1125 template<class ConstantClass, class TypeClass>
1126 struct VISIBILITY_HIDDEN ConvertConstantType {
1127 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1128 assert(0 && "This type cannot be converted!\n");
1133 template<class ValType, class TypeClass, class ConstantClass,
1134 bool HasLargeKey = false /*true for arrays and structs*/ >
1135 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1137 typedef std::pair<const Type*, ValType> MapKey;
1138 typedef std::map<MapKey, Constant *> MapTy;
1139 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1140 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1142 /// Map - This is the main map from the element descriptor to the Constants.
1143 /// This is the primary way we avoid creating two of the same shape
1147 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1148 /// from the constants to their element in Map. This is important for
1149 /// removal of constants from the array, which would otherwise have to scan
1150 /// through the map with very large keys.
1151 InverseMapTy InverseMap;
1153 /// AbstractTypeMap - Map for abstract type constants.
1155 AbstractTypeMapTy AbstractTypeMap;
1157 /// ValueMapLock - Mutex for this map.
1158 sys::SmartMutex<true> ValueMapLock;
1161 // NOTE: This function is not locked. It is the caller's responsibility
1162 // to enforce proper synchronization.
1163 typename MapTy::iterator map_end() { return Map.end(); }
1165 /// InsertOrGetItem - Return an iterator for the specified element.
1166 /// If the element exists in the map, the returned iterator points to the
1167 /// entry and Exists=true. If not, the iterator points to the newly
1168 /// inserted entry and returns Exists=false. Newly inserted entries have
1169 /// I->second == 0, and should be filled in.
1170 /// NOTE: This function is not locked. It is the caller's responsibility
1171 // to enforce proper synchronization.
1172 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1175 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1176 Exists = !IP.second;
1181 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1183 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1184 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1185 IMI->second->second == CP &&
1186 "InverseMap corrupt!");
1190 typename MapTy::iterator I =
1191 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1193 if (I == Map.end() || I->second != CP) {
1194 // FIXME: This should not use a linear scan. If this gets to be a
1195 // performance problem, someone should look at this.
1196 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1202 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1203 typename MapTy::iterator I) {
1204 ConstantClass* Result =
1205 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1207 assert(Result->getType() == Ty && "Type specified is not correct!");
1208 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1210 if (HasLargeKey) // Remember the reverse mapping if needed.
1211 InverseMap.insert(std::make_pair(Result, I));
1213 // If the type of the constant is abstract, make sure that an entry
1214 // exists for it in the AbstractTypeMap.
1215 if (Ty->isAbstract()) {
1216 typename AbstractTypeMapTy::iterator TI =
1217 AbstractTypeMap.find(Ty);
1219 if (TI == AbstractTypeMap.end()) {
1220 // Add ourselves to the ATU list of the type.
1221 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1223 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1231 /// getOrCreate - Return the specified constant from the map, creating it if
1233 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1234 sys::SmartScopedLock<true> Lock(&ValueMapLock);
1235 MapKey Lookup(Ty, V);
1236 ConstantClass* Result = 0;
1238 typename MapTy::iterator I = Map.find(Lookup);
1239 // Is it in the map?
1241 Result = static_cast<ConstantClass *>(I->second);
1244 // If no preexisting value, create one now...
1245 Result = Create(Ty, V, I);
1251 void remove(ConstantClass *CP) {
1252 sys::SmartScopedLock<true> Lock(&ValueMapLock);
1253 typename MapTy::iterator I = FindExistingElement(CP);
1254 assert(I != Map.end() && "Constant not found in constant table!");
1255 assert(I->second == CP && "Didn't find correct element?");
1257 if (HasLargeKey) // Remember the reverse mapping if needed.
1258 InverseMap.erase(CP);
1260 // Now that we found the entry, make sure this isn't the entry that
1261 // the AbstractTypeMap points to.
1262 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1263 if (Ty->isAbstract()) {
1264 assert(AbstractTypeMap.count(Ty) &&
1265 "Abstract type not in AbstractTypeMap?");
1266 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1267 if (ATMEntryIt == I) {
1268 // Yes, we are removing the representative entry for this type.
1269 // See if there are any other entries of the same type.
1270 typename MapTy::iterator TmpIt = ATMEntryIt;
1272 // First check the entry before this one...
1273 if (TmpIt != Map.begin()) {
1275 if (TmpIt->first.first != Ty) // Not the same type, move back...
1279 // If we didn't find the same type, try to move forward...
1280 if (TmpIt == ATMEntryIt) {
1282 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1283 --TmpIt; // No entry afterwards with the same type
1286 // If there is another entry in the map of the same abstract type,
1287 // update the AbstractTypeMap entry now.
1288 if (TmpIt != ATMEntryIt) {
1291 // Otherwise, we are removing the last instance of this type
1292 // from the table. Remove from the ATM, and from user list.
1293 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1294 AbstractTypeMap.erase(Ty);
1303 /// MoveConstantToNewSlot - If we are about to change C to be the element
1304 /// specified by I, update our internal data structures to reflect this
1306 /// NOTE: This function is not locked. It is the responsibility of the
1307 /// caller to enforce proper synchronization if using this method.
1308 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1309 // First, remove the old location of the specified constant in the map.
1310 typename MapTy::iterator OldI = FindExistingElement(C);
1311 assert(OldI != Map.end() && "Constant not found in constant table!");
1312 assert(OldI->second == C && "Didn't find correct element?");
1314 // If this constant is the representative element for its abstract type,
1315 // update the AbstractTypeMap so that the representative element is I.
1316 if (C->getType()->isAbstract()) {
1317 typename AbstractTypeMapTy::iterator ATI =
1318 AbstractTypeMap.find(C->getType());
1319 assert(ATI != AbstractTypeMap.end() &&
1320 "Abstract type not in AbstractTypeMap?");
1321 if (ATI->second == OldI)
1325 // Remove the old entry from the map.
1328 // Update the inverse map so that we know that this constant is now
1329 // located at descriptor I.
1331 assert(I->second == C && "Bad inversemap entry!");
1336 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1337 sys::SmartScopedLock<true> Lock(&ValueMapLock);
1338 typename AbstractTypeMapTy::iterator I =
1339 AbstractTypeMap.find(cast<Type>(OldTy));
1341 assert(I != AbstractTypeMap.end() &&
1342 "Abstract type not in AbstractTypeMap?");
1344 // Convert a constant at a time until the last one is gone. The last one
1345 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1346 // eliminated eventually.
1348 ConvertConstantType<ConstantClass,
1349 TypeClass>::convert(
1350 static_cast<ConstantClass *>(I->second->second),
1351 cast<TypeClass>(NewTy));
1353 I = AbstractTypeMap.find(cast<Type>(OldTy));
1354 } while (I != AbstractTypeMap.end());
1357 // If the type became concrete without being refined to any other existing
1358 // type, we just remove ourselves from the ATU list.
1359 void typeBecameConcrete(const DerivedType *AbsTy) {
1360 AbsTy->removeAbstractTypeUser(this);
1364 DOUT << "Constant.cpp: ValueMap\n";
1371 //---- ConstantAggregateZero::get() implementation...
1374 // ConstantAggregateZero does not take extra "value" argument...
1375 template<class ValType>
1376 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1377 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1378 return new ConstantAggregateZero(Ty);
1383 struct ConvertConstantType<ConstantAggregateZero, Type> {
1384 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1385 // Make everyone now use a constant of the new type...
1386 Constant *New = ConstantAggregateZero::get(NewTy);
1387 assert(New != OldC && "Didn't replace constant??");
1388 OldC->uncheckedReplaceAllUsesWith(New);
1389 OldC->destroyConstant(); // This constant is now dead, destroy it.
1394 static ManagedStatic<ValueMap<char, Type,
1395 ConstantAggregateZero> > AggZeroConstants;
1397 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1399 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1400 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1401 "Cannot create an aggregate zero of non-aggregate type!");
1403 // Implicitly locked.
1404 return AggZeroConstants->getOrCreate(Ty, 0);
1407 /// destroyConstant - Remove the constant from the constant table...
1409 void ConstantAggregateZero::destroyConstant() {
1410 // Implicitly locked.
1411 AggZeroConstants->remove(this);
1412 destroyConstantImpl();
1415 //---- ConstantArray::get() implementation...
1419 struct ConvertConstantType<ConstantArray, ArrayType> {
1420 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1421 // Make everyone now use a constant of the new type...
1422 std::vector<Constant*> C;
1423 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1424 C.push_back(cast<Constant>(OldC->getOperand(i)));
1425 Constant *New = ConstantArray::get(NewTy, C);
1426 assert(New != OldC && "Didn't replace constant??");
1427 OldC->uncheckedReplaceAllUsesWith(New);
1428 OldC->destroyConstant(); // This constant is now dead, destroy it.
1433 static std::vector<Constant*> getValType(ConstantArray *CA) {
1434 std::vector<Constant*> Elements;
1435 Elements.reserve(CA->getNumOperands());
1436 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1437 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1441 typedef ValueMap<std::vector<Constant*>, ArrayType,
1442 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1443 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1445 Constant *ConstantArray::get(const ArrayType *Ty,
1446 const std::vector<Constant*> &V) {
1447 // If this is an all-zero array, return a ConstantAggregateZero object
1450 if (!C->isNullValue()) {
1451 // Implicitly locked.
1452 return ArrayConstants->getOrCreate(Ty, V);
1454 for (unsigned i = 1, e = V.size(); i != e; ++i)
1456 // Implicitly locked.
1457 return ArrayConstants->getOrCreate(Ty, V);
1461 return ConstantAggregateZero::get(Ty);
1464 /// destroyConstant - Remove the constant from the constant table...
1466 void ConstantArray::destroyConstant() {
1467 // Implicitly locked.
1468 ArrayConstants->remove(this);
1469 destroyConstantImpl();
1472 /// ConstantArray::get(const string&) - Return an array that is initialized to
1473 /// contain the specified string. If length is zero then a null terminator is
1474 /// added to the specified string so that it may be used in a natural way.
1475 /// Otherwise, the length parameter specifies how much of the string to use
1476 /// and it won't be null terminated.
1478 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1479 std::vector<Constant*> ElementVals;
1480 for (unsigned i = 0; i < Str.length(); ++i)
1481 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1483 // Add a null terminator to the string...
1485 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1488 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1489 return ConstantArray::get(ATy, ElementVals);
1492 /// isString - This method returns true if the array is an array of i8, and
1493 /// if the elements of the array are all ConstantInt's.
1494 bool ConstantArray::isString() const {
1495 // Check the element type for i8...
1496 if (getType()->getElementType() != Type::Int8Ty)
1498 // Check the elements to make sure they are all integers, not constant
1500 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1501 if (!isa<ConstantInt>(getOperand(i)))
1506 /// isCString - This method returns true if the array is a string (see
1507 /// isString) and it ends in a null byte \\0 and does not contains any other
1508 /// null bytes except its terminator.
1509 bool ConstantArray::isCString() const {
1510 // Check the element type for i8...
1511 if (getType()->getElementType() != Type::Int8Ty)
1513 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1514 // Last element must be a null.
1515 if (getOperand(getNumOperands()-1) != Zero)
1517 // Other elements must be non-null integers.
1518 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1519 if (!isa<ConstantInt>(getOperand(i)))
1521 if (getOperand(i) == Zero)
1528 /// getAsString - If the sub-element type of this array is i8
1529 /// then this method converts the array to an std::string and returns it.
1530 /// Otherwise, it asserts out.
1532 std::string ConstantArray::getAsString() const {
1533 assert(isString() && "Not a string!");
1535 Result.reserve(getNumOperands());
1536 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1537 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1542 //---- ConstantStruct::get() implementation...
1547 struct ConvertConstantType<ConstantStruct, StructType> {
1548 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1549 // Make everyone now use a constant of the new type...
1550 std::vector<Constant*> C;
1551 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1552 C.push_back(cast<Constant>(OldC->getOperand(i)));
1553 Constant *New = ConstantStruct::get(NewTy, C);
1554 assert(New != OldC && "Didn't replace constant??");
1556 OldC->uncheckedReplaceAllUsesWith(New);
1557 OldC->destroyConstant(); // This constant is now dead, destroy it.
1562 typedef ValueMap<std::vector<Constant*>, StructType,
1563 ConstantStruct, true /*largekey*/> StructConstantsTy;
1564 static ManagedStatic<StructConstantsTy> StructConstants;
1566 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1567 std::vector<Constant*> Elements;
1568 Elements.reserve(CS->getNumOperands());
1569 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1570 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1574 Constant *ConstantStruct::get(const StructType *Ty,
1575 const std::vector<Constant*> &V) {
1576 // Create a ConstantAggregateZero value if all elements are zeros...
1577 for (unsigned i = 0, e = V.size(); i != e; ++i)
1578 if (!V[i]->isNullValue())
1579 // Implicitly locked.
1580 return StructConstants->getOrCreate(Ty, V);
1582 return ConstantAggregateZero::get(Ty);
1585 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1586 std::vector<const Type*> StructEls;
1587 StructEls.reserve(V.size());
1588 for (unsigned i = 0, e = V.size(); i != e; ++i)
1589 StructEls.push_back(V[i]->getType());
1590 return get(StructType::get(StructEls, packed), V);
1593 // destroyConstant - Remove the constant from the constant table...
1595 void ConstantStruct::destroyConstant() {
1596 // Implicitly locked.
1597 StructConstants->remove(this);
1598 destroyConstantImpl();
1601 //---- ConstantVector::get() implementation...
1605 struct ConvertConstantType<ConstantVector, VectorType> {
1606 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1607 // Make everyone now use a constant of the new type...
1608 std::vector<Constant*> C;
1609 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1610 C.push_back(cast<Constant>(OldC->getOperand(i)));
1611 Constant *New = ConstantVector::get(NewTy, C);
1612 assert(New != OldC && "Didn't replace constant??");
1613 OldC->uncheckedReplaceAllUsesWith(New);
1614 OldC->destroyConstant(); // This constant is now dead, destroy it.
1619 static std::vector<Constant*> getValType(ConstantVector *CP) {
1620 std::vector<Constant*> Elements;
1621 Elements.reserve(CP->getNumOperands());
1622 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1623 Elements.push_back(CP->getOperand(i));
1627 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1628 ConstantVector> > VectorConstants;
1630 Constant *ConstantVector::get(const VectorType *Ty,
1631 const std::vector<Constant*> &V) {
1632 assert(!V.empty() && "Vectors can't be empty");
1633 // If this is an all-undef or alll-zero vector, return a
1634 // ConstantAggregateZero or UndefValue.
1636 bool isZero = C->isNullValue();
1637 bool isUndef = isa<UndefValue>(C);
1639 if (isZero || isUndef) {
1640 for (unsigned i = 1, e = V.size(); i != e; ++i)
1642 isZero = isUndef = false;
1648 return ConstantAggregateZero::get(Ty);
1650 return UndefValue::get(Ty);
1652 // Implicitly locked.
1653 return VectorConstants->getOrCreate(Ty, V);
1656 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1657 assert(!V.empty() && "Cannot infer type if V is empty");
1658 return get(VectorType::get(V.front()->getType(),V.size()), V);
1661 // destroyConstant - Remove the constant from the constant table...
1663 void ConstantVector::destroyConstant() {
1664 // Implicitly locked.
1665 VectorConstants->remove(this);
1666 destroyConstantImpl();
1669 /// This function will return true iff every element in this vector constant
1670 /// is set to all ones.
1671 /// @returns true iff this constant's emements are all set to all ones.
1672 /// @brief Determine if the value is all ones.
1673 bool ConstantVector::isAllOnesValue() const {
1674 // Check out first element.
1675 const Constant *Elt = getOperand(0);
1676 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1677 if (!CI || !CI->isAllOnesValue()) return false;
1678 // Then make sure all remaining elements point to the same value.
1679 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1680 if (getOperand(I) != Elt) return false;
1685 /// getSplatValue - If this is a splat constant, where all of the
1686 /// elements have the same value, return that value. Otherwise return null.
1687 Constant *ConstantVector::getSplatValue() {
1688 // Check out first element.
1689 Constant *Elt = getOperand(0);
1690 // Then make sure all remaining elements point to the same value.
1691 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1692 if (getOperand(I) != Elt) return 0;
1696 //---- ConstantPointerNull::get() implementation...
1700 // ConstantPointerNull does not take extra "value" argument...
1701 template<class ValType>
1702 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1703 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1704 return new ConstantPointerNull(Ty);
1709 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1710 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1711 // Make everyone now use a constant of the new type...
1712 Constant *New = ConstantPointerNull::get(NewTy);
1713 assert(New != OldC && "Didn't replace constant??");
1714 OldC->uncheckedReplaceAllUsesWith(New);
1715 OldC->destroyConstant(); // This constant is now dead, destroy it.
1720 static ManagedStatic<ValueMap<char, PointerType,
1721 ConstantPointerNull> > NullPtrConstants;
1723 static char getValType(ConstantPointerNull *) {
1728 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1729 // Implicitly locked.
1730 return NullPtrConstants->getOrCreate(Ty, 0);
1733 // destroyConstant - Remove the constant from the constant table...
1735 void ConstantPointerNull::destroyConstant() {
1736 // Implicitly locked.
1737 NullPtrConstants->remove(this);
1738 destroyConstantImpl();
1742 //---- UndefValue::get() implementation...
1746 // UndefValue does not take extra "value" argument...
1747 template<class ValType>
1748 struct ConstantCreator<UndefValue, Type, ValType> {
1749 static UndefValue *create(const Type *Ty, const ValType &V) {
1750 return new UndefValue(Ty);
1755 struct ConvertConstantType<UndefValue, Type> {
1756 static void convert(UndefValue *OldC, const Type *NewTy) {
1757 // Make everyone now use a constant of the new type.
1758 Constant *New = UndefValue::get(NewTy);
1759 assert(New != OldC && "Didn't replace constant??");
1760 OldC->uncheckedReplaceAllUsesWith(New);
1761 OldC->destroyConstant(); // This constant is now dead, destroy it.
1766 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1768 static char getValType(UndefValue *) {
1773 UndefValue *UndefValue::get(const Type *Ty) {
1774 // Implicitly locked.
1775 return UndefValueConstants->getOrCreate(Ty, 0);
1778 // destroyConstant - Remove the constant from the constant table.
1780 void UndefValue::destroyConstant() {
1781 // Implicitly locked.
1782 UndefValueConstants->remove(this);
1783 destroyConstantImpl();
1786 //---- MDString::get() implementation
1789 MDString::MDString(const char *begin, const char *end)
1790 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1791 StrBegin(begin), StrEnd(end) {}
1793 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1795 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1796 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1797 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1799 MDString *&S = Entry.getValue();
1800 if (!S) S = new MDString(Entry.getKeyData(),
1801 Entry.getKeyData() + Entry.getKeyLength());
1806 MDString *MDString::get(const std::string &Str) {
1807 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1808 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1809 Str.data(), Str.data() + Str.size());
1810 MDString *&S = Entry.getValue();
1811 if (!S) S = new MDString(Entry.getKeyData(),
1812 Entry.getKeyData() + Entry.getKeyLength());
1817 void MDString::destroyConstant() {
1818 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1819 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1820 destroyConstantImpl();
1823 //---- MDNode::get() implementation
1826 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1828 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1829 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1830 for (unsigned i = 0; i != NumVals; ++i)
1831 Node.push_back(ElementVH(Vals[i], this));
1834 void MDNode::Profile(FoldingSetNodeID &ID) const {
1835 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1839 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1840 FoldingSetNodeID ID;
1841 for (unsigned i = 0; i != NumVals; ++i)
1842 ID.AddPointer(Vals[i]);
1844 ConstantsLock->reader_acquire();
1846 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1847 ConstantsLock->reader_release();
1850 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1851 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1853 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1854 N = new(0) MDNode(Vals, NumVals);
1855 MDNodeSet->InsertNode(N, InsertPoint);
1861 void MDNode::destroyConstant() {
1862 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
1863 MDNodeSet->RemoveNode(this);
1865 destroyConstantImpl();
1868 //---- ConstantExpr::get() implementations...
1873 struct ExprMapKeyType {
1874 typedef SmallVector<unsigned, 4> IndexList;
1876 ExprMapKeyType(unsigned opc,
1877 const std::vector<Constant*> &ops,
1878 unsigned short pred = 0,
1879 const IndexList &inds = IndexList())
1880 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1883 std::vector<Constant*> operands;
1885 bool operator==(const ExprMapKeyType& that) const {
1886 return this->opcode == that.opcode &&
1887 this->predicate == that.predicate &&
1888 this->operands == that.operands &&
1889 this->indices == that.indices;
1891 bool operator<(const ExprMapKeyType & that) const {
1892 return this->opcode < that.opcode ||
1893 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1894 (this->opcode == that.opcode && this->predicate == that.predicate &&
1895 this->operands < that.operands) ||
1896 (this->opcode == that.opcode && this->predicate == that.predicate &&
1897 this->operands == that.operands && this->indices < that.indices);
1900 bool operator!=(const ExprMapKeyType& that) const {
1901 return !(*this == that);
1909 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1910 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1911 unsigned short pred = 0) {
1912 if (Instruction::isCast(V.opcode))
1913 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1914 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1915 V.opcode < Instruction::BinaryOpsEnd))
1916 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1917 if (V.opcode == Instruction::Select)
1918 return new SelectConstantExpr(V.operands[0], V.operands[1],
1920 if (V.opcode == Instruction::ExtractElement)
1921 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1922 if (V.opcode == Instruction::InsertElement)
1923 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1925 if (V.opcode == Instruction::ShuffleVector)
1926 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1928 if (V.opcode == Instruction::InsertValue)
1929 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1931 if (V.opcode == Instruction::ExtractValue)
1932 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1933 if (V.opcode == Instruction::GetElementPtr) {
1934 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1935 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1938 // The compare instructions are weird. We have to encode the predicate
1939 // value and it is combined with the instruction opcode by multiplying
1940 // the opcode by one hundred. We must decode this to get the predicate.
1941 if (V.opcode == Instruction::ICmp)
1942 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1943 V.operands[0], V.operands[1]);
1944 if (V.opcode == Instruction::FCmp)
1945 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1946 V.operands[0], V.operands[1]);
1947 if (V.opcode == Instruction::VICmp)
1948 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1949 V.operands[0], V.operands[1]);
1950 if (V.opcode == Instruction::VFCmp)
1951 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1952 V.operands[0], V.operands[1]);
1953 assert(0 && "Invalid ConstantExpr!");
1959 struct ConvertConstantType<ConstantExpr, Type> {
1960 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1962 switch (OldC->getOpcode()) {
1963 case Instruction::Trunc:
1964 case Instruction::ZExt:
1965 case Instruction::SExt:
1966 case Instruction::FPTrunc:
1967 case Instruction::FPExt:
1968 case Instruction::UIToFP:
1969 case Instruction::SIToFP:
1970 case Instruction::FPToUI:
1971 case Instruction::FPToSI:
1972 case Instruction::PtrToInt:
1973 case Instruction::IntToPtr:
1974 case Instruction::BitCast:
1975 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1978 case Instruction::Select:
1979 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1980 OldC->getOperand(1),
1981 OldC->getOperand(2));
1984 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1985 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1986 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1987 OldC->getOperand(1));
1989 case Instruction::GetElementPtr:
1990 // Make everyone now use a constant of the new type...
1991 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1992 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1993 &Idx[0], Idx.size());
1997 assert(New != OldC && "Didn't replace constant??");
1998 OldC->uncheckedReplaceAllUsesWith(New);
1999 OldC->destroyConstant(); // This constant is now dead, destroy it.
2002 } // end namespace llvm
2005 static ExprMapKeyType getValType(ConstantExpr *CE) {
2006 std::vector<Constant*> Operands;
2007 Operands.reserve(CE->getNumOperands());
2008 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
2009 Operands.push_back(cast<Constant>(CE->getOperand(i)));
2010 return ExprMapKeyType(CE->getOpcode(), Operands,
2011 CE->isCompare() ? CE->getPredicate() : 0,
2013 CE->getIndices() : SmallVector<unsigned, 4>());
2016 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
2017 ConstantExpr> > ExprConstants;
2019 /// This is a utility function to handle folding of casts and lookup of the
2020 /// cast in the ExprConstants map. It is used by the various get* methods below.
2021 static inline Constant *getFoldedCast(
2022 Instruction::CastOps opc, Constant *C, const Type *Ty) {
2023 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2024 // Fold a few common cases
2025 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2028 // Look up the constant in the table first to ensure uniqueness
2029 std::vector<Constant*> argVec(1, C);
2030 ExprMapKeyType Key(opc, argVec);
2032 // Implicitly locked.
2033 return ExprConstants->getOrCreate(Ty, Key);
2036 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
2037 Instruction::CastOps opc = Instruction::CastOps(oc);
2038 assert(Instruction::isCast(opc) && "opcode out of range");
2039 assert(C && Ty && "Null arguments to getCast");
2040 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2044 assert(0 && "Invalid cast opcode");
2046 case Instruction::Trunc: return getTrunc(C, Ty);
2047 case Instruction::ZExt: return getZExt(C, Ty);
2048 case Instruction::SExt: return getSExt(C, Ty);
2049 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
2050 case Instruction::FPExt: return getFPExtend(C, Ty);
2051 case Instruction::UIToFP: return getUIToFP(C, Ty);
2052 case Instruction::SIToFP: return getSIToFP(C, Ty);
2053 case Instruction::FPToUI: return getFPToUI(C, Ty);
2054 case Instruction::FPToSI: return getFPToSI(C, Ty);
2055 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
2056 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
2057 case Instruction::BitCast: return getBitCast(C, Ty);
2062 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
2063 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2064 return getCast(Instruction::BitCast, C, Ty);
2065 return getCast(Instruction::ZExt, C, Ty);
2068 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
2069 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2070 return getCast(Instruction::BitCast, C, Ty);
2071 return getCast(Instruction::SExt, C, Ty);
2074 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
2075 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2076 return getCast(Instruction::BitCast, C, Ty);
2077 return getCast(Instruction::Trunc, C, Ty);
2080 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
2081 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2082 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
2084 if (Ty->isInteger())
2085 return getCast(Instruction::PtrToInt, S, Ty);
2086 return getCast(Instruction::BitCast, S, Ty);
2089 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
2091 assert(C->getType()->isIntOrIntVector() &&
2092 Ty->isIntOrIntVector() && "Invalid cast");
2093 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2094 unsigned DstBits = Ty->getScalarSizeInBits();
2095 Instruction::CastOps opcode =
2096 (SrcBits == DstBits ? Instruction::BitCast :
2097 (SrcBits > DstBits ? Instruction::Trunc :
2098 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2099 return getCast(opcode, C, Ty);
2102 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
2103 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2105 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2106 unsigned DstBits = Ty->getScalarSizeInBits();
2107 if (SrcBits == DstBits)
2108 return C; // Avoid a useless cast
2109 Instruction::CastOps opcode =
2110 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2111 return getCast(opcode, C, Ty);
2114 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
2116 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2117 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2119 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2120 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2121 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2122 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2123 "SrcTy must be larger than DestTy for Trunc!");
2125 return getFoldedCast(Instruction::Trunc, C, Ty);
2128 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
2130 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2131 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2133 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2134 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2135 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2136 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2137 "SrcTy must be smaller than DestTy for SExt!");
2139 return getFoldedCast(Instruction::SExt, C, Ty);
2142 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
2144 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2145 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2147 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2148 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2149 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2150 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2151 "SrcTy must be smaller than DestTy for ZExt!");
2153 return getFoldedCast(Instruction::ZExt, C, Ty);
2156 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
2158 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2159 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2161 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2162 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2163 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2164 "This is an illegal floating point truncation!");
2165 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2168 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2170 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2171 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2173 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2174 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2175 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2176 "This is an illegal floating point extension!");
2177 return getFoldedCast(Instruction::FPExt, C, Ty);
2180 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2182 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2183 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2185 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2186 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2187 "This is an illegal uint to floating point cast!");
2188 return getFoldedCast(Instruction::UIToFP, C, Ty);
2191 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2193 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2194 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2196 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2197 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2198 "This is an illegal sint to floating point cast!");
2199 return getFoldedCast(Instruction::SIToFP, C, Ty);
2202 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2204 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2205 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2207 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2208 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2209 "This is an illegal floating point to uint cast!");
2210 return getFoldedCast(Instruction::FPToUI, C, Ty);
2213 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2215 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2216 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2218 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2219 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2220 "This is an illegal floating point to sint cast!");
2221 return getFoldedCast(Instruction::FPToSI, C, Ty);
2224 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2225 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2226 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2227 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2230 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2231 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2232 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2233 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2236 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2237 // BitCast implies a no-op cast of type only. No bits change. However, you
2238 // can't cast pointers to anything but pointers.
2240 const Type *SrcTy = C->getType();
2241 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2242 "BitCast cannot cast pointer to non-pointer and vice versa");
2244 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2245 // or nonptr->ptr). For all the other types, the cast is okay if source and
2246 // destination bit widths are identical.
2247 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2248 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2250 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2252 // It is common to ask for a bitcast of a value to its own type, handle this
2254 if (C->getType() == DstTy) return C;
2256 return getFoldedCast(Instruction::BitCast, C, DstTy);
2259 Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2260 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2261 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2262 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2263 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2264 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2265 Constant *Indices[2] = { Zero, One };
2266 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2267 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2270 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
2271 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2272 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2274 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2275 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2278 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2279 Constant *C1, Constant *C2) {
2280 // Check the operands for consistency first
2281 assert(Opcode >= Instruction::BinaryOpsBegin &&
2282 Opcode < Instruction::BinaryOpsEnd &&
2283 "Invalid opcode in binary constant expression");
2284 assert(C1->getType() == C2->getType() &&
2285 "Operand types in binary constant expression should match");
2287 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2288 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2289 return FC; // Fold a few common cases...
2291 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2292 ExprMapKeyType Key(Opcode, argVec);
2294 // Implicitly locked.
2295 return ExprConstants->getOrCreate(ReqTy, Key);
2298 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2299 Constant *C1, Constant *C2) {
2300 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
2301 switch (predicate) {
2302 default: assert(0 && "Invalid CmpInst predicate");
2303 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2304 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2305 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2306 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2307 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2308 case CmpInst::FCMP_TRUE:
2309 return isVectorType ? getVFCmp(predicate, C1, C2)
2310 : getFCmp(predicate, C1, C2);
2311 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2312 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2313 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2314 case CmpInst::ICMP_SLE:
2315 return isVectorType ? getVICmp(predicate, C1, C2)
2316 : getICmp(predicate, C1, C2);
2320 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2321 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2322 if (C1->getType()->isFPOrFPVector()) {
2323 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2324 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2325 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2329 case Instruction::Add:
2330 case Instruction::Sub:
2331 case Instruction::Mul:
2332 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2333 assert(C1->getType()->isIntOrIntVector() &&
2334 "Tried to create an integer operation on a non-integer type!");
2336 case Instruction::FAdd:
2337 case Instruction::FSub:
2338 case Instruction::FMul:
2339 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2340 assert(C1->getType()->isFPOrFPVector() &&
2341 "Tried to create a floating-point operation on a "
2342 "non-floating-point type!");
2344 case Instruction::UDiv:
2345 case Instruction::SDiv:
2346 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2347 assert(C1->getType()->isIntOrIntVector() &&
2348 "Tried to create an arithmetic operation on a non-arithmetic type!");
2350 case Instruction::FDiv:
2351 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2352 assert(C1->getType()->isFPOrFPVector() &&
2353 "Tried to create an arithmetic operation on a non-arithmetic type!");
2355 case Instruction::URem:
2356 case Instruction::SRem:
2357 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2358 assert(C1->getType()->isIntOrIntVector() &&
2359 "Tried to create an arithmetic operation on a non-arithmetic type!");
2361 case Instruction::FRem:
2362 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2363 assert(C1->getType()->isFPOrFPVector() &&
2364 "Tried to create an arithmetic operation on a non-arithmetic type!");
2366 case Instruction::And:
2367 case Instruction::Or:
2368 case Instruction::Xor:
2369 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2370 assert(C1->getType()->isIntOrIntVector() &&
2371 "Tried to create a logical operation on a non-integral type!");
2373 case Instruction::Shl:
2374 case Instruction::LShr:
2375 case Instruction::AShr:
2376 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2377 assert(C1->getType()->isIntOrIntVector() &&
2378 "Tried to create a shift operation on a non-integer type!");
2385 return getTy(C1->getType(), Opcode, C1, C2);
2388 Constant *ConstantExpr::getCompare(unsigned short pred,
2389 Constant *C1, Constant *C2) {
2390 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2391 return getCompareTy(pred, C1, C2);
2394 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2395 Constant *V1, Constant *V2) {
2396 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2398 if (ReqTy == V1->getType())
2399 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2400 return SC; // Fold common cases
2402 std::vector<Constant*> argVec(3, C);
2405 ExprMapKeyType Key(Instruction::Select, argVec);
2407 // Implicitly locked.
2408 return ExprConstants->getOrCreate(ReqTy, Key);
2411 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2414 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2416 cast<PointerType>(ReqTy)->getElementType() &&
2417 "GEP indices invalid!");
2419 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2420 return FC; // Fold a few common cases...
2422 assert(isa<PointerType>(C->getType()) &&
2423 "Non-pointer type for constant GetElementPtr expression");
2424 // Look up the constant in the table first to ensure uniqueness
2425 std::vector<Constant*> ArgVec;
2426 ArgVec.reserve(NumIdx+1);
2427 ArgVec.push_back(C);
2428 for (unsigned i = 0; i != NumIdx; ++i)
2429 ArgVec.push_back(cast<Constant>(Idxs[i]));
2430 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2432 // Implicitly locked.
2433 return ExprConstants->getOrCreate(ReqTy, Key);
2436 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2438 // Get the result type of the getelementptr!
2440 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2441 assert(Ty && "GEP indices invalid!");
2442 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2443 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2446 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2448 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2453 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2454 assert(LHS->getType() == RHS->getType());
2455 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2456 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2458 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2459 return FC; // Fold a few common cases...
2461 // Look up the constant in the table first to ensure uniqueness
2462 std::vector<Constant*> ArgVec;
2463 ArgVec.push_back(LHS);
2464 ArgVec.push_back(RHS);
2465 // Get the key type with both the opcode and predicate
2466 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2468 // Implicitly locked.
2469 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2473 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2474 assert(LHS->getType() == RHS->getType());
2475 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2477 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2478 return FC; // Fold a few common cases...
2480 // Look up the constant in the table first to ensure uniqueness
2481 std::vector<Constant*> ArgVec;
2482 ArgVec.push_back(LHS);
2483 ArgVec.push_back(RHS);
2484 // Get the key type with both the opcode and predicate
2485 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2487 // Implicitly locked.
2488 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2492 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2493 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
2494 "Tried to create vicmp operation on non-vector type!");
2495 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2496 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2498 const VectorType *VTy = cast<VectorType>(LHS->getType());
2499 const Type *EltTy = VTy->getElementType();
2500 unsigned NumElts = VTy->getNumElements();
2502 // See if we can fold the element-wise comparison of the LHS and RHS.
2503 SmallVector<Constant *, 16> LHSElts, RHSElts;
2504 LHS->getVectorElements(LHSElts);
2505 RHS->getVectorElements(RHSElts);
2507 if (!LHSElts.empty() && !RHSElts.empty()) {
2508 SmallVector<Constant *, 16> Elts;
2509 for (unsigned i = 0; i != NumElts; ++i) {
2510 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2512 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2513 if (FCI->getZExtValue())
2514 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2516 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2517 } else if (FC && isa<UndefValue>(FC)) {
2518 Elts.push_back(UndefValue::get(EltTy));
2523 if (Elts.size() == NumElts)
2524 return ConstantVector::get(&Elts[0], Elts.size());
2527 // Look up the constant in the table first to ensure uniqueness
2528 std::vector<Constant*> ArgVec;
2529 ArgVec.push_back(LHS);
2530 ArgVec.push_back(RHS);
2531 // Get the key type with both the opcode and predicate
2532 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2534 // Implicitly locked.
2535 return ExprConstants->getOrCreate(LHS->getType(), Key);
2539 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2540 assert(isa<VectorType>(LHS->getType()) &&
2541 "Tried to create vfcmp operation on non-vector type!");
2542 assert(LHS->getType() == RHS->getType());
2543 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2545 const VectorType *VTy = cast<VectorType>(LHS->getType());
2546 unsigned NumElts = VTy->getNumElements();
2547 const Type *EltTy = VTy->getElementType();
2548 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2549 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2551 // See if we can fold the element-wise comparison of the LHS and RHS.
2552 SmallVector<Constant *, 16> LHSElts, RHSElts;
2553 LHS->getVectorElements(LHSElts);
2554 RHS->getVectorElements(RHSElts);
2556 if (!LHSElts.empty() && !RHSElts.empty()) {
2557 SmallVector<Constant *, 16> Elts;
2558 for (unsigned i = 0; i != NumElts; ++i) {
2559 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2561 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2562 if (FCI->getZExtValue())
2563 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2565 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2566 } else if (FC && isa<UndefValue>(FC)) {
2567 Elts.push_back(UndefValue::get(REltTy));
2572 if (Elts.size() == NumElts)
2573 return ConstantVector::get(&Elts[0], Elts.size());
2576 // Look up the constant in the table first to ensure uniqueness
2577 std::vector<Constant*> ArgVec;
2578 ArgVec.push_back(LHS);
2579 ArgVec.push_back(RHS);
2580 // Get the key type with both the opcode and predicate
2581 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2583 // Implicitly locked.
2584 return ExprConstants->getOrCreate(ResultTy, Key);
2587 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2589 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2590 return FC; // Fold a few common cases...
2591 // Look up the constant in the table first to ensure uniqueness
2592 std::vector<Constant*> ArgVec(1, Val);
2593 ArgVec.push_back(Idx);
2594 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2596 // Implicitly locked.
2597 return ExprConstants->getOrCreate(ReqTy, Key);
2600 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2601 assert(isa<VectorType>(Val->getType()) &&
2602 "Tried to create extractelement operation on non-vector type!");
2603 assert(Idx->getType() == Type::Int32Ty &&
2604 "Extractelement index must be i32 type!");
2605 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2609 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2610 Constant *Elt, Constant *Idx) {
2611 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2612 return FC; // Fold a few common cases...
2613 // Look up the constant in the table first to ensure uniqueness
2614 std::vector<Constant*> ArgVec(1, Val);
2615 ArgVec.push_back(Elt);
2616 ArgVec.push_back(Idx);
2617 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2619 // Implicitly locked.
2620 return ExprConstants->getOrCreate(ReqTy, Key);
2623 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2625 assert(isa<VectorType>(Val->getType()) &&
2626 "Tried to create insertelement operation on non-vector type!");
2627 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2628 && "Insertelement types must match!");
2629 assert(Idx->getType() == Type::Int32Ty &&
2630 "Insertelement index must be i32 type!");
2631 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2634 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2635 Constant *V2, Constant *Mask) {
2636 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2637 return FC; // Fold a few common cases...
2638 // Look up the constant in the table first to ensure uniqueness
2639 std::vector<Constant*> ArgVec(1, V1);
2640 ArgVec.push_back(V2);
2641 ArgVec.push_back(Mask);
2642 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2644 // Implicitly locked.
2645 return ExprConstants->getOrCreate(ReqTy, Key);
2648 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2650 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2651 "Invalid shuffle vector constant expr operands!");
2653 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2654 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2655 const Type *ShufTy = VectorType::get(EltTy, NElts);
2656 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2659 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2661 const unsigned *Idxs, unsigned NumIdx) {
2662 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2663 Idxs+NumIdx) == Val->getType() &&
2664 "insertvalue indices invalid!");
2665 assert(Agg->getType() == ReqTy &&
2666 "insertvalue type invalid!");
2667 assert(Agg->getType()->isFirstClassType() &&
2668 "Non-first-class type for constant InsertValue expression");
2669 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2670 assert(FC && "InsertValue constant expr couldn't be folded!");
2674 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2675 const unsigned *IdxList, unsigned NumIdx) {
2676 assert(Agg->getType()->isFirstClassType() &&
2677 "Tried to create insertelement operation on non-first-class type!");
2679 const Type *ReqTy = Agg->getType();
2682 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2684 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2685 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2688 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2689 const unsigned *Idxs, unsigned NumIdx) {
2690 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2691 Idxs+NumIdx) == ReqTy &&
2692 "extractvalue indices invalid!");
2693 assert(Agg->getType()->isFirstClassType() &&
2694 "Non-first-class type for constant extractvalue expression");
2695 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2696 assert(FC && "ExtractValue constant expr couldn't be folded!");
2700 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2701 const unsigned *IdxList, unsigned NumIdx) {
2702 assert(Agg->getType()->isFirstClassType() &&
2703 "Tried to create extractelement operation on non-first-class type!");
2706 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2707 assert(ReqTy && "extractvalue indices invalid!");
2708 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2711 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2712 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2713 if (PTy->getElementType()->isFloatingPoint()) {
2714 std::vector<Constant*> zeros(PTy->getNumElements(),
2715 ConstantFP::getNegativeZero(PTy->getElementType()));
2716 return ConstantVector::get(PTy, zeros);
2719 if (Ty->isFloatingPoint())
2720 return ConstantFP::getNegativeZero(Ty);
2722 return Constant::getNullValue(Ty);
2725 // destroyConstant - Remove the constant from the constant table...
2727 void ConstantExpr::destroyConstant() {
2728 // Implicitly locked.
2729 ExprConstants->remove(this);
2730 destroyConstantImpl();
2733 const char *ConstantExpr::getOpcodeName() const {
2734 return Instruction::getOpcodeName(getOpcode());
2737 //===----------------------------------------------------------------------===//
2738 // replaceUsesOfWithOnConstant implementations
2740 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2741 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2744 /// Note that we intentionally replace all uses of From with To here. Consider
2745 /// a large array that uses 'From' 1000 times. By handling this case all here,
2746 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2747 /// single invocation handles all 1000 uses. Handling them one at a time would
2748 /// work, but would be really slow because it would have to unique each updated
2750 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2752 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2753 Constant *ToC = cast<Constant>(To);
2755 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2756 Lookup.first.first = getType();
2757 Lookup.second = this;
2759 std::vector<Constant*> &Values = Lookup.first.second;
2760 Values.reserve(getNumOperands()); // Build replacement array.
2762 // Fill values with the modified operands of the constant array. Also,
2763 // compute whether this turns into an all-zeros array.
2764 bool isAllZeros = false;
2765 unsigned NumUpdated = 0;
2766 if (!ToC->isNullValue()) {
2767 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2768 Constant *Val = cast<Constant>(O->get());
2773 Values.push_back(Val);
2777 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2778 Constant *Val = cast<Constant>(O->get());
2783 Values.push_back(Val);
2784 if (isAllZeros) isAllZeros = Val->isNullValue();
2788 Constant *Replacement = 0;
2790 Replacement = ConstantAggregateZero::get(getType());
2792 // Check to see if we have this array type already.
2793 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
2795 ArrayConstantsTy::MapTy::iterator I =
2796 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2799 Replacement = I->second;
2801 // Okay, the new shape doesn't exist in the system yet. Instead of
2802 // creating a new constant array, inserting it, replaceallusesof'ing the
2803 // old with the new, then deleting the old... just update the current one
2805 ArrayConstants->MoveConstantToNewSlot(this, I);
2807 // Update to the new value. Optimize for the case when we have a single
2808 // operand that we're changing, but handle bulk updates efficiently.
2809 if (NumUpdated == 1) {
2810 unsigned OperandToUpdate = U-OperandList;
2811 assert(getOperand(OperandToUpdate) == From &&
2812 "ReplaceAllUsesWith broken!");
2813 setOperand(OperandToUpdate, ToC);
2815 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2816 if (getOperand(i) == From)
2823 // Otherwise, I do need to replace this with an existing value.
2824 assert(Replacement != this && "I didn't contain From!");
2826 // Everyone using this now uses the replacement.
2827 uncheckedReplaceAllUsesWith(Replacement);
2829 // Delete the old constant!
2833 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2835 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2836 Constant *ToC = cast<Constant>(To);
2838 unsigned OperandToUpdate = U-OperandList;
2839 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2841 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2842 Lookup.first.first = getType();
2843 Lookup.second = this;
2844 std::vector<Constant*> &Values = Lookup.first.second;
2845 Values.reserve(getNumOperands()); // Build replacement struct.
2848 // Fill values with the modified operands of the constant struct. Also,
2849 // compute whether this turns into an all-zeros struct.
2850 bool isAllZeros = false;
2851 if (!ToC->isNullValue()) {
2852 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2853 Values.push_back(cast<Constant>(O->get()));
2856 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2857 Constant *Val = cast<Constant>(O->get());
2858 Values.push_back(Val);
2859 if (isAllZeros) isAllZeros = Val->isNullValue();
2862 Values[OperandToUpdate] = ToC;
2864 Constant *Replacement = 0;
2866 Replacement = ConstantAggregateZero::get(getType());
2868 // Check to see if we have this array type already.
2869 sys::SmartScopedWriter<true> Writer(&*ConstantsLock);
2871 StructConstantsTy::MapTy::iterator I =
2872 StructConstants->InsertOrGetItem(Lookup, Exists);
2875 Replacement = I->second;
2877 // Okay, the new shape doesn't exist in the system yet. Instead of
2878 // creating a new constant struct, inserting it, replaceallusesof'ing the
2879 // old with the new, then deleting the old... just update the current one
2881 StructConstants->MoveConstantToNewSlot(this, I);
2883 // Update to the new value.
2884 setOperand(OperandToUpdate, ToC);
2889 assert(Replacement != this && "I didn't contain From!");
2891 // Everyone using this now uses the replacement.
2892 uncheckedReplaceAllUsesWith(Replacement);
2894 // Delete the old constant!
2898 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2900 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2902 std::vector<Constant*> Values;
2903 Values.reserve(getNumOperands()); // Build replacement array...
2904 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2905 Constant *Val = getOperand(i);
2906 if (Val == From) Val = cast<Constant>(To);
2907 Values.push_back(Val);
2910 Constant *Replacement = ConstantVector::get(getType(), Values);
2911 assert(Replacement != this && "I didn't contain From!");
2913 // Everyone using this now uses the replacement.
2914 uncheckedReplaceAllUsesWith(Replacement);
2916 // Delete the old constant!
2920 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2922 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2923 Constant *To = cast<Constant>(ToV);
2925 Constant *Replacement = 0;
2926 if (getOpcode() == Instruction::GetElementPtr) {
2927 SmallVector<Constant*, 8> Indices;
2928 Constant *Pointer = getOperand(0);
2929 Indices.reserve(getNumOperands()-1);
2930 if (Pointer == From) Pointer = To;
2932 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2933 Constant *Val = getOperand(i);
2934 if (Val == From) Val = To;
2935 Indices.push_back(Val);
2937 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2938 &Indices[0], Indices.size());
2939 } else if (getOpcode() == Instruction::ExtractValue) {
2940 Constant *Agg = getOperand(0);
2941 if (Agg == From) Agg = To;
2943 const SmallVector<unsigned, 4> &Indices = getIndices();
2944 Replacement = ConstantExpr::getExtractValue(Agg,
2945 &Indices[0], Indices.size());
2946 } else if (getOpcode() == Instruction::InsertValue) {
2947 Constant *Agg = getOperand(0);
2948 Constant *Val = getOperand(1);
2949 if (Agg == From) Agg = To;
2950 if (Val == From) Val = To;
2952 const SmallVector<unsigned, 4> &Indices = getIndices();
2953 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2954 &Indices[0], Indices.size());
2955 } else if (isCast()) {
2956 assert(getOperand(0) == From && "Cast only has one use!");
2957 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2958 } else if (getOpcode() == Instruction::Select) {
2959 Constant *C1 = getOperand(0);
2960 Constant *C2 = getOperand(1);
2961 Constant *C3 = getOperand(2);
2962 if (C1 == From) C1 = To;
2963 if (C2 == From) C2 = To;
2964 if (C3 == From) C3 = To;
2965 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2966 } else if (getOpcode() == Instruction::ExtractElement) {
2967 Constant *C1 = getOperand(0);
2968 Constant *C2 = getOperand(1);
2969 if (C1 == From) C1 = To;
2970 if (C2 == From) C2 = To;
2971 Replacement = ConstantExpr::getExtractElement(C1, C2);
2972 } else if (getOpcode() == Instruction::InsertElement) {
2973 Constant *C1 = getOperand(0);
2974 Constant *C2 = getOperand(1);
2975 Constant *C3 = getOperand(1);
2976 if (C1 == From) C1 = To;
2977 if (C2 == From) C2 = To;
2978 if (C3 == From) C3 = To;
2979 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2980 } else if (getOpcode() == Instruction::ShuffleVector) {
2981 Constant *C1 = getOperand(0);
2982 Constant *C2 = getOperand(1);
2983 Constant *C3 = getOperand(2);
2984 if (C1 == From) C1 = To;
2985 if (C2 == From) C2 = To;
2986 if (C3 == From) C3 = To;
2987 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2988 } else if (isCompare()) {
2989 Constant *C1 = getOperand(0);
2990 Constant *C2 = getOperand(1);
2991 if (C1 == From) C1 = To;
2992 if (C2 == From) C2 = To;
2993 if (getOpcode() == Instruction::ICmp)
2994 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2995 else if (getOpcode() == Instruction::FCmp)
2996 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2997 else if (getOpcode() == Instruction::VICmp)
2998 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
3000 assert(getOpcode() == Instruction::VFCmp);
3001 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
3003 } else if (getNumOperands() == 2) {
3004 Constant *C1 = getOperand(0);
3005 Constant *C2 = getOperand(1);
3006 if (C1 == From) C1 = To;
3007 if (C2 == From) C2 = To;
3008 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
3010 assert(0 && "Unknown ConstantExpr type!");
3014 assert(Replacement != this && "I didn't contain From!");
3016 // Everyone using this now uses the replacement.
3017 uncheckedReplaceAllUsesWith(Replacement);
3019 // Delete the old constant!
3023 void MDNode::replaceElement(Value *From, Value *To) {
3024 SmallVector<Value*, 4> Values;
3025 Values.reserve(getNumElements()); // Build replacement array...
3026 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
3027 Value *Val = getElement(i);
3028 if (Val == From) Val = To;
3029 Values.push_back(Val);
3032 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
3033 assert(Replacement != this && "I didn't contain From!");
3035 uncheckedReplaceAllUsesWith(Replacement);