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/ADT/DenseMap.h"
29 #include "llvm/ADT/SmallVector.h"
34 //===----------------------------------------------------------------------===//
36 //===----------------------------------------------------------------------===//
38 void Constant::destroyConstantImpl() {
39 // When a Constant is destroyed, there may be lingering
40 // references to the constant by other constants in the constant pool. These
41 // constants are implicitly dependent on the module that is being deleted,
42 // but they don't know that. Because we only find out when the CPV is
43 // deleted, we must now notify all of our users (that should only be
44 // Constants) that they are, in fact, invalid now and should be deleted.
46 while (!use_empty()) {
47 Value *V = use_back();
48 #ifndef NDEBUG // Only in -g mode...
49 if (!isa<Constant>(V))
50 DOUT << "While deleting: " << *this
51 << "\n\nUse still stuck around after Def is destroyed: "
54 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
55 Constant *CV = cast<Constant>(V);
56 CV->destroyConstant();
58 // The constant should remove itself from our use list...
59 assert((use_empty() || use_back() != V) && "Constant not removed!");
62 // Value has no outstanding references it is safe to delete it now...
66 /// canTrap - Return true if evaluation of this constant could trap. This is
67 /// true for things like constant expressions that could divide by zero.
68 bool Constant::canTrap() const {
69 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
70 // The only thing that could possibly trap are constant exprs.
71 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
72 if (!CE) return false;
74 // ConstantExpr traps if any operands can trap.
75 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
76 if (getOperand(i)->canTrap())
79 // Otherwise, only specific operations can trap.
80 switch (CE->getOpcode()) {
83 case Instruction::UDiv:
84 case Instruction::SDiv:
85 case Instruction::FDiv:
86 case Instruction::URem:
87 case Instruction::SRem:
88 case Instruction::FRem:
89 // Div and rem can trap if the RHS is not known to be non-zero.
90 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
96 /// ContainsRelocations - Return true if the constant value contains relocations
97 /// which cannot be resolved at compile time. Kind argument is used to filter
98 /// only 'interesting' sorts of relocations.
99 bool Constant::ContainsRelocations(unsigned Kind) const {
100 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
101 bool isLocal = GV->hasLocalLinkage();
102 if ((Kind & Reloc::Local) && isLocal) {
103 // Global has local linkage and 'local' kind of relocations are
108 if ((Kind & Reloc::Global) && !isLocal) {
109 // Global has non-local linkage and 'global' kind of relocations are
117 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
118 if (getOperand(i)->ContainsRelocations(Kind))
124 // Static constructor to create a '0' constant of arbitrary type...
125 Constant *Constant::getNullValue(const Type *Ty) {
126 static uint64_t zero[2] = {0, 0};
127 switch (Ty->getTypeID()) {
128 case Type::IntegerTyID:
129 return ConstantInt::get(Ty, 0);
130 case Type::FloatTyID:
131 return ConstantFP::get(APFloat(APInt(32, 0)));
132 case Type::DoubleTyID:
133 return ConstantFP::get(APFloat(APInt(64, 0)));
134 case Type::X86_FP80TyID:
135 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
136 case Type::FP128TyID:
137 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
138 case Type::PPC_FP128TyID:
139 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
140 case Type::PointerTyID:
141 return ConstantPointerNull::get(cast<PointerType>(Ty));
142 case Type::StructTyID:
143 case Type::ArrayTyID:
144 case Type::VectorTyID:
145 return ConstantAggregateZero::get(Ty);
147 // Function, Label, or Opaque type?
148 assert(!"Cannot create a null constant of that type!");
153 Constant *Constant::getAllOnesValue(const Type *Ty) {
154 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
155 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
156 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
159 // Static constructor to create an integral constant with all bits set
160 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
161 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
162 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
166 /// @returns the value for a vector integer constant of the given type that
167 /// has all its bits set to true.
168 /// @brief Get the all ones value
169 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
170 std::vector<Constant*> Elts;
171 Elts.resize(Ty->getNumElements(),
172 ConstantInt::getAllOnesValue(Ty->getElementType()));
173 assert(Elts[0] && "Not a vector integer type!");
174 return cast<ConstantVector>(ConstantVector::get(Elts));
178 /// getVectorElements - This method, which is only valid on constant of vector
179 /// type, returns the elements of the vector in the specified smallvector.
180 /// This handles breaking down a vector undef into undef elements, etc. For
181 /// constant exprs and other cases we can't handle, we return an empty vector.
182 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
183 assert(isa<VectorType>(getType()) && "Not a vector constant!");
185 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
186 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
187 Elts.push_back(CV->getOperand(i));
191 const VectorType *VT = cast<VectorType>(getType());
192 if (isa<ConstantAggregateZero>(this)) {
193 Elts.assign(VT->getNumElements(),
194 Constant::getNullValue(VT->getElementType()));
198 if (isa<UndefValue>(this)) {
199 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
203 // Unknown type, must be constant expr etc.
208 //===----------------------------------------------------------------------===//
210 //===----------------------------------------------------------------------===//
212 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
213 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
214 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
217 ConstantInt *ConstantInt::TheTrueVal = 0;
218 ConstantInt *ConstantInt::TheFalseVal = 0;
221 void CleanupTrueFalse(void *) {
222 ConstantInt::ResetTrueFalse();
226 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
228 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
229 assert(TheTrueVal == 0 && TheFalseVal == 0);
230 TheTrueVal = get(Type::Int1Ty, 1);
231 TheFalseVal = get(Type::Int1Ty, 0);
233 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
234 TrueFalseCleanup.Register();
236 return WhichOne ? TheTrueVal : TheFalseVal;
241 struct DenseMapAPIntKeyInfo {
245 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
246 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
247 bool operator==(const KeyTy& that) const {
248 return type == that.type && this->val == that.val;
250 bool operator!=(const KeyTy& that) const {
251 return !this->operator==(that);
254 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
255 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
256 static unsigned getHashValue(const KeyTy &Key) {
257 return DenseMapInfo<void*>::getHashValue(Key.type) ^
258 Key.val.getHashValue();
260 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
263 static bool isPod() { return false; }
268 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
269 DenseMapAPIntKeyInfo> IntMapTy;
270 static ManagedStatic<IntMapTy> IntConstants;
272 ConstantInt *ConstantInt::get(const IntegerType *Ty,
273 uint64_t V, bool isSigned) {
274 return get(APInt(Ty->getBitWidth(), V, isSigned));
277 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
278 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
280 // For vectors, broadcast the value.
281 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
283 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
288 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
289 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
290 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
291 // compare APInt's of different widths, which would violate an APInt class
292 // invariant which generates an assertion.
293 ConstantInt *ConstantInt::get(const APInt& V) {
294 // Get the corresponding integer type for the bit width of the value.
295 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
296 // get an existing value or the insertion position
297 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
298 ConstantInt *&Slot = (*IntConstants)[Key];
299 // if it exists, return it.
302 // otherwise create a new one, insert it, and return it.
303 return Slot = new ConstantInt(ITy, V);
306 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
307 ConstantInt *C = ConstantInt::get(V);
308 assert(C->getType() == Ty->getScalarType() &&
309 "ConstantInt type doesn't match the type implied by its value!");
311 // For vectors, broadcast the value.
312 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
314 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
319 //===----------------------------------------------------------------------===//
321 //===----------------------------------------------------------------------===//
323 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
324 if (Ty == Type::FloatTy)
325 return &APFloat::IEEEsingle;
326 if (Ty == Type::DoubleTy)
327 return &APFloat::IEEEdouble;
328 if (Ty == Type::X86_FP80Ty)
329 return &APFloat::x87DoubleExtended;
330 else if (Ty == Type::FP128Ty)
331 return &APFloat::IEEEquad;
333 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
334 return &APFloat::PPCDoubleDouble;
337 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
338 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
339 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
343 bool ConstantFP::isNullValue() const {
344 return Val.isZero() && !Val.isNegative();
347 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
348 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
350 return ConstantFP::get(apf);
353 bool ConstantFP::isExactlyValue(const APFloat& V) const {
354 return Val.bitwiseIsEqual(V);
358 struct DenseMapAPFloatKeyInfo {
361 KeyTy(const APFloat& V) : val(V){}
362 KeyTy(const KeyTy& that) : val(that.val) {}
363 bool operator==(const KeyTy& that) const {
364 return this->val.bitwiseIsEqual(that.val);
366 bool operator!=(const KeyTy& that) const {
367 return !this->operator==(that);
370 static inline KeyTy getEmptyKey() {
371 return KeyTy(APFloat(APFloat::Bogus,1));
373 static inline KeyTy getTombstoneKey() {
374 return KeyTy(APFloat(APFloat::Bogus,2));
376 static unsigned getHashValue(const KeyTy &Key) {
377 return Key.val.getHashValue();
379 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
382 static bool isPod() { return false; }
386 //---- ConstantFP::get() implementation...
388 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
389 DenseMapAPFloatKeyInfo> FPMapTy;
391 static ManagedStatic<FPMapTy> FPConstants;
393 ConstantFP *ConstantFP::get(const APFloat &V) {
394 DenseMapAPFloatKeyInfo::KeyTy Key(V);
395 ConstantFP *&Slot = (*FPConstants)[Key];
396 if (Slot) return Slot;
399 if (&V.getSemantics() == &APFloat::IEEEsingle)
401 else if (&V.getSemantics() == &APFloat::IEEEdouble)
403 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
404 Ty = Type::X86_FP80Ty;
405 else if (&V.getSemantics() == &APFloat::IEEEquad)
408 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
409 Ty = Type::PPC_FP128Ty;
412 return Slot = new ConstantFP(Ty, V);
415 /// get() - This returns a constant fp for the specified value in the
416 /// specified type. This should only be used for simple constant values like
417 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
418 Constant *ConstantFP::get(const Type *Ty, double V) {
421 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
422 APFloat::rmNearestTiesToEven, &ignored);
423 Constant *C = get(FV);
425 // For vectors, broadcast the value.
426 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
428 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
433 //===----------------------------------------------------------------------===//
434 // ConstantXXX Classes
435 //===----------------------------------------------------------------------===//
438 ConstantArray::ConstantArray(const ArrayType *T,
439 const std::vector<Constant*> &V)
440 : Constant(T, ConstantArrayVal,
441 OperandTraits<ConstantArray>::op_end(this) - V.size(),
443 assert(V.size() == T->getNumElements() &&
444 "Invalid initializer vector for constant array");
445 Use *OL = OperandList;
446 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
449 assert((C->getType() == T->getElementType() ||
451 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
452 "Initializer for array element doesn't match array element type!");
458 ConstantStruct::ConstantStruct(const StructType *T,
459 const std::vector<Constant*> &V)
460 : Constant(T, ConstantStructVal,
461 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
463 assert(V.size() == T->getNumElements() &&
464 "Invalid initializer vector for constant structure");
465 Use *OL = OperandList;
466 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
469 assert((C->getType() == T->getElementType(I-V.begin()) ||
470 ((T->getElementType(I-V.begin())->isAbstract() ||
471 C->getType()->isAbstract()) &&
472 T->getElementType(I-V.begin())->getTypeID() ==
473 C->getType()->getTypeID())) &&
474 "Initializer for struct element doesn't match struct element type!");
480 ConstantVector::ConstantVector(const VectorType *T,
481 const std::vector<Constant*> &V)
482 : Constant(T, ConstantVectorVal,
483 OperandTraits<ConstantVector>::op_end(this) - V.size(),
485 Use *OL = OperandList;
486 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
489 assert((C->getType() == T->getElementType() ||
491 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
492 "Initializer for vector element doesn't match vector element type!");
499 // We declare several classes private to this file, so use an anonymous
503 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
504 /// behind the scenes to implement unary constant exprs.
505 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
506 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
508 // allocate space for exactly one operand
509 void *operator new(size_t s) {
510 return User::operator new(s, 1);
512 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
513 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
516 /// Transparently provide more efficient getOperand methods.
517 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
520 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
521 /// behind the scenes to implement binary constant exprs.
522 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
523 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
525 // allocate space for exactly two operands
526 void *operator new(size_t s) {
527 return User::operator new(s, 2);
529 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
530 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
534 /// Transparently provide more efficient getOperand methods.
535 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
538 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
539 /// behind the scenes to implement select constant exprs.
540 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
541 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
543 // allocate space for exactly three operands
544 void *operator new(size_t s) {
545 return User::operator new(s, 3);
547 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
548 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
553 /// Transparently provide more efficient getOperand methods.
554 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
557 /// ExtractElementConstantExpr - This class is private to
558 /// Constants.cpp, and is used behind the scenes to implement
559 /// extractelement constant exprs.
560 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
561 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
563 // allocate space for exactly two operands
564 void *operator new(size_t s) {
565 return User::operator new(s, 2);
567 ExtractElementConstantExpr(Constant *C1, Constant *C2)
568 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
569 Instruction::ExtractElement, &Op<0>(), 2) {
573 /// Transparently provide more efficient getOperand methods.
574 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
577 /// InsertElementConstantExpr - This class is private to
578 /// Constants.cpp, and is used behind the scenes to implement
579 /// insertelement constant exprs.
580 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
581 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
583 // allocate space for exactly three operands
584 void *operator new(size_t s) {
585 return User::operator new(s, 3);
587 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
588 : ConstantExpr(C1->getType(), Instruction::InsertElement,
594 /// Transparently provide more efficient getOperand methods.
595 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
598 /// ShuffleVectorConstantExpr - This class is private to
599 /// Constants.cpp, and is used behind the scenes to implement
600 /// shufflevector constant exprs.
601 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
602 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
604 // allocate space for exactly three operands
605 void *operator new(size_t s) {
606 return User::operator new(s, 3);
608 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
609 : ConstantExpr(VectorType::get(
610 cast<VectorType>(C1->getType())->getElementType(),
611 cast<VectorType>(C3->getType())->getNumElements()),
612 Instruction::ShuffleVector,
618 /// Transparently provide more efficient getOperand methods.
619 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
622 /// ExtractValueConstantExpr - This class is private to
623 /// Constants.cpp, and is used behind the scenes to implement
624 /// extractvalue constant exprs.
625 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
626 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
628 // allocate space for exactly one operand
629 void *operator new(size_t s) {
630 return User::operator new(s, 1);
632 ExtractValueConstantExpr(Constant *Agg,
633 const SmallVector<unsigned, 4> &IdxList,
635 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
640 /// Indices - These identify which value to extract.
641 const SmallVector<unsigned, 4> Indices;
643 /// Transparently provide more efficient getOperand methods.
644 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
647 /// InsertValueConstantExpr - This class is private to
648 /// Constants.cpp, and is used behind the scenes to implement
649 /// insertvalue constant exprs.
650 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
651 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
653 // allocate space for exactly one operand
654 void *operator new(size_t s) {
655 return User::operator new(s, 2);
657 InsertValueConstantExpr(Constant *Agg, Constant *Val,
658 const SmallVector<unsigned, 4> &IdxList,
660 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
666 /// Indices - These identify the position for the insertion.
667 const SmallVector<unsigned, 4> Indices;
669 /// Transparently provide more efficient getOperand methods.
670 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
674 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
675 /// used behind the scenes to implement getelementpr constant exprs.
676 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
677 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
680 static GetElementPtrConstantExpr *Create(Constant *C,
681 const std::vector<Constant*>&IdxList,
682 const Type *DestTy) {
683 return new(IdxList.size() + 1)
684 GetElementPtrConstantExpr(C, IdxList, DestTy);
686 /// Transparently provide more efficient getOperand methods.
687 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
690 // CompareConstantExpr - This class is private to Constants.cpp, and is used
691 // behind the scenes to implement ICmp and FCmp constant expressions. This is
692 // needed in order to store the predicate value for these instructions.
693 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
694 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
695 // allocate space for exactly two operands
696 void *operator new(size_t s) {
697 return User::operator new(s, 2);
699 unsigned short predicate;
700 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
701 unsigned short pred, Constant* LHS, Constant* RHS)
702 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
706 /// Transparently provide more efficient getOperand methods.
707 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
710 } // end anonymous namespace
713 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
715 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
718 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
720 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
723 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
725 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
728 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
730 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
733 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
735 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
738 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
740 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
743 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
745 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
748 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
750 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
753 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
756 GetElementPtrConstantExpr::GetElementPtrConstantExpr
758 const std::vector<Constant*> &IdxList,
760 : ConstantExpr(DestTy, Instruction::GetElementPtr,
761 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
762 - (IdxList.size()+1),
765 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
766 OperandList[i+1] = IdxList[i];
769 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
773 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
775 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
778 } // End llvm namespace
781 // Utility function for determining if a ConstantExpr is a CastOp or not. This
782 // can't be inline because we don't want to #include Instruction.h into
784 bool ConstantExpr::isCast() const {
785 return Instruction::isCast(getOpcode());
788 bool ConstantExpr::isCompare() const {
789 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
790 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
793 bool ConstantExpr::hasIndices() const {
794 return getOpcode() == Instruction::ExtractValue ||
795 getOpcode() == Instruction::InsertValue;
798 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
799 if (const ExtractValueConstantExpr *EVCE =
800 dyn_cast<ExtractValueConstantExpr>(this))
801 return EVCE->Indices;
803 return cast<InsertValueConstantExpr>(this)->Indices;
806 /// ConstantExpr::get* - Return some common constants without having to
807 /// specify the full Instruction::OPCODE identifier.
809 Constant *ConstantExpr::getNeg(Constant *C) {
810 // API compatibility: Adjust integer opcodes to floating-point opcodes.
811 if (C->getType()->isFPOrFPVector())
813 assert(C->getType()->isIntOrIntVector() &&
814 "Cannot NEG a nonintegral value!");
815 return get(Instruction::Sub,
816 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
819 Constant *ConstantExpr::getFNeg(Constant *C) {
820 assert(C->getType()->isFPOrFPVector() &&
821 "Cannot FNEG a non-floating-point value!");
822 return get(Instruction::FSub,
823 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
826 Constant *ConstantExpr::getNot(Constant *C) {
827 assert(C->getType()->isIntOrIntVector() &&
828 "Cannot NOT a nonintegral value!");
829 return get(Instruction::Xor, C,
830 Constant::getAllOnesValue(C->getType()));
832 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
833 return get(Instruction::Add, C1, C2);
835 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
836 return get(Instruction::FAdd, C1, C2);
838 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
839 return get(Instruction::Sub, C1, C2);
841 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
842 return get(Instruction::FSub, C1, C2);
844 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
845 return get(Instruction::Mul, C1, C2);
847 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
848 return get(Instruction::FMul, C1, C2);
850 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
851 return get(Instruction::UDiv, C1, C2);
853 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
854 return get(Instruction::SDiv, C1, C2);
856 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
857 return get(Instruction::FDiv, C1, C2);
859 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
860 return get(Instruction::URem, C1, C2);
862 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
863 return get(Instruction::SRem, C1, C2);
865 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
866 return get(Instruction::FRem, C1, C2);
868 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
869 return get(Instruction::And, C1, C2);
871 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
872 return get(Instruction::Or, C1, C2);
874 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
875 return get(Instruction::Xor, C1, C2);
877 unsigned ConstantExpr::getPredicate() const {
878 assert(getOpcode() == Instruction::FCmp ||
879 getOpcode() == Instruction::ICmp ||
880 getOpcode() == Instruction::VFCmp ||
881 getOpcode() == Instruction::VICmp);
882 return ((const CompareConstantExpr*)this)->predicate;
884 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
885 return get(Instruction::Shl, C1, C2);
887 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
888 return get(Instruction::LShr, C1, C2);
890 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
891 return get(Instruction::AShr, C1, C2);
894 /// getWithOperandReplaced - Return a constant expression identical to this
895 /// one, but with the specified operand set to the specified value.
897 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
898 assert(OpNo < getNumOperands() && "Operand num is out of range!");
899 assert(Op->getType() == getOperand(OpNo)->getType() &&
900 "Replacing operand with value of different type!");
901 if (getOperand(OpNo) == Op)
902 return const_cast<ConstantExpr*>(this);
904 Constant *Op0, *Op1, *Op2;
905 switch (getOpcode()) {
906 case Instruction::Trunc:
907 case Instruction::ZExt:
908 case Instruction::SExt:
909 case Instruction::FPTrunc:
910 case Instruction::FPExt:
911 case Instruction::UIToFP:
912 case Instruction::SIToFP:
913 case Instruction::FPToUI:
914 case Instruction::FPToSI:
915 case Instruction::PtrToInt:
916 case Instruction::IntToPtr:
917 case Instruction::BitCast:
918 return ConstantExpr::getCast(getOpcode(), Op, getType());
919 case Instruction::Select:
920 Op0 = (OpNo == 0) ? Op : getOperand(0);
921 Op1 = (OpNo == 1) ? Op : getOperand(1);
922 Op2 = (OpNo == 2) ? Op : getOperand(2);
923 return ConstantExpr::getSelect(Op0, Op1, Op2);
924 case Instruction::InsertElement:
925 Op0 = (OpNo == 0) ? Op : getOperand(0);
926 Op1 = (OpNo == 1) ? Op : getOperand(1);
927 Op2 = (OpNo == 2) ? Op : getOperand(2);
928 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
929 case Instruction::ExtractElement:
930 Op0 = (OpNo == 0) ? Op : getOperand(0);
931 Op1 = (OpNo == 1) ? Op : getOperand(1);
932 return ConstantExpr::getExtractElement(Op0, Op1);
933 case Instruction::ShuffleVector:
934 Op0 = (OpNo == 0) ? Op : getOperand(0);
935 Op1 = (OpNo == 1) ? Op : getOperand(1);
936 Op2 = (OpNo == 2) ? Op : getOperand(2);
937 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
938 case Instruction::GetElementPtr: {
939 SmallVector<Constant*, 8> Ops;
940 Ops.resize(getNumOperands()-1);
941 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
942 Ops[i-1] = getOperand(i);
944 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
946 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
949 assert(getNumOperands() == 2 && "Must be binary operator?");
950 Op0 = (OpNo == 0) ? Op : getOperand(0);
951 Op1 = (OpNo == 1) ? Op : getOperand(1);
952 return ConstantExpr::get(getOpcode(), Op0, Op1);
956 /// getWithOperands - This returns the current constant expression with the
957 /// operands replaced with the specified values. The specified operands must
958 /// match count and type with the existing ones.
959 Constant *ConstantExpr::
960 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
961 assert(NumOps == getNumOperands() && "Operand count mismatch!");
962 bool AnyChange = false;
963 for (unsigned i = 0; i != NumOps; ++i) {
964 assert(Ops[i]->getType() == getOperand(i)->getType() &&
965 "Operand type mismatch!");
966 AnyChange |= Ops[i] != getOperand(i);
968 if (!AnyChange) // No operands changed, return self.
969 return const_cast<ConstantExpr*>(this);
971 switch (getOpcode()) {
972 case Instruction::Trunc:
973 case Instruction::ZExt:
974 case Instruction::SExt:
975 case Instruction::FPTrunc:
976 case Instruction::FPExt:
977 case Instruction::UIToFP:
978 case Instruction::SIToFP:
979 case Instruction::FPToUI:
980 case Instruction::FPToSI:
981 case Instruction::PtrToInt:
982 case Instruction::IntToPtr:
983 case Instruction::BitCast:
984 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
985 case Instruction::Select:
986 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
987 case Instruction::InsertElement:
988 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
989 case Instruction::ExtractElement:
990 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
991 case Instruction::ShuffleVector:
992 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
993 case Instruction::GetElementPtr:
994 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
995 case Instruction::ICmp:
996 case Instruction::FCmp:
997 case Instruction::VICmp:
998 case Instruction::VFCmp:
999 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1001 assert(getNumOperands() == 2 && "Must be binary operator?");
1002 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
1007 //===----------------------------------------------------------------------===//
1008 // isValueValidForType implementations
1010 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
1011 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1012 if (Ty == Type::Int1Ty)
1013 return Val == 0 || Val == 1;
1015 return true; // always true, has to fit in largest type
1016 uint64_t Max = (1ll << NumBits) - 1;
1020 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
1021 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
1022 if (Ty == Type::Int1Ty)
1023 return Val == 0 || Val == 1 || Val == -1;
1025 return true; // always true, has to fit in largest type
1026 int64_t Min = -(1ll << (NumBits-1));
1027 int64_t Max = (1ll << (NumBits-1)) - 1;
1028 return (Val >= Min && Val <= Max);
1031 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
1032 // convert modifies in place, so make a copy.
1033 APFloat Val2 = APFloat(Val);
1035 switch (Ty->getTypeID()) {
1037 return false; // These can't be represented as floating point!
1039 // FIXME rounding mode needs to be more flexible
1040 case Type::FloatTyID: {
1041 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1043 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1046 case Type::DoubleTyID: {
1047 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
1048 &Val2.getSemantics() == &APFloat::IEEEdouble)
1050 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1053 case Type::X86_FP80TyID:
1054 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1055 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1056 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1057 case Type::FP128TyID:
1058 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1059 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1060 &Val2.getSemantics() == &APFloat::IEEEquad;
1061 case Type::PPC_FP128TyID:
1062 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
1063 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1064 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1068 //===----------------------------------------------------------------------===//
1069 // Factory Function Implementation
1072 // The number of operands for each ConstantCreator::create method is
1073 // determined by the ConstantTraits template.
1074 // ConstantCreator - A class that is used to create constants by
1075 // ValueMap*. This class should be partially specialized if there is
1076 // something strange that needs to be done to interface to the ctor for the
1080 template<class ValType>
1081 struct ConstantTraits;
1083 template<typename T, typename Alloc>
1084 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1085 static unsigned uses(const std::vector<T, Alloc>& v) {
1090 template<class ConstantClass, class TypeClass, class ValType>
1091 struct VISIBILITY_HIDDEN ConstantCreator {
1092 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1093 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1097 template<class ConstantClass, class TypeClass>
1098 struct VISIBILITY_HIDDEN ConvertConstantType {
1099 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1100 assert(0 && "This type cannot be converted!\n");
1105 template<class ValType, class TypeClass, class ConstantClass,
1106 bool HasLargeKey = false /*true for arrays and structs*/ >
1107 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1109 typedef std::pair<const Type*, ValType> MapKey;
1110 typedef std::map<MapKey, Constant *> MapTy;
1111 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1112 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1114 /// Map - This is the main map from the element descriptor to the Constants.
1115 /// This is the primary way we avoid creating two of the same shape
1119 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1120 /// from the constants to their element in Map. This is important for
1121 /// removal of constants from the array, which would otherwise have to scan
1122 /// through the map with very large keys.
1123 InverseMapTy InverseMap;
1125 /// AbstractTypeMap - Map for abstract type constants.
1127 AbstractTypeMapTy AbstractTypeMap;
1130 typename MapTy::iterator map_end() { return Map.end(); }
1132 /// InsertOrGetItem - Return an iterator for the specified element.
1133 /// If the element exists in the map, the returned iterator points to the
1134 /// entry and Exists=true. If not, the iterator points to the newly
1135 /// inserted entry and returns Exists=false. Newly inserted entries have
1136 /// I->second == 0, and should be filled in.
1137 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1140 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1141 Exists = !IP.second;
1146 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1148 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1149 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1150 IMI->second->second == CP &&
1151 "InverseMap corrupt!");
1155 typename MapTy::iterator I =
1156 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1158 if (I == Map.end() || I->second != CP) {
1159 // FIXME: This should not use a linear scan. If this gets to be a
1160 // performance problem, someone should look at this.
1161 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1168 /// getOrCreate - Return the specified constant from the map, creating it if
1170 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1171 MapKey Lookup(Ty, V);
1172 typename MapTy::iterator I = Map.find(Lookup);
1173 // Is it in the map?
1175 return static_cast<ConstantClass *>(I->second);
1177 // If no preexisting value, create one now...
1178 ConstantClass *Result =
1179 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1181 assert(Result->getType() == Ty && "Type specified is not correct!");
1182 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1184 if (HasLargeKey) // Remember the reverse mapping if needed.
1185 InverseMap.insert(std::make_pair(Result, I));
1187 // If the type of the constant is abstract, make sure that an entry exists
1188 // for it in the AbstractTypeMap.
1189 if (Ty->isAbstract()) {
1190 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
1192 if (TI == AbstractTypeMap.end()) {
1193 // Add ourselves to the ATU list of the type.
1194 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1196 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1202 void remove(ConstantClass *CP) {
1203 typename MapTy::iterator I = FindExistingElement(CP);
1204 assert(I != Map.end() && "Constant not found in constant table!");
1205 assert(I->second == CP && "Didn't find correct element?");
1207 if (HasLargeKey) // Remember the reverse mapping if needed.
1208 InverseMap.erase(CP);
1210 // Now that we found the entry, make sure this isn't the entry that
1211 // the AbstractTypeMap points to.
1212 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1213 if (Ty->isAbstract()) {
1214 assert(AbstractTypeMap.count(Ty) &&
1215 "Abstract type not in AbstractTypeMap?");
1216 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1217 if (ATMEntryIt == I) {
1218 // Yes, we are removing the representative entry for this type.
1219 // See if there are any other entries of the same type.
1220 typename MapTy::iterator TmpIt = ATMEntryIt;
1222 // First check the entry before this one...
1223 if (TmpIt != Map.begin()) {
1225 if (TmpIt->first.first != Ty) // Not the same type, move back...
1229 // If we didn't find the same type, try to move forward...
1230 if (TmpIt == ATMEntryIt) {
1232 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1233 --TmpIt; // No entry afterwards with the same type
1236 // If there is another entry in the map of the same abstract type,
1237 // update the AbstractTypeMap entry now.
1238 if (TmpIt != ATMEntryIt) {
1241 // Otherwise, we are removing the last instance of this type
1242 // from the table. Remove from the ATM, and from user list.
1243 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1244 AbstractTypeMap.erase(Ty);
1253 /// MoveConstantToNewSlot - If we are about to change C to be the element
1254 /// specified by I, update our internal data structures to reflect this
1256 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1257 // First, remove the old location of the specified constant in the map.
1258 typename MapTy::iterator OldI = FindExistingElement(C);
1259 assert(OldI != Map.end() && "Constant not found in constant table!");
1260 assert(OldI->second == C && "Didn't find correct element?");
1262 // If this constant is the representative element for its abstract type,
1263 // update the AbstractTypeMap so that the representative element is I.
1264 if (C->getType()->isAbstract()) {
1265 typename AbstractTypeMapTy::iterator ATI =
1266 AbstractTypeMap.find(C->getType());
1267 assert(ATI != AbstractTypeMap.end() &&
1268 "Abstract type not in AbstractTypeMap?");
1269 if (ATI->second == OldI)
1273 // Remove the old entry from the map.
1276 // Update the inverse map so that we know that this constant is now
1277 // located at descriptor I.
1279 assert(I->second == C && "Bad inversemap entry!");
1284 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1285 typename AbstractTypeMapTy::iterator I =
1286 AbstractTypeMap.find(cast<Type>(OldTy));
1288 assert(I != AbstractTypeMap.end() &&
1289 "Abstract type not in AbstractTypeMap?");
1291 // Convert a constant at a time until the last one is gone. The last one
1292 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1293 // eliminated eventually.
1295 ConvertConstantType<ConstantClass,
1296 TypeClass>::convert(
1297 static_cast<ConstantClass *>(I->second->second),
1298 cast<TypeClass>(NewTy));
1300 I = AbstractTypeMap.find(cast<Type>(OldTy));
1301 } while (I != AbstractTypeMap.end());
1304 // If the type became concrete without being refined to any other existing
1305 // type, we just remove ourselves from the ATU list.
1306 void typeBecameConcrete(const DerivedType *AbsTy) {
1307 AbsTy->removeAbstractTypeUser(this);
1311 DOUT << "Constant.cpp: ValueMap\n";
1318 //---- ConstantAggregateZero::get() implementation...
1321 // ConstantAggregateZero does not take extra "value" argument...
1322 template<class ValType>
1323 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1324 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1325 return new ConstantAggregateZero(Ty);
1330 struct ConvertConstantType<ConstantAggregateZero, Type> {
1331 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1332 // Make everyone now use a constant of the new type...
1333 Constant *New = ConstantAggregateZero::get(NewTy);
1334 assert(New != OldC && "Didn't replace constant??");
1335 OldC->uncheckedReplaceAllUsesWith(New);
1336 OldC->destroyConstant(); // This constant is now dead, destroy it.
1341 static ManagedStatic<ValueMap<char, Type,
1342 ConstantAggregateZero> > AggZeroConstants;
1344 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1346 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1347 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1348 "Cannot create an aggregate zero of non-aggregate type!");
1349 return AggZeroConstants->getOrCreate(Ty, 0);
1352 /// destroyConstant - Remove the constant from the constant table...
1354 void ConstantAggregateZero::destroyConstant() {
1355 AggZeroConstants->remove(this);
1356 destroyConstantImpl();
1359 //---- ConstantArray::get() implementation...
1363 struct ConvertConstantType<ConstantArray, ArrayType> {
1364 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1365 // Make everyone now use a constant of the new type...
1366 std::vector<Constant*> C;
1367 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1368 C.push_back(cast<Constant>(OldC->getOperand(i)));
1369 Constant *New = ConstantArray::get(NewTy, C);
1370 assert(New != OldC && "Didn't replace constant??");
1371 OldC->uncheckedReplaceAllUsesWith(New);
1372 OldC->destroyConstant(); // This constant is now dead, destroy it.
1377 static std::vector<Constant*> getValType(ConstantArray *CA) {
1378 std::vector<Constant*> Elements;
1379 Elements.reserve(CA->getNumOperands());
1380 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1381 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1385 typedef ValueMap<std::vector<Constant*>, ArrayType,
1386 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1387 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1389 Constant *ConstantArray::get(const ArrayType *Ty,
1390 const std::vector<Constant*> &V) {
1391 // If this is an all-zero array, return a ConstantAggregateZero object
1394 if (!C->isNullValue())
1395 return ArrayConstants->getOrCreate(Ty, V);
1396 for (unsigned i = 1, e = V.size(); i != e; ++i)
1398 return ArrayConstants->getOrCreate(Ty, V);
1400 return ConstantAggregateZero::get(Ty);
1403 /// destroyConstant - Remove the constant from the constant table...
1405 void ConstantArray::destroyConstant() {
1406 ArrayConstants->remove(this);
1407 destroyConstantImpl();
1410 /// ConstantArray::get(const string&) - Return an array that is initialized to
1411 /// contain the specified string. If length is zero then a null terminator is
1412 /// added to the specified string so that it may be used in a natural way.
1413 /// Otherwise, the length parameter specifies how much of the string to use
1414 /// and it won't be null terminated.
1416 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1417 std::vector<Constant*> ElementVals;
1418 for (unsigned i = 0; i < Str.length(); ++i)
1419 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1421 // Add a null terminator to the string...
1423 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1426 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1427 return ConstantArray::get(ATy, ElementVals);
1430 /// isString - This method returns true if the array is an array of i8, and
1431 /// if the elements of the array are all ConstantInt's.
1432 bool ConstantArray::isString() const {
1433 // Check the element type for i8...
1434 if (getType()->getElementType() != Type::Int8Ty)
1436 // Check the elements to make sure they are all integers, not constant
1438 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1439 if (!isa<ConstantInt>(getOperand(i)))
1444 /// isCString - This method returns true if the array is a string (see
1445 /// isString) and it ends in a null byte \\0 and does not contains any other
1446 /// null bytes except its terminator.
1447 bool ConstantArray::isCString() const {
1448 // Check the element type for i8...
1449 if (getType()->getElementType() != Type::Int8Ty)
1451 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1452 // Last element must be a null.
1453 if (getOperand(getNumOperands()-1) != Zero)
1455 // Other elements must be non-null integers.
1456 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1457 if (!isa<ConstantInt>(getOperand(i)))
1459 if (getOperand(i) == Zero)
1466 /// getAsString - If the sub-element type of this array is i8
1467 /// then this method converts the array to an std::string and returns it.
1468 /// Otherwise, it asserts out.
1470 std::string ConstantArray::getAsString() const {
1471 assert(isString() && "Not a string!");
1473 Result.reserve(getNumOperands());
1474 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1475 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1480 //---- ConstantStruct::get() implementation...
1485 struct ConvertConstantType<ConstantStruct, StructType> {
1486 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1487 // Make everyone now use a constant of the new type...
1488 std::vector<Constant*> C;
1489 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1490 C.push_back(cast<Constant>(OldC->getOperand(i)));
1491 Constant *New = ConstantStruct::get(NewTy, C);
1492 assert(New != OldC && "Didn't replace constant??");
1494 OldC->uncheckedReplaceAllUsesWith(New);
1495 OldC->destroyConstant(); // This constant is now dead, destroy it.
1500 typedef ValueMap<std::vector<Constant*>, StructType,
1501 ConstantStruct, true /*largekey*/> StructConstantsTy;
1502 static ManagedStatic<StructConstantsTy> StructConstants;
1504 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1505 std::vector<Constant*> Elements;
1506 Elements.reserve(CS->getNumOperands());
1507 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1508 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1512 Constant *ConstantStruct::get(const StructType *Ty,
1513 const std::vector<Constant*> &V) {
1514 // Create a ConstantAggregateZero value if all elements are zeros...
1515 for (unsigned i = 0, e = V.size(); i != e; ++i)
1516 if (!V[i]->isNullValue())
1517 return StructConstants->getOrCreate(Ty, V);
1519 return ConstantAggregateZero::get(Ty);
1522 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1523 std::vector<const Type*> StructEls;
1524 StructEls.reserve(V.size());
1525 for (unsigned i = 0, e = V.size(); i != e; ++i)
1526 StructEls.push_back(V[i]->getType());
1527 return get(StructType::get(StructEls, packed), V);
1530 // destroyConstant - Remove the constant from the constant table...
1532 void ConstantStruct::destroyConstant() {
1533 StructConstants->remove(this);
1534 destroyConstantImpl();
1537 //---- ConstantVector::get() implementation...
1541 struct ConvertConstantType<ConstantVector, VectorType> {
1542 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1543 // Make everyone now use a constant of the new type...
1544 std::vector<Constant*> C;
1545 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1546 C.push_back(cast<Constant>(OldC->getOperand(i)));
1547 Constant *New = ConstantVector::get(NewTy, C);
1548 assert(New != OldC && "Didn't replace constant??");
1549 OldC->uncheckedReplaceAllUsesWith(New);
1550 OldC->destroyConstant(); // This constant is now dead, destroy it.
1555 static std::vector<Constant*> getValType(ConstantVector *CP) {
1556 std::vector<Constant*> Elements;
1557 Elements.reserve(CP->getNumOperands());
1558 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1559 Elements.push_back(CP->getOperand(i));
1563 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1564 ConstantVector> > VectorConstants;
1566 Constant *ConstantVector::get(const VectorType *Ty,
1567 const std::vector<Constant*> &V) {
1568 assert(!V.empty() && "Vectors can't be empty");
1569 // If this is an all-undef or alll-zero vector, return a
1570 // ConstantAggregateZero or UndefValue.
1572 bool isZero = C->isNullValue();
1573 bool isUndef = isa<UndefValue>(C);
1575 if (isZero || isUndef) {
1576 for (unsigned i = 1, e = V.size(); i != e; ++i)
1578 isZero = isUndef = false;
1584 return ConstantAggregateZero::get(Ty);
1586 return UndefValue::get(Ty);
1587 return VectorConstants->getOrCreate(Ty, V);
1590 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1591 assert(!V.empty() && "Cannot infer type if V is empty");
1592 return get(VectorType::get(V.front()->getType(),V.size()), V);
1595 // destroyConstant - Remove the constant from the constant table...
1597 void ConstantVector::destroyConstant() {
1598 VectorConstants->remove(this);
1599 destroyConstantImpl();
1602 /// This function will return true iff every element in this vector constant
1603 /// is set to all ones.
1604 /// @returns true iff this constant's emements are all set to all ones.
1605 /// @brief Determine if the value is all ones.
1606 bool ConstantVector::isAllOnesValue() const {
1607 // Check out first element.
1608 const Constant *Elt = getOperand(0);
1609 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1610 if (!CI || !CI->isAllOnesValue()) return false;
1611 // Then make sure all remaining elements point to the same value.
1612 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1613 if (getOperand(I) != Elt) return false;
1618 /// getSplatValue - If this is a splat constant, where all of the
1619 /// elements have the same value, return that value. Otherwise return null.
1620 Constant *ConstantVector::getSplatValue() {
1621 // Check out first element.
1622 Constant *Elt = getOperand(0);
1623 // Then make sure all remaining elements point to the same value.
1624 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1625 if (getOperand(I) != Elt) return 0;
1629 //---- ConstantPointerNull::get() implementation...
1633 // ConstantPointerNull does not take extra "value" argument...
1634 template<class ValType>
1635 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1636 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1637 return new ConstantPointerNull(Ty);
1642 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1643 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1644 // Make everyone now use a constant of the new type...
1645 Constant *New = ConstantPointerNull::get(NewTy);
1646 assert(New != OldC && "Didn't replace constant??");
1647 OldC->uncheckedReplaceAllUsesWith(New);
1648 OldC->destroyConstant(); // This constant is now dead, destroy it.
1653 static ManagedStatic<ValueMap<char, PointerType,
1654 ConstantPointerNull> > NullPtrConstants;
1656 static char getValType(ConstantPointerNull *) {
1661 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1662 return NullPtrConstants->getOrCreate(Ty, 0);
1665 // destroyConstant - Remove the constant from the constant table...
1667 void ConstantPointerNull::destroyConstant() {
1668 NullPtrConstants->remove(this);
1669 destroyConstantImpl();
1673 //---- UndefValue::get() implementation...
1677 // UndefValue does not take extra "value" argument...
1678 template<class ValType>
1679 struct ConstantCreator<UndefValue, Type, ValType> {
1680 static UndefValue *create(const Type *Ty, const ValType &V) {
1681 return new UndefValue(Ty);
1686 struct ConvertConstantType<UndefValue, Type> {
1687 static void convert(UndefValue *OldC, const Type *NewTy) {
1688 // Make everyone now use a constant of the new type.
1689 Constant *New = UndefValue::get(NewTy);
1690 assert(New != OldC && "Didn't replace constant??");
1691 OldC->uncheckedReplaceAllUsesWith(New);
1692 OldC->destroyConstant(); // This constant is now dead, destroy it.
1697 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1699 static char getValType(UndefValue *) {
1704 UndefValue *UndefValue::get(const Type *Ty) {
1705 return UndefValueConstants->getOrCreate(Ty, 0);
1708 // destroyConstant - Remove the constant from the constant table.
1710 void UndefValue::destroyConstant() {
1711 UndefValueConstants->remove(this);
1712 destroyConstantImpl();
1715 //---- MDString::get() implementation
1718 MDString::MDString(const char *begin, const char *end)
1719 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1720 StrBegin(begin), StrEnd(end) {}
1722 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1724 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1725 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(StrBegin,
1727 MDString *&S = Entry.getValue();
1728 if (!S) S = new MDString(Entry.getKeyData(),
1729 Entry.getKeyData() + Entry.getKeyLength());
1733 void MDString::destroyConstant() {
1734 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1735 destroyConstantImpl();
1738 //---- MDNode::get() implementation
1741 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1743 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1744 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1745 for (unsigned i = 0; i != NumVals; ++i)
1746 Node.push_back(ElementVH(Vals[i], this));
1749 void MDNode::Profile(FoldingSetNodeID &ID) const {
1750 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1754 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1755 FoldingSetNodeID ID;
1756 for (unsigned i = 0; i != NumVals; ++i)
1757 ID.AddPointer(Vals[i]);
1760 if (MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint))
1763 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1764 MDNode *N = new(0) MDNode(Vals, NumVals);
1765 MDNodeSet->InsertNode(N, InsertPoint);
1769 void MDNode::destroyConstant() {
1770 MDNodeSet->RemoveNode(this);
1771 destroyConstantImpl();
1774 //---- ConstantExpr::get() implementations...
1779 struct ExprMapKeyType {
1780 typedef SmallVector<unsigned, 4> IndexList;
1782 ExprMapKeyType(unsigned opc,
1783 const std::vector<Constant*> &ops,
1784 unsigned short pred = 0,
1785 const IndexList &inds = IndexList())
1786 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1789 std::vector<Constant*> operands;
1791 bool operator==(const ExprMapKeyType& that) const {
1792 return this->opcode == that.opcode &&
1793 this->predicate == that.predicate &&
1794 this->operands == that.operands &&
1795 this->indices == that.indices;
1797 bool operator<(const ExprMapKeyType & that) const {
1798 return this->opcode < that.opcode ||
1799 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1800 (this->opcode == that.opcode && this->predicate == that.predicate &&
1801 this->operands < that.operands) ||
1802 (this->opcode == that.opcode && this->predicate == that.predicate &&
1803 this->operands == that.operands && this->indices < that.indices);
1806 bool operator!=(const ExprMapKeyType& that) const {
1807 return !(*this == that);
1815 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1816 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1817 unsigned short pred = 0) {
1818 if (Instruction::isCast(V.opcode))
1819 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1820 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1821 V.opcode < Instruction::BinaryOpsEnd))
1822 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1823 if (V.opcode == Instruction::Select)
1824 return new SelectConstantExpr(V.operands[0], V.operands[1],
1826 if (V.opcode == Instruction::ExtractElement)
1827 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1828 if (V.opcode == Instruction::InsertElement)
1829 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1831 if (V.opcode == Instruction::ShuffleVector)
1832 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1834 if (V.opcode == Instruction::InsertValue)
1835 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1837 if (V.opcode == Instruction::ExtractValue)
1838 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1839 if (V.opcode == Instruction::GetElementPtr) {
1840 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1841 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1844 // The compare instructions are weird. We have to encode the predicate
1845 // value and it is combined with the instruction opcode by multiplying
1846 // the opcode by one hundred. We must decode this to get the predicate.
1847 if (V.opcode == Instruction::ICmp)
1848 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1849 V.operands[0], V.operands[1]);
1850 if (V.opcode == Instruction::FCmp)
1851 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1852 V.operands[0], V.operands[1]);
1853 if (V.opcode == Instruction::VICmp)
1854 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1855 V.operands[0], V.operands[1]);
1856 if (V.opcode == Instruction::VFCmp)
1857 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1858 V.operands[0], V.operands[1]);
1859 assert(0 && "Invalid ConstantExpr!");
1865 struct ConvertConstantType<ConstantExpr, Type> {
1866 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1868 switch (OldC->getOpcode()) {
1869 case Instruction::Trunc:
1870 case Instruction::ZExt:
1871 case Instruction::SExt:
1872 case Instruction::FPTrunc:
1873 case Instruction::FPExt:
1874 case Instruction::UIToFP:
1875 case Instruction::SIToFP:
1876 case Instruction::FPToUI:
1877 case Instruction::FPToSI:
1878 case Instruction::PtrToInt:
1879 case Instruction::IntToPtr:
1880 case Instruction::BitCast:
1881 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1884 case Instruction::Select:
1885 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1886 OldC->getOperand(1),
1887 OldC->getOperand(2));
1890 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1891 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1892 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1893 OldC->getOperand(1));
1895 case Instruction::GetElementPtr:
1896 // Make everyone now use a constant of the new type...
1897 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1898 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1899 &Idx[0], Idx.size());
1903 assert(New != OldC && "Didn't replace constant??");
1904 OldC->uncheckedReplaceAllUsesWith(New);
1905 OldC->destroyConstant(); // This constant is now dead, destroy it.
1908 } // end namespace llvm
1911 static ExprMapKeyType getValType(ConstantExpr *CE) {
1912 std::vector<Constant*> Operands;
1913 Operands.reserve(CE->getNumOperands());
1914 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1915 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1916 return ExprMapKeyType(CE->getOpcode(), Operands,
1917 CE->isCompare() ? CE->getPredicate() : 0,
1919 CE->getIndices() : SmallVector<unsigned, 4>());
1922 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1923 ConstantExpr> > ExprConstants;
1925 /// This is a utility function to handle folding of casts and lookup of the
1926 /// cast in the ExprConstants map. It is used by the various get* methods below.
1927 static inline Constant *getFoldedCast(
1928 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1929 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1930 // Fold a few common cases
1931 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1934 // Look up the constant in the table first to ensure uniqueness
1935 std::vector<Constant*> argVec(1, C);
1936 ExprMapKeyType Key(opc, argVec);
1937 return ExprConstants->getOrCreate(Ty, Key);
1940 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1941 Instruction::CastOps opc = Instruction::CastOps(oc);
1942 assert(Instruction::isCast(opc) && "opcode out of range");
1943 assert(C && Ty && "Null arguments to getCast");
1944 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1948 assert(0 && "Invalid cast opcode");
1950 case Instruction::Trunc: return getTrunc(C, Ty);
1951 case Instruction::ZExt: return getZExt(C, Ty);
1952 case Instruction::SExt: return getSExt(C, Ty);
1953 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1954 case Instruction::FPExt: return getFPExtend(C, Ty);
1955 case Instruction::UIToFP: return getUIToFP(C, Ty);
1956 case Instruction::SIToFP: return getSIToFP(C, Ty);
1957 case Instruction::FPToUI: return getFPToUI(C, Ty);
1958 case Instruction::FPToSI: return getFPToSI(C, Ty);
1959 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1960 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1961 case Instruction::BitCast: return getBitCast(C, Ty);
1966 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1967 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1968 return getCast(Instruction::BitCast, C, Ty);
1969 return getCast(Instruction::ZExt, C, Ty);
1972 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1973 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1974 return getCast(Instruction::BitCast, C, Ty);
1975 return getCast(Instruction::SExt, C, Ty);
1978 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1979 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1980 return getCast(Instruction::BitCast, C, Ty);
1981 return getCast(Instruction::Trunc, C, Ty);
1984 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1985 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1986 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1988 if (Ty->isInteger())
1989 return getCast(Instruction::PtrToInt, S, Ty);
1990 return getCast(Instruction::BitCast, S, Ty);
1993 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1995 assert(C->getType()->isIntOrIntVector() &&
1996 Ty->isIntOrIntVector() && "Invalid cast");
1997 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1998 unsigned DstBits = Ty->getScalarSizeInBits();
1999 Instruction::CastOps opcode =
2000 (SrcBits == DstBits ? Instruction::BitCast :
2001 (SrcBits > DstBits ? Instruction::Trunc :
2002 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2003 return getCast(opcode, C, Ty);
2006 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
2007 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2009 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2010 unsigned DstBits = Ty->getScalarSizeInBits();
2011 if (SrcBits == DstBits)
2012 return C; // Avoid a useless cast
2013 Instruction::CastOps opcode =
2014 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
2015 return getCast(opcode, C, Ty);
2018 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
2020 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2021 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2023 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2024 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2025 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2026 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2027 "SrcTy must be larger than DestTy for Trunc!");
2029 return getFoldedCast(Instruction::Trunc, C, Ty);
2032 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
2034 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2035 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2037 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2038 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2039 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2040 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2041 "SrcTy must be smaller than DestTy for SExt!");
2043 return getFoldedCast(Instruction::SExt, C, Ty);
2046 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
2048 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2049 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2051 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2052 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2053 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2054 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2055 "SrcTy must be smaller than DestTy for ZExt!");
2057 return getFoldedCast(Instruction::ZExt, C, Ty);
2060 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
2062 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2063 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2065 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2066 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2067 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2068 "This is an illegal floating point truncation!");
2069 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2072 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2074 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2075 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2077 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2078 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2079 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2080 "This is an illegal floating point extension!");
2081 return getFoldedCast(Instruction::FPExt, C, Ty);
2084 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2086 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2087 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2089 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2090 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2091 "This is an illegal uint to floating point cast!");
2092 return getFoldedCast(Instruction::UIToFP, C, Ty);
2095 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2097 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2098 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2100 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2101 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2102 "This is an illegal sint to floating point cast!");
2103 return getFoldedCast(Instruction::SIToFP, C, Ty);
2106 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2108 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2109 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2111 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2112 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2113 "This is an illegal floating point to uint cast!");
2114 return getFoldedCast(Instruction::FPToUI, C, Ty);
2117 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2119 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2120 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2122 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2123 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2124 "This is an illegal floating point to sint cast!");
2125 return getFoldedCast(Instruction::FPToSI, C, Ty);
2128 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2129 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2130 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2131 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2134 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2135 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2136 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2137 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2140 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2141 // BitCast implies a no-op cast of type only. No bits change. However, you
2142 // can't cast pointers to anything but pointers.
2144 const Type *SrcTy = C->getType();
2145 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2146 "BitCast cannot cast pointer to non-pointer and vice versa");
2148 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2149 // or nonptr->ptr). For all the other types, the cast is okay if source and
2150 // destination bit widths are identical.
2151 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2152 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2154 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2156 // It is common to ask for a bitcast of a value to its own type, handle this
2158 if (C->getType() == DstTy) return C;
2160 return getFoldedCast(Instruction::BitCast, C, DstTy);
2163 Constant *ConstantExpr::getAlignOf(const Type *Ty) {
2164 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
2165 const Type *AligningTy = StructType::get(Type::Int8Ty, Ty, NULL);
2166 Constant *NullPtr = getNullValue(AligningTy->getPointerTo());
2167 Constant *Zero = ConstantInt::get(Type::Int32Ty, 0);
2168 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
2169 Constant *Indices[2] = { Zero, One };
2170 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
2171 return getCast(Instruction::PtrToInt, GEP, Type::Int32Ty);
2174 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
2175 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2176 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2178 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2179 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2182 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2183 Constant *C1, Constant *C2) {
2184 // Check the operands for consistency first
2185 assert(Opcode >= Instruction::BinaryOpsBegin &&
2186 Opcode < Instruction::BinaryOpsEnd &&
2187 "Invalid opcode in binary constant expression");
2188 assert(C1->getType() == C2->getType() &&
2189 "Operand types in binary constant expression should match");
2191 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2192 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2193 return FC; // Fold a few common cases...
2195 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2196 ExprMapKeyType Key(Opcode, argVec);
2197 return ExprConstants->getOrCreate(ReqTy, Key);
2200 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2201 Constant *C1, Constant *C2) {
2202 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
2203 switch (predicate) {
2204 default: assert(0 && "Invalid CmpInst predicate");
2205 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2206 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2207 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2208 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2209 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2210 case CmpInst::FCMP_TRUE:
2211 return isVectorType ? getVFCmp(predicate, C1, C2)
2212 : getFCmp(predicate, C1, C2);
2213 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2214 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2215 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2216 case CmpInst::ICMP_SLE:
2217 return isVectorType ? getVICmp(predicate, C1, C2)
2218 : getICmp(predicate, C1, C2);
2222 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2223 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2224 if (C1->getType()->isFPOrFPVector()) {
2225 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2226 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2227 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2231 case Instruction::Add:
2232 case Instruction::Sub:
2233 case Instruction::Mul:
2234 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2235 assert(C1->getType()->isIntOrIntVector() &&
2236 "Tried to create an integer operation on a non-integer type!");
2238 case Instruction::FAdd:
2239 case Instruction::FSub:
2240 case Instruction::FMul:
2241 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2242 assert(C1->getType()->isFPOrFPVector() &&
2243 "Tried to create a floating-point operation on a "
2244 "non-floating-point type!");
2246 case Instruction::UDiv:
2247 case Instruction::SDiv:
2248 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2249 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2250 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2251 "Tried to create an arithmetic operation on a non-arithmetic type!");
2253 case Instruction::FDiv:
2254 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2255 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2256 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2257 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2259 case Instruction::URem:
2260 case Instruction::SRem:
2261 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2262 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2263 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2264 "Tried to create an arithmetic operation on a non-arithmetic type!");
2266 case Instruction::FRem:
2267 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2268 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2269 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2270 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2272 case Instruction::And:
2273 case Instruction::Or:
2274 case Instruction::Xor:
2275 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2276 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
2277 "Tried to create a logical operation on a non-integral type!");
2279 case Instruction::Shl:
2280 case Instruction::LShr:
2281 case Instruction::AShr:
2282 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2283 assert(C1->getType()->isIntOrIntVector() &&
2284 "Tried to create a shift operation on a non-integer type!");
2291 return getTy(C1->getType(), Opcode, C1, C2);
2294 Constant *ConstantExpr::getCompare(unsigned short pred,
2295 Constant *C1, Constant *C2) {
2296 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2297 return getCompareTy(pred, C1, C2);
2300 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2301 Constant *V1, Constant *V2) {
2302 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2304 if (ReqTy == V1->getType())
2305 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2306 return SC; // Fold common cases
2308 std::vector<Constant*> argVec(3, C);
2311 ExprMapKeyType Key(Instruction::Select, argVec);
2312 return ExprConstants->getOrCreate(ReqTy, Key);
2315 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2318 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2320 cast<PointerType>(ReqTy)->getElementType() &&
2321 "GEP indices invalid!");
2323 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2324 return FC; // Fold a few common cases...
2326 assert(isa<PointerType>(C->getType()) &&
2327 "Non-pointer type for constant GetElementPtr expression");
2328 // Look up the constant in the table first to ensure uniqueness
2329 std::vector<Constant*> ArgVec;
2330 ArgVec.reserve(NumIdx+1);
2331 ArgVec.push_back(C);
2332 for (unsigned i = 0; i != NumIdx; ++i)
2333 ArgVec.push_back(cast<Constant>(Idxs[i]));
2334 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2335 return ExprConstants->getOrCreate(ReqTy, Key);
2338 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2340 // Get the result type of the getelementptr!
2342 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2343 assert(Ty && "GEP indices invalid!");
2344 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2345 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2348 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2350 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2355 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2356 assert(LHS->getType() == RHS->getType());
2357 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2358 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2360 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2361 return FC; // Fold a few common cases...
2363 // Look up the constant in the table first to ensure uniqueness
2364 std::vector<Constant*> ArgVec;
2365 ArgVec.push_back(LHS);
2366 ArgVec.push_back(RHS);
2367 // Get the key type with both the opcode and predicate
2368 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2369 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2373 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2374 assert(LHS->getType() == RHS->getType());
2375 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2377 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2378 return FC; // Fold a few common cases...
2380 // Look up the constant in the table first to ensure uniqueness
2381 std::vector<Constant*> ArgVec;
2382 ArgVec.push_back(LHS);
2383 ArgVec.push_back(RHS);
2384 // Get the key type with both the opcode and predicate
2385 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2386 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2390 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2391 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
2392 "Tried to create vicmp operation on non-vector type!");
2393 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2394 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2396 const VectorType *VTy = cast<VectorType>(LHS->getType());
2397 const Type *EltTy = VTy->getElementType();
2398 unsigned NumElts = VTy->getNumElements();
2400 // See if we can fold the element-wise comparison of the LHS and RHS.
2401 SmallVector<Constant *, 16> LHSElts, RHSElts;
2402 LHS->getVectorElements(LHSElts);
2403 RHS->getVectorElements(RHSElts);
2405 if (!LHSElts.empty() && !RHSElts.empty()) {
2406 SmallVector<Constant *, 16> Elts;
2407 for (unsigned i = 0; i != NumElts; ++i) {
2408 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2410 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2411 if (FCI->getZExtValue())
2412 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2414 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2415 } else if (FC && isa<UndefValue>(FC)) {
2416 Elts.push_back(UndefValue::get(EltTy));
2421 if (Elts.size() == NumElts)
2422 return ConstantVector::get(&Elts[0], Elts.size());
2425 // Look up the constant in the table first to ensure uniqueness
2426 std::vector<Constant*> ArgVec;
2427 ArgVec.push_back(LHS);
2428 ArgVec.push_back(RHS);
2429 // Get the key type with both the opcode and predicate
2430 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2431 return ExprConstants->getOrCreate(LHS->getType(), Key);
2435 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2436 assert(isa<VectorType>(LHS->getType()) &&
2437 "Tried to create vfcmp operation on non-vector type!");
2438 assert(LHS->getType() == RHS->getType());
2439 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2441 const VectorType *VTy = cast<VectorType>(LHS->getType());
2442 unsigned NumElts = VTy->getNumElements();
2443 const Type *EltTy = VTy->getElementType();
2444 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2445 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2447 // See if we can fold the element-wise comparison of the LHS and RHS.
2448 SmallVector<Constant *, 16> LHSElts, RHSElts;
2449 LHS->getVectorElements(LHSElts);
2450 RHS->getVectorElements(RHSElts);
2452 if (!LHSElts.empty() && !RHSElts.empty()) {
2453 SmallVector<Constant *, 16> Elts;
2454 for (unsigned i = 0; i != NumElts; ++i) {
2455 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2457 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2458 if (FCI->getZExtValue())
2459 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2461 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2462 } else if (FC && isa<UndefValue>(FC)) {
2463 Elts.push_back(UndefValue::get(REltTy));
2468 if (Elts.size() == NumElts)
2469 return ConstantVector::get(&Elts[0], Elts.size());
2472 // Look up the constant in the table first to ensure uniqueness
2473 std::vector<Constant*> ArgVec;
2474 ArgVec.push_back(LHS);
2475 ArgVec.push_back(RHS);
2476 // Get the key type with both the opcode and predicate
2477 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2478 return ExprConstants->getOrCreate(ResultTy, Key);
2481 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2483 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2484 return FC; // Fold a few common cases...
2485 // Look up the constant in the table first to ensure uniqueness
2486 std::vector<Constant*> ArgVec(1, Val);
2487 ArgVec.push_back(Idx);
2488 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2489 return ExprConstants->getOrCreate(ReqTy, Key);
2492 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2493 assert(isa<VectorType>(Val->getType()) &&
2494 "Tried to create extractelement operation on non-vector type!");
2495 assert(Idx->getType() == Type::Int32Ty &&
2496 "Extractelement index must be i32 type!");
2497 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2501 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2502 Constant *Elt, Constant *Idx) {
2503 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2504 return FC; // Fold a few common cases...
2505 // Look up the constant in the table first to ensure uniqueness
2506 std::vector<Constant*> ArgVec(1, Val);
2507 ArgVec.push_back(Elt);
2508 ArgVec.push_back(Idx);
2509 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2510 return ExprConstants->getOrCreate(ReqTy, Key);
2513 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2515 assert(isa<VectorType>(Val->getType()) &&
2516 "Tried to create insertelement operation on non-vector type!");
2517 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2518 && "Insertelement types must match!");
2519 assert(Idx->getType() == Type::Int32Ty &&
2520 "Insertelement index must be i32 type!");
2521 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2524 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2525 Constant *V2, Constant *Mask) {
2526 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2527 return FC; // Fold a few common cases...
2528 // Look up the constant in the table first to ensure uniqueness
2529 std::vector<Constant*> ArgVec(1, V1);
2530 ArgVec.push_back(V2);
2531 ArgVec.push_back(Mask);
2532 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2533 return ExprConstants->getOrCreate(ReqTy, Key);
2536 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2538 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2539 "Invalid shuffle vector constant expr operands!");
2541 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2542 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2543 const Type *ShufTy = VectorType::get(EltTy, NElts);
2544 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2547 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2549 const unsigned *Idxs, unsigned NumIdx) {
2550 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2551 Idxs+NumIdx) == Val->getType() &&
2552 "insertvalue indices invalid!");
2553 assert(Agg->getType() == ReqTy &&
2554 "insertvalue type invalid!");
2555 assert(Agg->getType()->isFirstClassType() &&
2556 "Non-first-class type for constant InsertValue expression");
2557 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2558 assert(FC && "InsertValue constant expr couldn't be folded!");
2562 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2563 const unsigned *IdxList, unsigned NumIdx) {
2564 assert(Agg->getType()->isFirstClassType() &&
2565 "Tried to create insertelement operation on non-first-class type!");
2567 const Type *ReqTy = Agg->getType();
2570 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2572 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2573 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2576 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2577 const unsigned *Idxs, unsigned NumIdx) {
2578 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2579 Idxs+NumIdx) == ReqTy &&
2580 "extractvalue indices invalid!");
2581 assert(Agg->getType()->isFirstClassType() &&
2582 "Non-first-class type for constant extractvalue expression");
2583 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2584 assert(FC && "ExtractValue constant expr couldn't be folded!");
2588 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2589 const unsigned *IdxList, unsigned NumIdx) {
2590 assert(Agg->getType()->isFirstClassType() &&
2591 "Tried to create extractelement operation on non-first-class type!");
2594 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2595 assert(ReqTy && "extractvalue indices invalid!");
2596 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2599 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2600 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2601 if (PTy->getElementType()->isFloatingPoint()) {
2602 std::vector<Constant*> zeros(PTy->getNumElements(),
2603 ConstantFP::getNegativeZero(PTy->getElementType()));
2604 return ConstantVector::get(PTy, zeros);
2607 if (Ty->isFloatingPoint())
2608 return ConstantFP::getNegativeZero(Ty);
2610 return Constant::getNullValue(Ty);
2613 // destroyConstant - Remove the constant from the constant table...
2615 void ConstantExpr::destroyConstant() {
2616 ExprConstants->remove(this);
2617 destroyConstantImpl();
2620 const char *ConstantExpr::getOpcodeName() const {
2621 return Instruction::getOpcodeName(getOpcode());
2624 //===----------------------------------------------------------------------===//
2625 // replaceUsesOfWithOnConstant implementations
2627 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2628 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2631 /// Note that we intentionally replace all uses of From with To here. Consider
2632 /// a large array that uses 'From' 1000 times. By handling this case all here,
2633 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2634 /// single invocation handles all 1000 uses. Handling them one at a time would
2635 /// work, but would be really slow because it would have to unique each updated
2637 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2639 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2640 Constant *ToC = cast<Constant>(To);
2642 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2643 Lookup.first.first = getType();
2644 Lookup.second = this;
2646 std::vector<Constant*> &Values = Lookup.first.second;
2647 Values.reserve(getNumOperands()); // Build replacement array.
2649 // Fill values with the modified operands of the constant array. Also,
2650 // compute whether this turns into an all-zeros array.
2651 bool isAllZeros = false;
2652 unsigned NumUpdated = 0;
2653 if (!ToC->isNullValue()) {
2654 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2655 Constant *Val = cast<Constant>(O->get());
2660 Values.push_back(Val);
2664 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2665 Constant *Val = cast<Constant>(O->get());
2670 Values.push_back(Val);
2671 if (isAllZeros) isAllZeros = Val->isNullValue();
2675 Constant *Replacement = 0;
2677 Replacement = ConstantAggregateZero::get(getType());
2679 // Check to see if we have this array type already.
2681 ArrayConstantsTy::MapTy::iterator I =
2682 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2685 Replacement = I->second;
2687 // Okay, the new shape doesn't exist in the system yet. Instead of
2688 // creating a new constant array, inserting it, replaceallusesof'ing the
2689 // old with the new, then deleting the old... just update the current one
2691 ArrayConstants->MoveConstantToNewSlot(this, I);
2693 // Update to the new value. Optimize for the case when we have a single
2694 // operand that we're changing, but handle bulk updates efficiently.
2695 if (NumUpdated == 1) {
2696 unsigned OperandToUpdate = U-OperandList;
2697 assert(getOperand(OperandToUpdate) == From &&
2698 "ReplaceAllUsesWith broken!");
2699 setOperand(OperandToUpdate, ToC);
2701 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2702 if (getOperand(i) == From)
2709 // Otherwise, I do need to replace this with an existing value.
2710 assert(Replacement != this && "I didn't contain From!");
2712 // Everyone using this now uses the replacement.
2713 uncheckedReplaceAllUsesWith(Replacement);
2715 // Delete the old constant!
2719 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2721 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2722 Constant *ToC = cast<Constant>(To);
2724 unsigned OperandToUpdate = U-OperandList;
2725 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2727 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2728 Lookup.first.first = getType();
2729 Lookup.second = this;
2730 std::vector<Constant*> &Values = Lookup.first.second;
2731 Values.reserve(getNumOperands()); // Build replacement struct.
2734 // Fill values with the modified operands of the constant struct. Also,
2735 // compute whether this turns into an all-zeros struct.
2736 bool isAllZeros = false;
2737 if (!ToC->isNullValue()) {
2738 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2739 Values.push_back(cast<Constant>(O->get()));
2742 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2743 Constant *Val = cast<Constant>(O->get());
2744 Values.push_back(Val);
2745 if (isAllZeros) isAllZeros = Val->isNullValue();
2748 Values[OperandToUpdate] = ToC;
2750 Constant *Replacement = 0;
2752 Replacement = ConstantAggregateZero::get(getType());
2754 // Check to see if we have this array type already.
2756 StructConstantsTy::MapTy::iterator I =
2757 StructConstants->InsertOrGetItem(Lookup, Exists);
2760 Replacement = I->second;
2762 // Okay, the new shape doesn't exist in the system yet. Instead of
2763 // creating a new constant struct, inserting it, replaceallusesof'ing the
2764 // old with the new, then deleting the old... just update the current one
2766 StructConstants->MoveConstantToNewSlot(this, I);
2768 // Update to the new value.
2769 setOperand(OperandToUpdate, ToC);
2774 assert(Replacement != this && "I didn't contain From!");
2776 // Everyone using this now uses the replacement.
2777 uncheckedReplaceAllUsesWith(Replacement);
2779 // Delete the old constant!
2783 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2785 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2787 std::vector<Constant*> Values;
2788 Values.reserve(getNumOperands()); // Build replacement array...
2789 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2790 Constant *Val = getOperand(i);
2791 if (Val == From) Val = cast<Constant>(To);
2792 Values.push_back(Val);
2795 Constant *Replacement = ConstantVector::get(getType(), Values);
2796 assert(Replacement != this && "I didn't contain From!");
2798 // Everyone using this now uses the replacement.
2799 uncheckedReplaceAllUsesWith(Replacement);
2801 // Delete the old constant!
2805 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2807 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2808 Constant *To = cast<Constant>(ToV);
2810 Constant *Replacement = 0;
2811 if (getOpcode() == Instruction::GetElementPtr) {
2812 SmallVector<Constant*, 8> Indices;
2813 Constant *Pointer = getOperand(0);
2814 Indices.reserve(getNumOperands()-1);
2815 if (Pointer == From) Pointer = To;
2817 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2818 Constant *Val = getOperand(i);
2819 if (Val == From) Val = To;
2820 Indices.push_back(Val);
2822 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2823 &Indices[0], Indices.size());
2824 } else if (getOpcode() == Instruction::ExtractValue) {
2825 Constant *Agg = getOperand(0);
2826 if (Agg == From) Agg = To;
2828 const SmallVector<unsigned, 4> &Indices = getIndices();
2829 Replacement = ConstantExpr::getExtractValue(Agg,
2830 &Indices[0], Indices.size());
2831 } else if (getOpcode() == Instruction::InsertValue) {
2832 Constant *Agg = getOperand(0);
2833 Constant *Val = getOperand(1);
2834 if (Agg == From) Agg = To;
2835 if (Val == From) Val = To;
2837 const SmallVector<unsigned, 4> &Indices = getIndices();
2838 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2839 &Indices[0], Indices.size());
2840 } else if (isCast()) {
2841 assert(getOperand(0) == From && "Cast only has one use!");
2842 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2843 } else if (getOpcode() == Instruction::Select) {
2844 Constant *C1 = getOperand(0);
2845 Constant *C2 = getOperand(1);
2846 Constant *C3 = getOperand(2);
2847 if (C1 == From) C1 = To;
2848 if (C2 == From) C2 = To;
2849 if (C3 == From) C3 = To;
2850 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2851 } else if (getOpcode() == Instruction::ExtractElement) {
2852 Constant *C1 = getOperand(0);
2853 Constant *C2 = getOperand(1);
2854 if (C1 == From) C1 = To;
2855 if (C2 == From) C2 = To;
2856 Replacement = ConstantExpr::getExtractElement(C1, C2);
2857 } else if (getOpcode() == Instruction::InsertElement) {
2858 Constant *C1 = getOperand(0);
2859 Constant *C2 = getOperand(1);
2860 Constant *C3 = getOperand(1);
2861 if (C1 == From) C1 = To;
2862 if (C2 == From) C2 = To;
2863 if (C3 == From) C3 = To;
2864 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2865 } else if (getOpcode() == Instruction::ShuffleVector) {
2866 Constant *C1 = getOperand(0);
2867 Constant *C2 = getOperand(1);
2868 Constant *C3 = getOperand(2);
2869 if (C1 == From) C1 = To;
2870 if (C2 == From) C2 = To;
2871 if (C3 == From) C3 = To;
2872 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2873 } else if (isCompare()) {
2874 Constant *C1 = getOperand(0);
2875 Constant *C2 = getOperand(1);
2876 if (C1 == From) C1 = To;
2877 if (C2 == From) C2 = To;
2878 if (getOpcode() == Instruction::ICmp)
2879 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2880 else if (getOpcode() == Instruction::FCmp)
2881 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2882 else if (getOpcode() == Instruction::VICmp)
2883 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2885 assert(getOpcode() == Instruction::VFCmp);
2886 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
2888 } else if (getNumOperands() == 2) {
2889 Constant *C1 = getOperand(0);
2890 Constant *C2 = getOperand(1);
2891 if (C1 == From) C1 = To;
2892 if (C2 == From) C2 = To;
2893 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2895 assert(0 && "Unknown ConstantExpr type!");
2899 assert(Replacement != this && "I didn't contain From!");
2901 // Everyone using this now uses the replacement.
2902 uncheckedReplaceAllUsesWith(Replacement);
2904 // Delete the old constant!
2908 void MDNode::replaceElement(Value *From, Value *To) {
2909 SmallVector<Value*, 4> Values;
2910 Values.reserve(getNumElements()); // Build replacement array...
2911 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2912 Value *Val = getElement(i);
2913 if (Val == From) Val = To;
2914 Values.push_back(Val);
2917 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2918 assert(Replacement != this && "I didn't contain From!");
2920 uncheckedReplaceAllUsesWith(Replacement);