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/Module.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/SmallVector.h"
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 void Constant::destroyConstantImpl() {
36 // When a Constant is destroyed, there may be lingering
37 // references to the constant by other constants in the constant pool. These
38 // constants are implicitly dependent on the module that is being deleted,
39 // but they don't know that. Because we only find out when the CPV is
40 // deleted, we must now notify all of our users (that should only be
41 // Constants) that they are, in fact, invalid now and should be deleted.
43 while (!use_empty()) {
44 Value *V = use_back();
45 #ifndef NDEBUG // Only in -g mode...
46 if (!isa<Constant>(V))
47 DOUT << "While deleting: " << *this
48 << "\n\nUse still stuck around after Def is destroyed: "
51 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
52 Constant *CV = cast<Constant>(V);
53 CV->destroyConstant();
55 // The constant should remove itself from our use list...
56 assert((use_empty() || use_back() != V) && "Constant not removed!");
59 // Value has no outstanding references it is safe to delete it now...
63 /// canTrap - Return true if evaluation of this constant could trap. This is
64 /// true for things like constant expressions that could divide by zero.
65 bool Constant::canTrap() const {
66 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
67 // The only thing that could possibly trap are constant exprs.
68 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
69 if (!CE) return false;
71 // ConstantExpr traps if any operands can trap.
72 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
73 if (getOperand(i)->canTrap())
76 // Otherwise, only specific operations can trap.
77 switch (CE->getOpcode()) {
80 case Instruction::UDiv:
81 case Instruction::SDiv:
82 case Instruction::FDiv:
83 case Instruction::URem:
84 case Instruction::SRem:
85 case Instruction::FRem:
86 // Div and rem can trap if the RHS is not known to be non-zero.
87 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
93 /// ContaintsRelocations - Return true if the constant value contains
94 /// relocations which cannot be resolved at compile time.
95 bool Constant::ContainsRelocations() const {
96 if (isa<GlobalValue>(this))
98 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
99 if (getOperand(i)->ContainsRelocations())
104 // Static constructor to create a '0' constant of arbitrary type...
105 Constant *Constant::getNullValue(const Type *Ty) {
106 static uint64_t zero[2] = {0, 0};
107 switch (Ty->getTypeID()) {
108 case Type::IntegerTyID:
109 return ConstantInt::get(Ty, 0);
110 case Type::FloatTyID:
111 return ConstantFP::get(APFloat(APInt(32, 0)));
112 case Type::DoubleTyID:
113 return ConstantFP::get(APFloat(APInt(64, 0)));
114 case Type::X86_FP80TyID:
115 return ConstantFP::get(APFloat(APInt(80, 2, zero)));
116 case Type::FP128TyID:
117 return ConstantFP::get(APFloat(APInt(128, 2, zero), true));
118 case Type::PPC_FP128TyID:
119 return ConstantFP::get(APFloat(APInt(128, 2, zero)));
120 case Type::PointerTyID:
121 return ConstantPointerNull::get(cast<PointerType>(Ty));
122 case Type::StructTyID:
123 case Type::ArrayTyID:
124 case Type::VectorTyID:
125 return ConstantAggregateZero::get(Ty);
127 // Function, Label, or Opaque type?
128 assert(!"Cannot create a null constant of that type!");
133 Constant *Constant::getAllOnesValue(const Type *Ty) {
134 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
135 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
136 return ConstantVector::getAllOnesValue(cast<VectorType>(Ty));
139 // Static constructor to create an integral constant with all bits set
140 ConstantInt *ConstantInt::getAllOnesValue(const Type *Ty) {
141 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
142 return ConstantInt::get(APInt::getAllOnesValue(ITy->getBitWidth()));
146 /// @returns the value for a vector integer constant of the given type that
147 /// has all its bits set to true.
148 /// @brief Get the all ones value
149 ConstantVector *ConstantVector::getAllOnesValue(const VectorType *Ty) {
150 std::vector<Constant*> Elts;
151 Elts.resize(Ty->getNumElements(),
152 ConstantInt::getAllOnesValue(Ty->getElementType()));
153 assert(Elts[0] && "Not a vector integer type!");
154 return cast<ConstantVector>(ConstantVector::get(Elts));
158 /// getVectorElements - This method, which is only valid on constant of vector
159 /// type, returns the elements of the vector in the specified smallvector.
160 /// This handles breaking down a vector undef into undef elements, etc. For
161 /// constant exprs and other cases we can't handle, we return an empty vector.
162 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
163 assert(isa<VectorType>(getType()) && "Not a vector constant!");
165 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
166 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
167 Elts.push_back(CV->getOperand(i));
171 const VectorType *VT = cast<VectorType>(getType());
172 if (isa<ConstantAggregateZero>(this)) {
173 Elts.assign(VT->getNumElements(),
174 Constant::getNullValue(VT->getElementType()));
178 if (isa<UndefValue>(this)) {
179 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
183 // Unknown type, must be constant expr etc.
188 //===----------------------------------------------------------------------===//
190 //===----------------------------------------------------------------------===//
192 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
193 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
194 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
197 ConstantInt *ConstantInt::TheTrueVal = 0;
198 ConstantInt *ConstantInt::TheFalseVal = 0;
201 void CleanupTrueFalse(void *) {
202 ConstantInt::ResetTrueFalse();
206 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
208 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
209 assert(TheTrueVal == 0 && TheFalseVal == 0);
210 TheTrueVal = get(Type::Int1Ty, 1);
211 TheFalseVal = get(Type::Int1Ty, 0);
213 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
214 TrueFalseCleanup.Register();
216 return WhichOne ? TheTrueVal : TheFalseVal;
221 struct DenseMapAPIntKeyInfo {
225 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
226 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
227 bool operator==(const KeyTy& that) const {
228 return type == that.type && this->val == that.val;
230 bool operator!=(const KeyTy& that) const {
231 return !this->operator==(that);
234 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
235 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
236 static unsigned getHashValue(const KeyTy &Key) {
237 return DenseMapInfo<void*>::getHashValue(Key.type) ^
238 Key.val.getHashValue();
240 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
243 static bool isPod() { return false; }
248 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
249 DenseMapAPIntKeyInfo> IntMapTy;
250 static ManagedStatic<IntMapTy> IntConstants;
252 ConstantInt *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
253 const IntegerType *ITy = cast<IntegerType>(Ty);
254 return get(APInt(ITy->getBitWidth(), V, isSigned));
257 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
258 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
259 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
260 // compare APInt's of different widths, which would violate an APInt class
261 // invariant which generates an assertion.
262 ConstantInt *ConstantInt::get(const APInt& V) {
263 // Get the corresponding integer type for the bit width of the value.
264 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
265 // get an existing value or the insertion position
266 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
267 ConstantInt *&Slot = (*IntConstants)[Key];
268 // if it exists, return it.
271 // otherwise create a new one, insert it, and return it.
272 return Slot = new ConstantInt(ITy, V);
275 //===----------------------------------------------------------------------===//
277 //===----------------------------------------------------------------------===//
279 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
280 if (Ty == Type::FloatTy)
281 return &APFloat::IEEEsingle;
282 if (Ty == Type::DoubleTy)
283 return &APFloat::IEEEdouble;
284 if (Ty == Type::X86_FP80Ty)
285 return &APFloat::x87DoubleExtended;
286 else if (Ty == Type::FP128Ty)
287 return &APFloat::IEEEquad;
289 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
290 return &APFloat::PPCDoubleDouble;
293 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
294 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
295 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
299 bool ConstantFP::isNullValue() const {
300 return Val.isZero() && !Val.isNegative();
303 ConstantFP *ConstantFP::getNegativeZero(const Type *Ty) {
304 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
306 return ConstantFP::get(apf);
309 bool ConstantFP::isExactlyValue(const APFloat& V) const {
310 return Val.bitwiseIsEqual(V);
314 struct DenseMapAPFloatKeyInfo {
317 KeyTy(const APFloat& V) : val(V){}
318 KeyTy(const KeyTy& that) : val(that.val) {}
319 bool operator==(const KeyTy& that) const {
320 return this->val.bitwiseIsEqual(that.val);
322 bool operator!=(const KeyTy& that) const {
323 return !this->operator==(that);
326 static inline KeyTy getEmptyKey() {
327 return KeyTy(APFloat(APFloat::Bogus,1));
329 static inline KeyTy getTombstoneKey() {
330 return KeyTy(APFloat(APFloat::Bogus,2));
332 static unsigned getHashValue(const KeyTy &Key) {
333 return Key.val.getHashValue();
335 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
338 static bool isPod() { return false; }
342 //---- ConstantFP::get() implementation...
344 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
345 DenseMapAPFloatKeyInfo> FPMapTy;
347 static ManagedStatic<FPMapTy> FPConstants;
349 ConstantFP *ConstantFP::get(const APFloat &V) {
350 DenseMapAPFloatKeyInfo::KeyTy Key(V);
351 ConstantFP *&Slot = (*FPConstants)[Key];
352 if (Slot) return Slot;
355 if (&V.getSemantics() == &APFloat::IEEEsingle)
357 else if (&V.getSemantics() == &APFloat::IEEEdouble)
359 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
360 Ty = Type::X86_FP80Ty;
361 else if (&V.getSemantics() == &APFloat::IEEEquad)
364 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble&&"Unknown FP format");
365 Ty = Type::PPC_FP128Ty;
368 return Slot = new ConstantFP(Ty, V);
371 /// get() - This returns a constant fp for the specified value in the
372 /// specified type. This should only be used for simple constant values like
373 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
374 ConstantFP *ConstantFP::get(const Type *Ty, double V) {
376 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven);
380 //===----------------------------------------------------------------------===//
381 // ConstantXXX Classes
382 //===----------------------------------------------------------------------===//
385 ConstantArray::ConstantArray(const ArrayType *T,
386 const std::vector<Constant*> &V)
387 : Constant(T, ConstantArrayVal,
388 OperandTraits<ConstantArray>::op_end(this) - V.size(),
390 assert(V.size() == T->getNumElements() &&
391 "Invalid initializer vector for constant array");
392 Use *OL = OperandList;
393 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
396 assert((C->getType() == T->getElementType() ||
398 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
399 "Initializer for array element doesn't match array element type!");
405 ConstantStruct::ConstantStruct(const StructType *T,
406 const std::vector<Constant*> &V)
407 : Constant(T, ConstantStructVal,
408 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
410 assert(V.size() == T->getNumElements() &&
411 "Invalid initializer vector for constant structure");
412 Use *OL = OperandList;
413 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
416 assert((C->getType() == T->getElementType(I-V.begin()) ||
417 ((T->getElementType(I-V.begin())->isAbstract() ||
418 C->getType()->isAbstract()) &&
419 T->getElementType(I-V.begin())->getTypeID() ==
420 C->getType()->getTypeID())) &&
421 "Initializer for struct element doesn't match struct element type!");
427 ConstantVector::ConstantVector(const VectorType *T,
428 const std::vector<Constant*> &V)
429 : Constant(T, ConstantVectorVal,
430 OperandTraits<ConstantVector>::op_end(this) - V.size(),
432 Use *OL = OperandList;
433 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
436 assert((C->getType() == T->getElementType() ||
438 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
439 "Initializer for vector element doesn't match vector element type!");
446 // We declare several classes private to this file, so use an anonymous
450 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
451 /// behind the scenes to implement unary constant exprs.
452 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
453 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
455 // allocate space for exactly one operand
456 void *operator new(size_t s) {
457 return User::operator new(s, 1);
459 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
460 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
463 /// Transparently provide more efficient getOperand methods.
464 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
467 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
468 /// behind the scenes to implement binary constant exprs.
469 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
470 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
472 // allocate space for exactly two operands
473 void *operator new(size_t s) {
474 return User::operator new(s, 2);
476 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
477 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
481 /// Transparently provide more efficient getOperand methods.
482 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
485 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
486 /// behind the scenes to implement select constant exprs.
487 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
488 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
490 // allocate space for exactly three operands
491 void *operator new(size_t s) {
492 return User::operator new(s, 3);
494 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
495 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
500 /// Transparently provide more efficient getOperand methods.
501 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
504 /// ExtractElementConstantExpr - This class is private to
505 /// Constants.cpp, and is used behind the scenes to implement
506 /// extractelement constant exprs.
507 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
508 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
510 // allocate space for exactly two operands
511 void *operator new(size_t s) {
512 return User::operator new(s, 2);
514 ExtractElementConstantExpr(Constant *C1, Constant *C2)
515 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
516 Instruction::ExtractElement, &Op<0>(), 2) {
520 /// Transparently provide more efficient getOperand methods.
521 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
524 /// InsertElementConstantExpr - This class is private to
525 /// Constants.cpp, and is used behind the scenes to implement
526 /// insertelement constant exprs.
527 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
528 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
530 // allocate space for exactly three operands
531 void *operator new(size_t s) {
532 return User::operator new(s, 3);
534 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
535 : ConstantExpr(C1->getType(), Instruction::InsertElement,
541 /// Transparently provide more efficient getOperand methods.
542 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
545 /// ShuffleVectorConstantExpr - This class is private to
546 /// Constants.cpp, and is used behind the scenes to implement
547 /// shufflevector constant exprs.
548 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
549 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
551 // allocate space for exactly three operands
552 void *operator new(size_t s) {
553 return User::operator new(s, 3);
555 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
556 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
562 /// Transparently provide more efficient getOperand methods.
563 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
566 /// ExtractValueConstantExpr - This class is private to
567 /// Constants.cpp, and is used behind the scenes to implement
568 /// extractvalue constant exprs.
569 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
570 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
572 // allocate space for exactly one operand
573 void *operator new(size_t s) {
574 return User::operator new(s, 1);
576 ExtractValueConstantExpr(Constant *Agg,
577 const SmallVector<unsigned, 4> &IdxList,
579 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
584 /// Indices - These identify which value to extract.
585 const SmallVector<unsigned, 4> Indices;
587 /// Transparently provide more efficient getOperand methods.
588 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
591 /// InsertValueConstantExpr - This class is private to
592 /// Constants.cpp, and is used behind the scenes to implement
593 /// insertvalue constant exprs.
594 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
595 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
597 // allocate space for exactly one operand
598 void *operator new(size_t s) {
599 return User::operator new(s, 2);
601 InsertValueConstantExpr(Constant *Agg, Constant *Val,
602 const SmallVector<unsigned, 4> &IdxList,
604 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
610 /// Indices - These identify the position for the insertion.
611 const SmallVector<unsigned, 4> Indices;
613 /// Transparently provide more efficient getOperand methods.
614 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
618 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
619 /// used behind the scenes to implement getelementpr constant exprs.
620 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
621 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
624 static GetElementPtrConstantExpr *Create(Constant *C,
625 const std::vector<Constant*>&IdxList,
626 const Type *DestTy) {
627 return new(IdxList.size() + 1)
628 GetElementPtrConstantExpr(C, IdxList, DestTy);
630 /// Transparently provide more efficient getOperand methods.
631 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
634 // CompareConstantExpr - This class is private to Constants.cpp, and is used
635 // behind the scenes to implement ICmp and FCmp constant expressions. This is
636 // needed in order to store the predicate value for these instructions.
637 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
638 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
639 // allocate space for exactly two operands
640 void *operator new(size_t s) {
641 return User::operator new(s, 2);
643 unsigned short predicate;
644 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
645 unsigned short pred, Constant* LHS, Constant* RHS)
646 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
650 /// Transparently provide more efficient getOperand methods.
651 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
654 } // end anonymous namespace
657 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
659 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
662 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
664 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
667 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
669 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
672 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
674 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
677 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
679 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
682 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
684 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
687 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
689 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
692 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
694 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
697 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
700 GetElementPtrConstantExpr::GetElementPtrConstantExpr
702 const std::vector<Constant*> &IdxList,
704 : ConstantExpr(DestTy, Instruction::GetElementPtr,
705 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
706 - (IdxList.size()+1),
709 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
710 OperandList[i+1] = IdxList[i];
713 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
717 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
719 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
722 } // End llvm namespace
725 // Utility function for determining if a ConstantExpr is a CastOp or not. This
726 // can't be inline because we don't want to #include Instruction.h into
728 bool ConstantExpr::isCast() const {
729 return Instruction::isCast(getOpcode());
732 bool ConstantExpr::isCompare() const {
733 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
734 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
737 bool ConstantExpr::hasIndices() const {
738 return getOpcode() == Instruction::ExtractValue ||
739 getOpcode() == Instruction::InsertValue;
742 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
743 if (const ExtractValueConstantExpr *EVCE =
744 dyn_cast<ExtractValueConstantExpr>(this))
745 return EVCE->Indices;
747 return cast<InsertValueConstantExpr>(this)->Indices;
750 /// ConstantExpr::get* - Return some common constants without having to
751 /// specify the full Instruction::OPCODE identifier.
753 Constant *ConstantExpr::getNeg(Constant *C) {
754 return get(Instruction::Sub,
755 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
758 Constant *ConstantExpr::getNot(Constant *C) {
759 assert((isa<IntegerType>(C->getType()) ||
760 cast<VectorType>(C->getType())->getElementType()->isInteger()) &&
761 "Cannot NOT a nonintegral value!");
762 return get(Instruction::Xor, C,
763 Constant::getAllOnesValue(C->getType()));
765 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
766 return get(Instruction::Add, C1, C2);
768 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
769 return get(Instruction::Sub, C1, C2);
771 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
772 return get(Instruction::Mul, C1, C2);
774 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
775 return get(Instruction::UDiv, C1, C2);
777 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
778 return get(Instruction::SDiv, C1, C2);
780 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
781 return get(Instruction::FDiv, C1, C2);
783 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
784 return get(Instruction::URem, C1, C2);
786 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
787 return get(Instruction::SRem, C1, C2);
789 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
790 return get(Instruction::FRem, C1, C2);
792 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
793 return get(Instruction::And, C1, C2);
795 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
796 return get(Instruction::Or, C1, C2);
798 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
799 return get(Instruction::Xor, C1, C2);
801 unsigned ConstantExpr::getPredicate() const {
802 assert(getOpcode() == Instruction::FCmp ||
803 getOpcode() == Instruction::ICmp ||
804 getOpcode() == Instruction::VFCmp ||
805 getOpcode() == Instruction::VICmp);
806 return ((const CompareConstantExpr*)this)->predicate;
808 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
809 return get(Instruction::Shl, C1, C2);
811 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
812 return get(Instruction::LShr, C1, C2);
814 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
815 return get(Instruction::AShr, C1, C2);
818 /// getWithOperandReplaced - Return a constant expression identical to this
819 /// one, but with the specified operand set to the specified value.
821 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
822 assert(OpNo < getNumOperands() && "Operand num is out of range!");
823 assert(Op->getType() == getOperand(OpNo)->getType() &&
824 "Replacing operand with value of different type!");
825 if (getOperand(OpNo) == Op)
826 return const_cast<ConstantExpr*>(this);
828 Constant *Op0, *Op1, *Op2;
829 switch (getOpcode()) {
830 case Instruction::Trunc:
831 case Instruction::ZExt:
832 case Instruction::SExt:
833 case Instruction::FPTrunc:
834 case Instruction::FPExt:
835 case Instruction::UIToFP:
836 case Instruction::SIToFP:
837 case Instruction::FPToUI:
838 case Instruction::FPToSI:
839 case Instruction::PtrToInt:
840 case Instruction::IntToPtr:
841 case Instruction::BitCast:
842 return ConstantExpr::getCast(getOpcode(), Op, getType());
843 case Instruction::Select:
844 Op0 = (OpNo == 0) ? Op : getOperand(0);
845 Op1 = (OpNo == 1) ? Op : getOperand(1);
846 Op2 = (OpNo == 2) ? Op : getOperand(2);
847 return ConstantExpr::getSelect(Op0, Op1, Op2);
848 case Instruction::InsertElement:
849 Op0 = (OpNo == 0) ? Op : getOperand(0);
850 Op1 = (OpNo == 1) ? Op : getOperand(1);
851 Op2 = (OpNo == 2) ? Op : getOperand(2);
852 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
853 case Instruction::ExtractElement:
854 Op0 = (OpNo == 0) ? Op : getOperand(0);
855 Op1 = (OpNo == 1) ? Op : getOperand(1);
856 return ConstantExpr::getExtractElement(Op0, Op1);
857 case Instruction::ShuffleVector:
858 Op0 = (OpNo == 0) ? Op : getOperand(0);
859 Op1 = (OpNo == 1) ? Op : getOperand(1);
860 Op2 = (OpNo == 2) ? Op : getOperand(2);
861 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
862 case Instruction::GetElementPtr: {
863 SmallVector<Constant*, 8> Ops;
864 Ops.resize(getNumOperands()-1);
865 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
866 Ops[i-1] = getOperand(i);
868 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
870 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
873 assert(getNumOperands() == 2 && "Must be binary operator?");
874 Op0 = (OpNo == 0) ? Op : getOperand(0);
875 Op1 = (OpNo == 1) ? Op : getOperand(1);
876 return ConstantExpr::get(getOpcode(), Op0, Op1);
880 /// getWithOperands - This returns the current constant expression with the
881 /// operands replaced with the specified values. The specified operands must
882 /// match count and type with the existing ones.
883 Constant *ConstantExpr::
884 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
885 assert(NumOps == getNumOperands() && "Operand count mismatch!");
886 bool AnyChange = false;
887 for (unsigned i = 0; i != NumOps; ++i) {
888 assert(Ops[i]->getType() == getOperand(i)->getType() &&
889 "Operand type mismatch!");
890 AnyChange |= Ops[i] != getOperand(i);
892 if (!AnyChange) // No operands changed, return self.
893 return const_cast<ConstantExpr*>(this);
895 switch (getOpcode()) {
896 case Instruction::Trunc:
897 case Instruction::ZExt:
898 case Instruction::SExt:
899 case Instruction::FPTrunc:
900 case Instruction::FPExt:
901 case Instruction::UIToFP:
902 case Instruction::SIToFP:
903 case Instruction::FPToUI:
904 case Instruction::FPToSI:
905 case Instruction::PtrToInt:
906 case Instruction::IntToPtr:
907 case Instruction::BitCast:
908 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
909 case Instruction::Select:
910 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
911 case Instruction::InsertElement:
912 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
913 case Instruction::ExtractElement:
914 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
915 case Instruction::ShuffleVector:
916 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
917 case Instruction::GetElementPtr:
918 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
919 case Instruction::ICmp:
920 case Instruction::FCmp:
921 case Instruction::VICmp:
922 case Instruction::VFCmp:
923 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
925 assert(getNumOperands() == 2 && "Must be binary operator?");
926 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
931 //===----------------------------------------------------------------------===//
932 // isValueValidForType implementations
934 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
935 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
936 if (Ty == Type::Int1Ty)
937 return Val == 0 || Val == 1;
939 return true; // always true, has to fit in largest type
940 uint64_t Max = (1ll << NumBits) - 1;
944 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
945 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
946 if (Ty == Type::Int1Ty)
947 return Val == 0 || Val == 1 || Val == -1;
949 return true; // always true, has to fit in largest type
950 int64_t Min = -(1ll << (NumBits-1));
951 int64_t Max = (1ll << (NumBits-1)) - 1;
952 return (Val >= Min && Val <= Max);
955 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
956 // convert modifies in place, so make a copy.
957 APFloat Val2 = APFloat(Val);
958 switch (Ty->getTypeID()) {
960 return false; // These can't be represented as floating point!
962 // FIXME rounding mode needs to be more flexible
963 case Type::FloatTyID:
964 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
965 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
967 case Type::DoubleTyID:
968 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
969 &Val2.getSemantics() == &APFloat::IEEEdouble ||
970 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
972 case Type::X86_FP80TyID:
973 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
974 &Val2.getSemantics() == &APFloat::IEEEdouble ||
975 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
976 case Type::FP128TyID:
977 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
978 &Val2.getSemantics() == &APFloat::IEEEdouble ||
979 &Val2.getSemantics() == &APFloat::IEEEquad;
980 case Type::PPC_FP128TyID:
981 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
982 &Val2.getSemantics() == &APFloat::IEEEdouble ||
983 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
987 //===----------------------------------------------------------------------===//
988 // Factory Function Implementation
991 // The number of operands for each ConstantCreator::create method is
992 // determined by the ConstantTraits template.
993 // ConstantCreator - A class that is used to create constants by
994 // ValueMap*. This class should be partially specialized if there is
995 // something strange that needs to be done to interface to the ctor for the
999 template<class ValType>
1000 struct ConstantTraits;
1002 template<typename T, typename Alloc>
1003 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1004 static unsigned uses(const std::vector<T, Alloc>& v) {
1009 template<class ConstantClass, class TypeClass, class ValType>
1010 struct VISIBILITY_HIDDEN ConstantCreator {
1011 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1012 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1016 template<class ConstantClass, class TypeClass>
1017 struct VISIBILITY_HIDDEN ConvertConstantType {
1018 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1019 assert(0 && "This type cannot be converted!\n");
1024 template<class ValType, class TypeClass, class ConstantClass,
1025 bool HasLargeKey = false /*true for arrays and structs*/ >
1026 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1028 typedef std::pair<const Type*, ValType> MapKey;
1029 typedef std::map<MapKey, Constant *> MapTy;
1030 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1031 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1033 /// Map - This is the main map from the element descriptor to the Constants.
1034 /// This is the primary way we avoid creating two of the same shape
1038 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1039 /// from the constants to their element in Map. This is important for
1040 /// removal of constants from the array, which would otherwise have to scan
1041 /// through the map with very large keys.
1042 InverseMapTy InverseMap;
1044 /// AbstractTypeMap - Map for abstract type constants.
1046 AbstractTypeMapTy AbstractTypeMap;
1049 typename MapTy::iterator map_end() { return Map.end(); }
1051 /// InsertOrGetItem - Return an iterator for the specified element.
1052 /// If the element exists in the map, the returned iterator points to the
1053 /// entry and Exists=true. If not, the iterator points to the newly
1054 /// inserted entry and returns Exists=false. Newly inserted entries have
1055 /// I->second == 0, and should be filled in.
1056 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1059 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1060 Exists = !IP.second;
1065 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1067 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1068 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1069 IMI->second->second == CP &&
1070 "InverseMap corrupt!");
1074 typename MapTy::iterator I =
1075 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1077 if (I == Map.end() || I->second != CP) {
1078 // FIXME: This should not use a linear scan. If this gets to be a
1079 // performance problem, someone should look at this.
1080 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1087 /// getOrCreate - Return the specified constant from the map, creating it if
1089 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1090 MapKey Lookup(Ty, V);
1091 typename MapTy::iterator I = Map.find(Lookup);
1092 // Is it in the map?
1094 return static_cast<ConstantClass *>(I->second);
1096 // If no preexisting value, create one now...
1097 ConstantClass *Result =
1098 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1100 assert(Result->getType() == Ty && "Type specified is not correct!");
1101 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1103 if (HasLargeKey) // Remember the reverse mapping if needed.
1104 InverseMap.insert(std::make_pair(Result, I));
1106 // If the type of the constant is abstract, make sure that an entry exists
1107 // for it in the AbstractTypeMap.
1108 if (Ty->isAbstract()) {
1109 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
1111 if (TI == AbstractTypeMap.end()) {
1112 // Add ourselves to the ATU list of the type.
1113 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1115 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1121 void remove(ConstantClass *CP) {
1122 typename MapTy::iterator I = FindExistingElement(CP);
1123 assert(I != Map.end() && "Constant not found in constant table!");
1124 assert(I->second == CP && "Didn't find correct element?");
1126 if (HasLargeKey) // Remember the reverse mapping if needed.
1127 InverseMap.erase(CP);
1129 // Now that we found the entry, make sure this isn't the entry that
1130 // the AbstractTypeMap points to.
1131 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1132 if (Ty->isAbstract()) {
1133 assert(AbstractTypeMap.count(Ty) &&
1134 "Abstract type not in AbstractTypeMap?");
1135 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1136 if (ATMEntryIt == I) {
1137 // Yes, we are removing the representative entry for this type.
1138 // See if there are any other entries of the same type.
1139 typename MapTy::iterator TmpIt = ATMEntryIt;
1141 // First check the entry before this one...
1142 if (TmpIt != Map.begin()) {
1144 if (TmpIt->first.first != Ty) // Not the same type, move back...
1148 // If we didn't find the same type, try to move forward...
1149 if (TmpIt == ATMEntryIt) {
1151 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1152 --TmpIt; // No entry afterwards with the same type
1155 // If there is another entry in the map of the same abstract type,
1156 // update the AbstractTypeMap entry now.
1157 if (TmpIt != ATMEntryIt) {
1160 // Otherwise, we are removing the last instance of this type
1161 // from the table. Remove from the ATM, and from user list.
1162 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1163 AbstractTypeMap.erase(Ty);
1172 /// MoveConstantToNewSlot - If we are about to change C to be the element
1173 /// specified by I, update our internal data structures to reflect this
1175 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1176 // First, remove the old location of the specified constant in the map.
1177 typename MapTy::iterator OldI = FindExistingElement(C);
1178 assert(OldI != Map.end() && "Constant not found in constant table!");
1179 assert(OldI->second == C && "Didn't find correct element?");
1181 // If this constant is the representative element for its abstract type,
1182 // update the AbstractTypeMap so that the representative element is I.
1183 if (C->getType()->isAbstract()) {
1184 typename AbstractTypeMapTy::iterator ATI =
1185 AbstractTypeMap.find(C->getType());
1186 assert(ATI != AbstractTypeMap.end() &&
1187 "Abstract type not in AbstractTypeMap?");
1188 if (ATI->second == OldI)
1192 // Remove the old entry from the map.
1195 // Update the inverse map so that we know that this constant is now
1196 // located at descriptor I.
1198 assert(I->second == C && "Bad inversemap entry!");
1203 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1204 typename AbstractTypeMapTy::iterator I =
1205 AbstractTypeMap.find(cast<Type>(OldTy));
1207 assert(I != AbstractTypeMap.end() &&
1208 "Abstract type not in AbstractTypeMap?");
1210 // Convert a constant at a time until the last one is gone. The last one
1211 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1212 // eliminated eventually.
1214 ConvertConstantType<ConstantClass,
1215 TypeClass>::convert(
1216 static_cast<ConstantClass *>(I->second->second),
1217 cast<TypeClass>(NewTy));
1219 I = AbstractTypeMap.find(cast<Type>(OldTy));
1220 } while (I != AbstractTypeMap.end());
1223 // If the type became concrete without being refined to any other existing
1224 // type, we just remove ourselves from the ATU list.
1225 void typeBecameConcrete(const DerivedType *AbsTy) {
1226 AbsTy->removeAbstractTypeUser(this);
1230 DOUT << "Constant.cpp: ValueMap\n";
1237 //---- ConstantAggregateZero::get() implementation...
1240 // ConstantAggregateZero does not take extra "value" argument...
1241 template<class ValType>
1242 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1243 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1244 return new ConstantAggregateZero(Ty);
1249 struct ConvertConstantType<ConstantAggregateZero, Type> {
1250 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1251 // Make everyone now use a constant of the new type...
1252 Constant *New = ConstantAggregateZero::get(NewTy);
1253 assert(New != OldC && "Didn't replace constant??");
1254 OldC->uncheckedReplaceAllUsesWith(New);
1255 OldC->destroyConstant(); // This constant is now dead, destroy it.
1260 static ManagedStatic<ValueMap<char, Type,
1261 ConstantAggregateZero> > AggZeroConstants;
1263 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1265 Constant *ConstantAggregateZero::get(const Type *Ty) {
1266 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1267 "Cannot create an aggregate zero of non-aggregate type!");
1268 return AggZeroConstants->getOrCreate(Ty, 0);
1271 // destroyConstant - Remove the constant from the constant table...
1273 void ConstantAggregateZero::destroyConstant() {
1274 AggZeroConstants->remove(this);
1275 destroyConstantImpl();
1278 //---- ConstantArray::get() implementation...
1282 struct ConvertConstantType<ConstantArray, ArrayType> {
1283 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1284 // Make everyone now use a constant of the new type...
1285 std::vector<Constant*> C;
1286 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1287 C.push_back(cast<Constant>(OldC->getOperand(i)));
1288 Constant *New = ConstantArray::get(NewTy, C);
1289 assert(New != OldC && "Didn't replace constant??");
1290 OldC->uncheckedReplaceAllUsesWith(New);
1291 OldC->destroyConstant(); // This constant is now dead, destroy it.
1296 static std::vector<Constant*> getValType(ConstantArray *CA) {
1297 std::vector<Constant*> Elements;
1298 Elements.reserve(CA->getNumOperands());
1299 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1300 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1304 typedef ValueMap<std::vector<Constant*>, ArrayType,
1305 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1306 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1308 Constant *ConstantArray::get(const ArrayType *Ty,
1309 const std::vector<Constant*> &V) {
1310 // If this is an all-zero array, return a ConstantAggregateZero object
1313 if (!C->isNullValue())
1314 return ArrayConstants->getOrCreate(Ty, V);
1315 for (unsigned i = 1, e = V.size(); i != e; ++i)
1317 return ArrayConstants->getOrCreate(Ty, V);
1319 return ConstantAggregateZero::get(Ty);
1322 // destroyConstant - Remove the constant from the constant table...
1324 void ConstantArray::destroyConstant() {
1325 ArrayConstants->remove(this);
1326 destroyConstantImpl();
1329 /// ConstantArray::get(const string&) - Return an array that is initialized to
1330 /// contain the specified string. If length is zero then a null terminator is
1331 /// added to the specified string so that it may be used in a natural way.
1332 /// Otherwise, the length parameter specifies how much of the string to use
1333 /// and it won't be null terminated.
1335 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1336 std::vector<Constant*> ElementVals;
1337 for (unsigned i = 0; i < Str.length(); ++i)
1338 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1340 // Add a null terminator to the string...
1342 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1345 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1346 return ConstantArray::get(ATy, ElementVals);
1349 /// isString - This method returns true if the array is an array of i8, and
1350 /// if the elements of the array are all ConstantInt's.
1351 bool ConstantArray::isString() const {
1352 // Check the element type for i8...
1353 if (getType()->getElementType() != Type::Int8Ty)
1355 // Check the elements to make sure they are all integers, not constant
1357 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1358 if (!isa<ConstantInt>(getOperand(i)))
1363 /// isCString - This method returns true if the array is a string (see
1364 /// isString) and it ends in a null byte \0 and does not contains any other
1365 /// null bytes except its terminator.
1366 bool ConstantArray::isCString() const {
1367 // Check the element type for i8...
1368 if (getType()->getElementType() != Type::Int8Ty)
1370 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1371 // Last element must be a null.
1372 if (getOperand(getNumOperands()-1) != Zero)
1374 // Other elements must be non-null integers.
1375 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1376 if (!isa<ConstantInt>(getOperand(i)))
1378 if (getOperand(i) == Zero)
1385 // getAsString - If the sub-element type of this array is i8
1386 // then this method converts the array to an std::string and returns it.
1387 // Otherwise, it asserts out.
1389 std::string ConstantArray::getAsString() const {
1390 assert(isString() && "Not a string!");
1392 Result.reserve(getNumOperands());
1393 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1394 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1399 //---- ConstantStruct::get() implementation...
1404 struct ConvertConstantType<ConstantStruct, StructType> {
1405 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1406 // Make everyone now use a constant of the new type...
1407 std::vector<Constant*> C;
1408 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1409 C.push_back(cast<Constant>(OldC->getOperand(i)));
1410 Constant *New = ConstantStruct::get(NewTy, C);
1411 assert(New != OldC && "Didn't replace constant??");
1413 OldC->uncheckedReplaceAllUsesWith(New);
1414 OldC->destroyConstant(); // This constant is now dead, destroy it.
1419 typedef ValueMap<std::vector<Constant*>, StructType,
1420 ConstantStruct, true /*largekey*/> StructConstantsTy;
1421 static ManagedStatic<StructConstantsTy> StructConstants;
1423 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1424 std::vector<Constant*> Elements;
1425 Elements.reserve(CS->getNumOperands());
1426 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1427 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1431 Constant *ConstantStruct::get(const StructType *Ty,
1432 const std::vector<Constant*> &V) {
1433 // Create a ConstantAggregateZero value if all elements are zeros...
1434 for (unsigned i = 0, e = V.size(); i != e; ++i)
1435 if (!V[i]->isNullValue())
1436 return StructConstants->getOrCreate(Ty, V);
1438 return ConstantAggregateZero::get(Ty);
1441 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1442 std::vector<const Type*> StructEls;
1443 StructEls.reserve(V.size());
1444 for (unsigned i = 0, e = V.size(); i != e; ++i)
1445 StructEls.push_back(V[i]->getType());
1446 return get(StructType::get(StructEls, packed), V);
1449 // destroyConstant - Remove the constant from the constant table...
1451 void ConstantStruct::destroyConstant() {
1452 StructConstants->remove(this);
1453 destroyConstantImpl();
1456 //---- ConstantVector::get() implementation...
1460 struct ConvertConstantType<ConstantVector, VectorType> {
1461 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1462 // Make everyone now use a constant of the new type...
1463 std::vector<Constant*> C;
1464 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1465 C.push_back(cast<Constant>(OldC->getOperand(i)));
1466 Constant *New = ConstantVector::get(NewTy, C);
1467 assert(New != OldC && "Didn't replace constant??");
1468 OldC->uncheckedReplaceAllUsesWith(New);
1469 OldC->destroyConstant(); // This constant is now dead, destroy it.
1474 static std::vector<Constant*> getValType(ConstantVector *CP) {
1475 std::vector<Constant*> Elements;
1476 Elements.reserve(CP->getNumOperands());
1477 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1478 Elements.push_back(CP->getOperand(i));
1482 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1483 ConstantVector> > VectorConstants;
1485 Constant *ConstantVector::get(const VectorType *Ty,
1486 const std::vector<Constant*> &V) {
1487 assert(!V.empty() && "Vectors can't be empty");
1488 // If this is an all-undef or alll-zero vector, return a
1489 // ConstantAggregateZero or UndefValue.
1491 bool isZero = C->isNullValue();
1492 bool isUndef = isa<UndefValue>(C);
1494 if (isZero || isUndef) {
1495 for (unsigned i = 1, e = V.size(); i != e; ++i)
1497 isZero = isUndef = false;
1503 return ConstantAggregateZero::get(Ty);
1505 return UndefValue::get(Ty);
1506 return VectorConstants->getOrCreate(Ty, V);
1509 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1510 assert(!V.empty() && "Cannot infer type if V is empty");
1511 return get(VectorType::get(V.front()->getType(),V.size()), V);
1514 // destroyConstant - Remove the constant from the constant table...
1516 void ConstantVector::destroyConstant() {
1517 VectorConstants->remove(this);
1518 destroyConstantImpl();
1521 /// This function will return true iff every element in this vector constant
1522 /// is set to all ones.
1523 /// @returns true iff this constant's emements are all set to all ones.
1524 /// @brief Determine if the value is all ones.
1525 bool ConstantVector::isAllOnesValue() const {
1526 // Check out first element.
1527 const Constant *Elt = getOperand(0);
1528 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1529 if (!CI || !CI->isAllOnesValue()) return false;
1530 // Then make sure all remaining elements point to the same value.
1531 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1532 if (getOperand(I) != Elt) return false;
1537 /// getSplatValue - If this is a splat constant, where all of the
1538 /// elements have the same value, return that value. Otherwise return null.
1539 Constant *ConstantVector::getSplatValue() {
1540 // Check out first element.
1541 Constant *Elt = getOperand(0);
1542 // Then make sure all remaining elements point to the same value.
1543 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1544 if (getOperand(I) != Elt) return 0;
1548 //---- ConstantPointerNull::get() implementation...
1552 // ConstantPointerNull does not take extra "value" argument...
1553 template<class ValType>
1554 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1555 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1556 return new ConstantPointerNull(Ty);
1561 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1562 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1563 // Make everyone now use a constant of the new type...
1564 Constant *New = ConstantPointerNull::get(NewTy);
1565 assert(New != OldC && "Didn't replace constant??");
1566 OldC->uncheckedReplaceAllUsesWith(New);
1567 OldC->destroyConstant(); // This constant is now dead, destroy it.
1572 static ManagedStatic<ValueMap<char, PointerType,
1573 ConstantPointerNull> > NullPtrConstants;
1575 static char getValType(ConstantPointerNull *) {
1580 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1581 return NullPtrConstants->getOrCreate(Ty, 0);
1584 // destroyConstant - Remove the constant from the constant table...
1586 void ConstantPointerNull::destroyConstant() {
1587 NullPtrConstants->remove(this);
1588 destroyConstantImpl();
1592 //---- UndefValue::get() implementation...
1596 // UndefValue does not take extra "value" argument...
1597 template<class ValType>
1598 struct ConstantCreator<UndefValue, Type, ValType> {
1599 static UndefValue *create(const Type *Ty, const ValType &V) {
1600 return new UndefValue(Ty);
1605 struct ConvertConstantType<UndefValue, Type> {
1606 static void convert(UndefValue *OldC, const Type *NewTy) {
1607 // Make everyone now use a constant of the new type.
1608 Constant *New = UndefValue::get(NewTy);
1609 assert(New != OldC && "Didn't replace constant??");
1610 OldC->uncheckedReplaceAllUsesWith(New);
1611 OldC->destroyConstant(); // This constant is now dead, destroy it.
1616 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1618 static char getValType(UndefValue *) {
1623 UndefValue *UndefValue::get(const Type *Ty) {
1624 return UndefValueConstants->getOrCreate(Ty, 0);
1627 // destroyConstant - Remove the constant from the constant table.
1629 void UndefValue::destroyConstant() {
1630 UndefValueConstants->remove(this);
1631 destroyConstantImpl();
1635 //---- ConstantExpr::get() implementations...
1640 struct ExprMapKeyType {
1641 typedef SmallVector<unsigned, 4> IndexList;
1643 ExprMapKeyType(unsigned opc,
1644 const std::vector<Constant*> &ops,
1645 unsigned short pred = 0,
1646 const IndexList &inds = IndexList())
1647 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1650 std::vector<Constant*> operands;
1652 bool operator==(const ExprMapKeyType& that) const {
1653 return this->opcode == that.opcode &&
1654 this->predicate == that.predicate &&
1655 this->operands == that.operands;
1656 this->indices == that.indices;
1658 bool operator<(const ExprMapKeyType & that) const {
1659 return this->opcode < that.opcode ||
1660 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1661 (this->opcode == that.opcode && this->predicate == that.predicate &&
1662 this->operands < that.operands) ||
1663 (this->opcode == that.opcode && this->predicate == that.predicate &&
1664 this->operands == that.operands && this->indices < that.indices);
1667 bool operator!=(const ExprMapKeyType& that) const {
1668 return !(*this == that);
1676 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1677 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1678 unsigned short pred = 0) {
1679 if (Instruction::isCast(V.opcode))
1680 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1681 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1682 V.opcode < Instruction::BinaryOpsEnd))
1683 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1684 if (V.opcode == Instruction::Select)
1685 return new SelectConstantExpr(V.operands[0], V.operands[1],
1687 if (V.opcode == Instruction::ExtractElement)
1688 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1689 if (V.opcode == Instruction::InsertElement)
1690 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1692 if (V.opcode == Instruction::ShuffleVector)
1693 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1695 if (V.opcode == Instruction::InsertValue)
1696 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1698 if (V.opcode == Instruction::ExtractValue)
1699 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1700 if (V.opcode == Instruction::GetElementPtr) {
1701 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1702 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1705 // The compare instructions are weird. We have to encode the predicate
1706 // value and it is combined with the instruction opcode by multiplying
1707 // the opcode by one hundred. We must decode this to get the predicate.
1708 if (V.opcode == Instruction::ICmp)
1709 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1710 V.operands[0], V.operands[1]);
1711 if (V.opcode == Instruction::FCmp)
1712 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1713 V.operands[0], V.operands[1]);
1714 if (V.opcode == Instruction::VICmp)
1715 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1716 V.operands[0], V.operands[1]);
1717 if (V.opcode == Instruction::VFCmp)
1718 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1719 V.operands[0], V.operands[1]);
1720 assert(0 && "Invalid ConstantExpr!");
1726 struct ConvertConstantType<ConstantExpr, Type> {
1727 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1729 switch (OldC->getOpcode()) {
1730 case Instruction::Trunc:
1731 case Instruction::ZExt:
1732 case Instruction::SExt:
1733 case Instruction::FPTrunc:
1734 case Instruction::FPExt:
1735 case Instruction::UIToFP:
1736 case Instruction::SIToFP:
1737 case Instruction::FPToUI:
1738 case Instruction::FPToSI:
1739 case Instruction::PtrToInt:
1740 case Instruction::IntToPtr:
1741 case Instruction::BitCast:
1742 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1745 case Instruction::Select:
1746 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1747 OldC->getOperand(1),
1748 OldC->getOperand(2));
1751 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1752 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1753 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1754 OldC->getOperand(1));
1756 case Instruction::GetElementPtr:
1757 // Make everyone now use a constant of the new type...
1758 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1759 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1760 &Idx[0], Idx.size());
1764 assert(New != OldC && "Didn't replace constant??");
1765 OldC->uncheckedReplaceAllUsesWith(New);
1766 OldC->destroyConstant(); // This constant is now dead, destroy it.
1769 } // end namespace llvm
1772 static ExprMapKeyType getValType(ConstantExpr *CE) {
1773 std::vector<Constant*> Operands;
1774 Operands.reserve(CE->getNumOperands());
1775 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1776 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1777 return ExprMapKeyType(CE->getOpcode(), Operands,
1778 CE->isCompare() ? CE->getPredicate() : 0,
1780 CE->getIndices() : SmallVector<unsigned, 4>());
1783 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1784 ConstantExpr> > ExprConstants;
1786 /// This is a utility function to handle folding of casts and lookup of the
1787 /// cast in the ExprConstants map. It is used by the various get* methods below.
1788 static inline Constant *getFoldedCast(
1789 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1790 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1791 // Fold a few common cases
1792 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1795 // Look up the constant in the table first to ensure uniqueness
1796 std::vector<Constant*> argVec(1, C);
1797 ExprMapKeyType Key(opc, argVec);
1798 return ExprConstants->getOrCreate(Ty, Key);
1801 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1802 Instruction::CastOps opc = Instruction::CastOps(oc);
1803 assert(Instruction::isCast(opc) && "opcode out of range");
1804 assert(C && Ty && "Null arguments to getCast");
1805 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1809 assert(0 && "Invalid cast opcode");
1811 case Instruction::Trunc: return getTrunc(C, Ty);
1812 case Instruction::ZExt: return getZExt(C, Ty);
1813 case Instruction::SExt: return getSExt(C, Ty);
1814 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1815 case Instruction::FPExt: return getFPExtend(C, Ty);
1816 case Instruction::UIToFP: return getUIToFP(C, Ty);
1817 case Instruction::SIToFP: return getSIToFP(C, Ty);
1818 case Instruction::FPToUI: return getFPToUI(C, Ty);
1819 case Instruction::FPToSI: return getFPToSI(C, Ty);
1820 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1821 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1822 case Instruction::BitCast: return getBitCast(C, Ty);
1827 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1828 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1829 return getCast(Instruction::BitCast, C, Ty);
1830 return getCast(Instruction::ZExt, C, Ty);
1833 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1834 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1835 return getCast(Instruction::BitCast, C, Ty);
1836 return getCast(Instruction::SExt, C, Ty);
1839 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1840 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1841 return getCast(Instruction::BitCast, C, Ty);
1842 return getCast(Instruction::Trunc, C, Ty);
1845 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1846 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1847 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1849 if (Ty->isInteger())
1850 return getCast(Instruction::PtrToInt, S, Ty);
1851 return getCast(Instruction::BitCast, S, Ty);
1854 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1856 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1857 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1858 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1859 Instruction::CastOps opcode =
1860 (SrcBits == DstBits ? Instruction::BitCast :
1861 (SrcBits > DstBits ? Instruction::Trunc :
1862 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1863 return getCast(opcode, C, Ty);
1866 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1867 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1869 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1870 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1871 if (SrcBits == DstBits)
1872 return C; // Avoid a useless cast
1873 Instruction::CastOps opcode =
1874 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1875 return getCast(opcode, C, Ty);
1878 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1879 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1880 assert(Ty->isInteger() && "Trunc produces only integral");
1881 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1882 "SrcTy must be larger than DestTy for Trunc!");
1884 return getFoldedCast(Instruction::Trunc, C, Ty);
1887 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1888 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1889 assert(Ty->isInteger() && "SExt produces only integer");
1890 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1891 "SrcTy must be smaller than DestTy for SExt!");
1893 return getFoldedCast(Instruction::SExt, C, Ty);
1896 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1897 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1898 assert(Ty->isInteger() && "ZExt produces only integer");
1899 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1900 "SrcTy must be smaller than DestTy for ZExt!");
1902 return getFoldedCast(Instruction::ZExt, C, Ty);
1905 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1906 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1907 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1908 "This is an illegal floating point truncation!");
1909 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1912 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1913 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1914 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1915 "This is an illegal floating point extension!");
1916 return getFoldedCast(Instruction::FPExt, C, Ty);
1919 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1920 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1921 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1922 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1923 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1924 "This is an illegal uint to floating point cast!");
1925 return getFoldedCast(Instruction::UIToFP, C, Ty);
1928 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1929 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1930 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1931 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1932 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1933 "This is an illegal sint to floating point cast!");
1934 return getFoldedCast(Instruction::SIToFP, C, Ty);
1937 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1938 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1939 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1940 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1941 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1942 "This is an illegal floating point to uint cast!");
1943 return getFoldedCast(Instruction::FPToUI, C, Ty);
1946 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1947 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1948 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1949 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1950 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1951 "This is an illegal floating point to sint cast!");
1952 return getFoldedCast(Instruction::FPToSI, C, Ty);
1955 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1956 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1957 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1958 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1961 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1962 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1963 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1964 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1967 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1968 // BitCast implies a no-op cast of type only. No bits change. However, you
1969 // can't cast pointers to anything but pointers.
1970 const Type *SrcTy = C->getType();
1971 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1972 "BitCast cannot cast pointer to non-pointer and vice versa");
1974 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1975 // or nonptr->ptr). For all the other types, the cast is okay if source and
1976 // destination bit widths are identical.
1977 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1978 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1979 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1980 return getFoldedCast(Instruction::BitCast, C, DstTy);
1983 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1984 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1985 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1987 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1988 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1991 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1992 Constant *C1, Constant *C2) {
1993 // Check the operands for consistency first
1994 assert(Opcode >= Instruction::BinaryOpsBegin &&
1995 Opcode < Instruction::BinaryOpsEnd &&
1996 "Invalid opcode in binary constant expression");
1997 assert(C1->getType() == C2->getType() &&
1998 "Operand types in binary constant expression should match");
2000 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2001 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2002 return FC; // Fold a few common cases...
2004 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2005 ExprMapKeyType Key(Opcode, argVec);
2006 return ExprConstants->getOrCreate(ReqTy, Key);
2009 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2010 Constant *C1, Constant *C2) {
2011 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
2012 switch (predicate) {
2013 default: assert(0 && "Invalid CmpInst predicate");
2014 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2015 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2016 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2017 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2018 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2019 case CmpInst::FCMP_TRUE:
2020 return isVectorType ? getVFCmp(predicate, C1, C2)
2021 : getFCmp(predicate, C1, C2);
2022 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2023 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2024 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2025 case CmpInst::ICMP_SLE:
2026 return isVectorType ? getVICmp(predicate, C1, C2)
2027 : getICmp(predicate, C1, C2);
2031 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2034 case Instruction::Add:
2035 case Instruction::Sub:
2036 case Instruction::Mul:
2037 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2038 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
2039 isa<VectorType>(C1->getType())) &&
2040 "Tried to create an arithmetic operation on a non-arithmetic type!");
2042 case Instruction::UDiv:
2043 case Instruction::SDiv:
2044 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2045 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2046 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2047 "Tried to create an arithmetic operation on a non-arithmetic type!");
2049 case Instruction::FDiv:
2050 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2051 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2052 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2053 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2055 case Instruction::URem:
2056 case Instruction::SRem:
2057 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2058 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2059 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2060 "Tried to create an arithmetic operation on a non-arithmetic type!");
2062 case Instruction::FRem:
2063 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2064 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2065 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2066 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2068 case Instruction::And:
2069 case Instruction::Or:
2070 case Instruction::Xor:
2071 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2072 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
2073 "Tried to create a logical operation on a non-integral type!");
2075 case Instruction::Shl:
2076 case Instruction::LShr:
2077 case Instruction::AShr:
2078 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2079 assert(C1->getType()->isInteger() &&
2080 "Tried to create a shift operation on a non-integer type!");
2087 return getTy(C1->getType(), Opcode, C1, C2);
2090 Constant *ConstantExpr::getCompare(unsigned short pred,
2091 Constant *C1, Constant *C2) {
2092 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2093 return getCompareTy(pred, C1, C2);
2096 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2097 Constant *V1, Constant *V2) {
2098 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
2099 assert(V1->getType() == V2->getType() && "Select value types must match!");
2100 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
2102 if (ReqTy == V1->getType())
2103 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2104 return SC; // Fold common cases
2106 std::vector<Constant*> argVec(3, C);
2109 ExprMapKeyType Key(Instruction::Select, argVec);
2110 return ExprConstants->getOrCreate(ReqTy, Key);
2113 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2116 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2118 cast<PointerType>(ReqTy)->getElementType() &&
2119 "GEP indices invalid!");
2121 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2122 return FC; // Fold a few common cases...
2124 assert(isa<PointerType>(C->getType()) &&
2125 "Non-pointer type for constant GetElementPtr expression");
2126 // Look up the constant in the table first to ensure uniqueness
2127 std::vector<Constant*> ArgVec;
2128 ArgVec.reserve(NumIdx+1);
2129 ArgVec.push_back(C);
2130 for (unsigned i = 0; i != NumIdx; ++i)
2131 ArgVec.push_back(cast<Constant>(Idxs[i]));
2132 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2133 return ExprConstants->getOrCreate(ReqTy, Key);
2136 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2138 // Get the result type of the getelementptr!
2140 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2141 assert(Ty && "GEP indices invalid!");
2142 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2143 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2146 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2148 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2153 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2154 assert(LHS->getType() == RHS->getType());
2155 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2156 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2158 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2159 return FC; // Fold a few common cases...
2161 // Look up the constant in the table first to ensure uniqueness
2162 std::vector<Constant*> ArgVec;
2163 ArgVec.push_back(LHS);
2164 ArgVec.push_back(RHS);
2165 // Get the key type with both the opcode and predicate
2166 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2167 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2171 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2172 assert(LHS->getType() == RHS->getType());
2173 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2175 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2176 return FC; // Fold a few common cases...
2178 // Look up the constant in the table first to ensure uniqueness
2179 std::vector<Constant*> ArgVec;
2180 ArgVec.push_back(LHS);
2181 ArgVec.push_back(RHS);
2182 // Get the key type with both the opcode and predicate
2183 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2184 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2188 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2189 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
2190 "Tried to create vicmp operation on non-vector type!");
2191 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2192 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2194 const VectorType *VTy = cast<VectorType>(LHS->getType());
2195 const Type *EltTy = VTy->getElementType();
2196 unsigned NumElts = VTy->getNumElements();
2198 // See if we can fold the element-wise comparison of the LHS and RHS.
2199 SmallVector<Constant *, 16> LHSElts, RHSElts;
2200 LHS->getVectorElements(LHSElts);
2201 RHS->getVectorElements(RHSElts);
2203 if (!LHSElts.empty() && !RHSElts.empty()) {
2204 SmallVector<Constant *, 16> Elts;
2205 for (unsigned i = 0; i != NumElts; ++i) {
2206 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2208 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2209 if (FCI->getZExtValue())
2210 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2212 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2213 } else if (FC && isa<UndefValue>(FC)) {
2214 Elts.push_back(UndefValue::get(EltTy));
2219 if (Elts.size() == NumElts)
2220 return ConstantVector::get(&Elts[0], Elts.size());
2223 // Look up the constant in the table first to ensure uniqueness
2224 std::vector<Constant*> ArgVec;
2225 ArgVec.push_back(LHS);
2226 ArgVec.push_back(RHS);
2227 // Get the key type with both the opcode and predicate
2228 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2229 return ExprConstants->getOrCreate(LHS->getType(), Key);
2233 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2234 assert(isa<VectorType>(LHS->getType()) &&
2235 "Tried to create vfcmp operation on non-vector type!");
2236 assert(LHS->getType() == RHS->getType());
2237 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2239 const VectorType *VTy = cast<VectorType>(LHS->getType());
2240 unsigned NumElts = VTy->getNumElements();
2241 const Type *EltTy = VTy->getElementType();
2242 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2243 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2245 // See if we can fold the element-wise comparison of the LHS and RHS.
2246 SmallVector<Constant *, 16> LHSElts, RHSElts;
2247 LHS->getVectorElements(LHSElts);
2248 RHS->getVectorElements(RHSElts);
2250 if (!LHSElts.empty() && !RHSElts.empty()) {
2251 SmallVector<Constant *, 16> Elts;
2252 for (unsigned i = 0; i != NumElts; ++i) {
2253 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2255 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2256 if (FCI->getZExtValue())
2257 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2259 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2260 } else if (FC && isa<UndefValue>(FC)) {
2261 Elts.push_back(UndefValue::get(REltTy));
2266 if (Elts.size() == NumElts)
2267 return ConstantVector::get(&Elts[0], Elts.size());
2270 // Look up the constant in the table first to ensure uniqueness
2271 std::vector<Constant*> ArgVec;
2272 ArgVec.push_back(LHS);
2273 ArgVec.push_back(RHS);
2274 // Get the key type with both the opcode and predicate
2275 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2276 return ExprConstants->getOrCreate(ResultTy, Key);
2279 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2281 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2282 return FC; // Fold a few common cases...
2283 // Look up the constant in the table first to ensure uniqueness
2284 std::vector<Constant*> ArgVec(1, Val);
2285 ArgVec.push_back(Idx);
2286 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2287 return ExprConstants->getOrCreate(ReqTy, Key);
2290 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2291 assert(isa<VectorType>(Val->getType()) &&
2292 "Tried to create extractelement operation on non-vector type!");
2293 assert(Idx->getType() == Type::Int32Ty &&
2294 "Extractelement index must be i32 type!");
2295 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2299 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2300 Constant *Elt, Constant *Idx) {
2301 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2302 return FC; // Fold a few common cases...
2303 // Look up the constant in the table first to ensure uniqueness
2304 std::vector<Constant*> ArgVec(1, Val);
2305 ArgVec.push_back(Elt);
2306 ArgVec.push_back(Idx);
2307 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2308 return ExprConstants->getOrCreate(ReqTy, Key);
2311 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2313 assert(isa<VectorType>(Val->getType()) &&
2314 "Tried to create insertelement operation on non-vector type!");
2315 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2316 && "Insertelement types must match!");
2317 assert(Idx->getType() == Type::Int32Ty &&
2318 "Insertelement index must be i32 type!");
2319 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2323 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2324 Constant *V2, Constant *Mask) {
2325 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2326 return FC; // Fold a few common cases...
2327 // Look up the constant in the table first to ensure uniqueness
2328 std::vector<Constant*> ArgVec(1, V1);
2329 ArgVec.push_back(V2);
2330 ArgVec.push_back(Mask);
2331 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2332 return ExprConstants->getOrCreate(ReqTy, Key);
2335 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2337 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2338 "Invalid shuffle vector constant expr operands!");
2339 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2342 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2344 const unsigned *Idxs, unsigned NumIdx) {
2345 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2346 Idxs+NumIdx) == Val->getType() &&
2347 "insertvalue indices invalid!");
2348 assert(Agg->getType() == ReqTy &&
2349 "insertvalue type invalid!");
2350 assert(Agg->getType()->isFirstClassType() &&
2351 "Non-first-class type for constant InsertValue expression");
2352 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2353 assert(FC && "InsertValue constant expr couldn't be folded!");
2357 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2358 const unsigned *IdxList, unsigned NumIdx) {
2359 assert(Agg->getType()->isFirstClassType() &&
2360 "Tried to create insertelement operation on non-first-class type!");
2362 const Type *ReqTy = Agg->getType();
2364 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2365 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2366 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2369 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2370 const unsigned *Idxs, unsigned NumIdx) {
2371 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2372 Idxs+NumIdx) == ReqTy &&
2373 "extractvalue indices invalid!");
2374 assert(Agg->getType()->isFirstClassType() &&
2375 "Non-first-class type for constant extractvalue expression");
2376 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2377 assert(FC && "ExtractValue constant expr couldn't be folded!");
2381 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2382 const unsigned *IdxList, unsigned NumIdx) {
2383 assert(Agg->getType()->isFirstClassType() &&
2384 "Tried to create extractelement operation on non-first-class type!");
2387 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2388 assert(ReqTy && "extractvalue indices invalid!");
2389 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2392 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2393 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2394 if (PTy->getElementType()->isFloatingPoint()) {
2395 std::vector<Constant*> zeros(PTy->getNumElements(),
2396 ConstantFP::getNegativeZero(PTy->getElementType()));
2397 return ConstantVector::get(PTy, zeros);
2400 if (Ty->isFloatingPoint())
2401 return ConstantFP::getNegativeZero(Ty);
2403 return Constant::getNullValue(Ty);
2406 // destroyConstant - Remove the constant from the constant table...
2408 void ConstantExpr::destroyConstant() {
2409 ExprConstants->remove(this);
2410 destroyConstantImpl();
2413 const char *ConstantExpr::getOpcodeName() const {
2414 return Instruction::getOpcodeName(getOpcode());
2417 //===----------------------------------------------------------------------===//
2418 // replaceUsesOfWithOnConstant implementations
2420 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2421 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2424 /// Note that we intentionally replace all uses of From with To here. Consider
2425 /// a large array that uses 'From' 1000 times. By handling this case all here,
2426 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2427 /// single invocation handles all 1000 uses. Handling them one at a time would
2428 /// work, but would be really slow because it would have to unique each updated
2430 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2432 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2433 Constant *ToC = cast<Constant>(To);
2435 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2436 Lookup.first.first = getType();
2437 Lookup.second = this;
2439 std::vector<Constant*> &Values = Lookup.first.second;
2440 Values.reserve(getNumOperands()); // Build replacement array.
2442 // Fill values with the modified operands of the constant array. Also,
2443 // compute whether this turns into an all-zeros array.
2444 bool isAllZeros = false;
2445 unsigned NumUpdated = 0;
2446 if (!ToC->isNullValue()) {
2447 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2448 Constant *Val = cast<Constant>(O->get());
2453 Values.push_back(Val);
2457 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2458 Constant *Val = cast<Constant>(O->get());
2463 Values.push_back(Val);
2464 if (isAllZeros) isAllZeros = Val->isNullValue();
2468 Constant *Replacement = 0;
2470 Replacement = ConstantAggregateZero::get(getType());
2472 // Check to see if we have this array type already.
2474 ArrayConstantsTy::MapTy::iterator I =
2475 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2478 Replacement = I->second;
2480 // Okay, the new shape doesn't exist in the system yet. Instead of
2481 // creating a new constant array, inserting it, replaceallusesof'ing the
2482 // old with the new, then deleting the old... just update the current one
2484 ArrayConstants->MoveConstantToNewSlot(this, I);
2486 // Update to the new value. Optimize for the case when we have a single
2487 // operand that we're changing, but handle bulk updates efficiently.
2488 if (NumUpdated == 1) {
2489 unsigned OperandToUpdate = U-OperandList;
2490 assert(getOperand(OperandToUpdate) == From &&
2491 "ReplaceAllUsesWith broken!");
2492 setOperand(OperandToUpdate, ToC);
2494 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2495 if (getOperand(i) == From)
2502 // Otherwise, I do need to replace this with an existing value.
2503 assert(Replacement != this && "I didn't contain From!");
2505 // Everyone using this now uses the replacement.
2506 uncheckedReplaceAllUsesWith(Replacement);
2508 // Delete the old constant!
2512 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2514 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2515 Constant *ToC = cast<Constant>(To);
2517 unsigned OperandToUpdate = U-OperandList;
2518 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2520 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2521 Lookup.first.first = getType();
2522 Lookup.second = this;
2523 std::vector<Constant*> &Values = Lookup.first.second;
2524 Values.reserve(getNumOperands()); // Build replacement struct.
2527 // Fill values with the modified operands of the constant struct. Also,
2528 // compute whether this turns into an all-zeros struct.
2529 bool isAllZeros = false;
2530 if (!ToC->isNullValue()) {
2531 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2532 Values.push_back(cast<Constant>(O->get()));
2535 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2536 Constant *Val = cast<Constant>(O->get());
2537 Values.push_back(Val);
2538 if (isAllZeros) isAllZeros = Val->isNullValue();
2541 Values[OperandToUpdate] = ToC;
2543 Constant *Replacement = 0;
2545 Replacement = ConstantAggregateZero::get(getType());
2547 // Check to see if we have this array type already.
2549 StructConstantsTy::MapTy::iterator I =
2550 StructConstants->InsertOrGetItem(Lookup, Exists);
2553 Replacement = I->second;
2555 // Okay, the new shape doesn't exist in the system yet. Instead of
2556 // creating a new constant struct, inserting it, replaceallusesof'ing the
2557 // old with the new, then deleting the old... just update the current one
2559 StructConstants->MoveConstantToNewSlot(this, I);
2561 // Update to the new value.
2562 setOperand(OperandToUpdate, ToC);
2567 assert(Replacement != this && "I didn't contain From!");
2569 // Everyone using this now uses the replacement.
2570 uncheckedReplaceAllUsesWith(Replacement);
2572 // Delete the old constant!
2576 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2578 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2580 std::vector<Constant*> Values;
2581 Values.reserve(getNumOperands()); // Build replacement array...
2582 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2583 Constant *Val = getOperand(i);
2584 if (Val == From) Val = cast<Constant>(To);
2585 Values.push_back(Val);
2588 Constant *Replacement = ConstantVector::get(getType(), Values);
2589 assert(Replacement != this && "I didn't contain From!");
2591 // Everyone using this now uses the replacement.
2592 uncheckedReplaceAllUsesWith(Replacement);
2594 // Delete the old constant!
2598 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2600 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2601 Constant *To = cast<Constant>(ToV);
2603 Constant *Replacement = 0;
2604 if (getOpcode() == Instruction::GetElementPtr) {
2605 SmallVector<Constant*, 8> Indices;
2606 Constant *Pointer = getOperand(0);
2607 Indices.reserve(getNumOperands()-1);
2608 if (Pointer == From) Pointer = To;
2610 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2611 Constant *Val = getOperand(i);
2612 if (Val == From) Val = To;
2613 Indices.push_back(Val);
2615 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2616 &Indices[0], Indices.size());
2617 } else if (getOpcode() == Instruction::ExtractValue) {
2618 Constant *Agg = getOperand(0);
2619 if (Agg == From) Agg = To;
2621 const SmallVector<unsigned, 4> &Indices = getIndices();
2622 Replacement = ConstantExpr::getExtractValue(Agg,
2623 &Indices[0], Indices.size());
2624 } else if (getOpcode() == Instruction::InsertValue) {
2625 Constant *Agg = getOperand(0);
2626 Constant *Val = getOperand(1);
2627 if (Agg == From) Agg = To;
2628 if (Val == From) Val = To;
2630 const SmallVector<unsigned, 4> &Indices = getIndices();
2631 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2632 &Indices[0], Indices.size());
2633 } else if (isCast()) {
2634 assert(getOperand(0) == From && "Cast only has one use!");
2635 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2636 } else if (getOpcode() == Instruction::Select) {
2637 Constant *C1 = getOperand(0);
2638 Constant *C2 = getOperand(1);
2639 Constant *C3 = getOperand(2);
2640 if (C1 == From) C1 = To;
2641 if (C2 == From) C2 = To;
2642 if (C3 == From) C3 = To;
2643 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2644 } else if (getOpcode() == Instruction::ExtractElement) {
2645 Constant *C1 = getOperand(0);
2646 Constant *C2 = getOperand(1);
2647 if (C1 == From) C1 = To;
2648 if (C2 == From) C2 = To;
2649 Replacement = ConstantExpr::getExtractElement(C1, C2);
2650 } else if (getOpcode() == Instruction::InsertElement) {
2651 Constant *C1 = getOperand(0);
2652 Constant *C2 = getOperand(1);
2653 Constant *C3 = getOperand(1);
2654 if (C1 == From) C1 = To;
2655 if (C2 == From) C2 = To;
2656 if (C3 == From) C3 = To;
2657 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2658 } else if (getOpcode() == Instruction::ShuffleVector) {
2659 Constant *C1 = getOperand(0);
2660 Constant *C2 = getOperand(1);
2661 Constant *C3 = getOperand(2);
2662 if (C1 == From) C1 = To;
2663 if (C2 == From) C2 = To;
2664 if (C3 == From) C3 = To;
2665 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2666 } else if (isCompare()) {
2667 Constant *C1 = getOperand(0);
2668 Constant *C2 = getOperand(1);
2669 if (C1 == From) C1 = To;
2670 if (C2 == From) C2 = To;
2671 if (getOpcode() == Instruction::ICmp)
2672 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2673 else if (getOpcode() == Instruction::FCmp)
2674 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2675 else if (getOpcode() == Instruction::VICmp)
2676 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2678 assert(getOpcode() == Instruction::VFCmp);
2679 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
2681 } else if (getNumOperands() == 2) {
2682 Constant *C1 = getOperand(0);
2683 Constant *C2 = getOperand(1);
2684 if (C1 == From) C1 = To;
2685 if (C2 == From) C2 = To;
2686 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2688 assert(0 && "Unknown ConstantExpr type!");
2692 assert(Replacement != this && "I didn't contain From!");
2694 // Everyone using this now uses the replacement.
2695 uncheckedReplaceAllUsesWith(Replacement);
2697 // Delete the old constant!