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()) && "Cannot NOT a nonintegral value!");
760 return get(Instruction::Xor, C,
761 ConstantInt::getAllOnesValue(C->getType()));
763 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
764 return get(Instruction::Add, C1, C2);
766 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
767 return get(Instruction::Sub, C1, C2);
769 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
770 return get(Instruction::Mul, C1, C2);
772 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
773 return get(Instruction::UDiv, C1, C2);
775 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
776 return get(Instruction::SDiv, C1, C2);
778 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
779 return get(Instruction::FDiv, C1, C2);
781 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
782 return get(Instruction::URem, C1, C2);
784 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
785 return get(Instruction::SRem, C1, C2);
787 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
788 return get(Instruction::FRem, C1, C2);
790 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
791 return get(Instruction::And, C1, C2);
793 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
794 return get(Instruction::Or, C1, C2);
796 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
797 return get(Instruction::Xor, C1, C2);
799 unsigned ConstantExpr::getPredicate() const {
800 assert(getOpcode() == Instruction::FCmp ||
801 getOpcode() == Instruction::ICmp ||
802 getOpcode() == Instruction::VFCmp ||
803 getOpcode() == Instruction::VICmp);
804 return ((const CompareConstantExpr*)this)->predicate;
806 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
807 return get(Instruction::Shl, C1, C2);
809 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
810 return get(Instruction::LShr, C1, C2);
812 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
813 return get(Instruction::AShr, C1, C2);
816 /// getWithOperandReplaced - Return a constant expression identical to this
817 /// one, but with the specified operand set to the specified value.
819 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
820 assert(OpNo < getNumOperands() && "Operand num is out of range!");
821 assert(Op->getType() == getOperand(OpNo)->getType() &&
822 "Replacing operand with value of different type!");
823 if (getOperand(OpNo) == Op)
824 return const_cast<ConstantExpr*>(this);
826 Constant *Op0, *Op1, *Op2;
827 switch (getOpcode()) {
828 case Instruction::Trunc:
829 case Instruction::ZExt:
830 case Instruction::SExt:
831 case Instruction::FPTrunc:
832 case Instruction::FPExt:
833 case Instruction::UIToFP:
834 case Instruction::SIToFP:
835 case Instruction::FPToUI:
836 case Instruction::FPToSI:
837 case Instruction::PtrToInt:
838 case Instruction::IntToPtr:
839 case Instruction::BitCast:
840 return ConstantExpr::getCast(getOpcode(), Op, getType());
841 case Instruction::Select:
842 Op0 = (OpNo == 0) ? Op : getOperand(0);
843 Op1 = (OpNo == 1) ? Op : getOperand(1);
844 Op2 = (OpNo == 2) ? Op : getOperand(2);
845 return ConstantExpr::getSelect(Op0, Op1, Op2);
846 case Instruction::InsertElement:
847 Op0 = (OpNo == 0) ? Op : getOperand(0);
848 Op1 = (OpNo == 1) ? Op : getOperand(1);
849 Op2 = (OpNo == 2) ? Op : getOperand(2);
850 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
851 case Instruction::ExtractElement:
852 Op0 = (OpNo == 0) ? Op : getOperand(0);
853 Op1 = (OpNo == 1) ? Op : getOperand(1);
854 return ConstantExpr::getExtractElement(Op0, Op1);
855 case Instruction::ShuffleVector:
856 Op0 = (OpNo == 0) ? Op : getOperand(0);
857 Op1 = (OpNo == 1) ? Op : getOperand(1);
858 Op2 = (OpNo == 2) ? Op : getOperand(2);
859 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
860 case Instruction::GetElementPtr: {
861 SmallVector<Constant*, 8> Ops;
862 Ops.resize(getNumOperands()-1);
863 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
864 Ops[i-1] = getOperand(i);
866 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
868 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
871 assert(getNumOperands() == 2 && "Must be binary operator?");
872 Op0 = (OpNo == 0) ? Op : getOperand(0);
873 Op1 = (OpNo == 1) ? Op : getOperand(1);
874 return ConstantExpr::get(getOpcode(), Op0, Op1);
878 /// getWithOperands - This returns the current constant expression with the
879 /// operands replaced with the specified values. The specified operands must
880 /// match count and type with the existing ones.
881 Constant *ConstantExpr::
882 getWithOperands(const std::vector<Constant*> &Ops) const {
883 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
884 bool AnyChange = false;
885 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
886 assert(Ops[i]->getType() == getOperand(i)->getType() &&
887 "Operand type mismatch!");
888 AnyChange |= Ops[i] != getOperand(i);
890 if (!AnyChange) // No operands changed, return self.
891 return const_cast<ConstantExpr*>(this);
893 switch (getOpcode()) {
894 case Instruction::Trunc:
895 case Instruction::ZExt:
896 case Instruction::SExt:
897 case Instruction::FPTrunc:
898 case Instruction::FPExt:
899 case Instruction::UIToFP:
900 case Instruction::SIToFP:
901 case Instruction::FPToUI:
902 case Instruction::FPToSI:
903 case Instruction::PtrToInt:
904 case Instruction::IntToPtr:
905 case Instruction::BitCast:
906 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
907 case Instruction::Select:
908 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
909 case Instruction::InsertElement:
910 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
911 case Instruction::ExtractElement:
912 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
913 case Instruction::ShuffleVector:
914 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
915 case Instruction::GetElementPtr:
916 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
917 case Instruction::ICmp:
918 case Instruction::FCmp:
919 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
921 assert(getNumOperands() == 2 && "Must be binary operator?");
922 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
927 //===----------------------------------------------------------------------===//
928 // isValueValidForType implementations
930 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
931 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
932 if (Ty == Type::Int1Ty)
933 return Val == 0 || Val == 1;
935 return true; // always true, has to fit in largest type
936 uint64_t Max = (1ll << NumBits) - 1;
940 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
941 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
942 if (Ty == Type::Int1Ty)
943 return Val == 0 || Val == 1 || Val == -1;
945 return true; // always true, has to fit in largest type
946 int64_t Min = -(1ll << (NumBits-1));
947 int64_t Max = (1ll << (NumBits-1)) - 1;
948 return (Val >= Min && Val <= Max);
951 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
952 // convert modifies in place, so make a copy.
953 APFloat Val2 = APFloat(Val);
954 switch (Ty->getTypeID()) {
956 return false; // These can't be represented as floating point!
958 // FIXME rounding mode needs to be more flexible
959 case Type::FloatTyID:
960 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
961 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) ==
963 case Type::DoubleTyID:
964 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
965 &Val2.getSemantics() == &APFloat::IEEEdouble ||
966 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) ==
968 case Type::X86_FP80TyID:
969 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
970 &Val2.getSemantics() == &APFloat::IEEEdouble ||
971 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
972 case Type::FP128TyID:
973 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
974 &Val2.getSemantics() == &APFloat::IEEEdouble ||
975 &Val2.getSemantics() == &APFloat::IEEEquad;
976 case Type::PPC_FP128TyID:
977 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
978 &Val2.getSemantics() == &APFloat::IEEEdouble ||
979 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
983 //===----------------------------------------------------------------------===//
984 // Factory Function Implementation
987 // The number of operands for each ConstantCreator::create method is
988 // determined by the ConstantTraits template.
989 // ConstantCreator - A class that is used to create constants by
990 // ValueMap*. This class should be partially specialized if there is
991 // something strange that needs to be done to interface to the ctor for the
995 template<class ValType>
996 struct ConstantTraits;
998 template<typename T, typename Alloc>
999 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1000 static unsigned uses(const std::vector<T, Alloc>& v) {
1005 template<class ConstantClass, class TypeClass, class ValType>
1006 struct VISIBILITY_HIDDEN ConstantCreator {
1007 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1008 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1012 template<class ConstantClass, class TypeClass>
1013 struct VISIBILITY_HIDDEN ConvertConstantType {
1014 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1015 assert(0 && "This type cannot be converted!\n");
1020 template<class ValType, class TypeClass, class ConstantClass,
1021 bool HasLargeKey = false /*true for arrays and structs*/ >
1022 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1024 typedef std::pair<const Type*, ValType> MapKey;
1025 typedef std::map<MapKey, Constant *> MapTy;
1026 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1027 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1029 /// Map - This is the main map from the element descriptor to the Constants.
1030 /// This is the primary way we avoid creating two of the same shape
1034 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1035 /// from the constants to their element in Map. This is important for
1036 /// removal of constants from the array, which would otherwise have to scan
1037 /// through the map with very large keys.
1038 InverseMapTy InverseMap;
1040 /// AbstractTypeMap - Map for abstract type constants.
1042 AbstractTypeMapTy AbstractTypeMap;
1045 typename MapTy::iterator map_end() { return Map.end(); }
1047 /// InsertOrGetItem - Return an iterator for the specified element.
1048 /// If the element exists in the map, the returned iterator points to the
1049 /// entry and Exists=true. If not, the iterator points to the newly
1050 /// inserted entry and returns Exists=false. Newly inserted entries have
1051 /// I->second == 0, and should be filled in.
1052 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1055 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1056 Exists = !IP.second;
1061 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1063 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1064 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1065 IMI->second->second == CP &&
1066 "InverseMap corrupt!");
1070 typename MapTy::iterator I =
1071 Map.find(MapKey((TypeClass*)CP->getRawType(), getValType(CP)));
1072 if (I == Map.end() || I->second != CP) {
1073 // FIXME: This should not use a linear scan. If this gets to be a
1074 // performance problem, someone should look at this.
1075 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1082 /// getOrCreate - Return the specified constant from the map, creating it if
1084 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1085 MapKey Lookup(Ty, V);
1086 typename MapTy::iterator I = Map.find(Lookup);
1087 // Is it in the map?
1089 return static_cast<ConstantClass *>(I->second);
1091 // If no preexisting value, create one now...
1092 ConstantClass *Result =
1093 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1095 /// FIXME: why does this assert fail when loading 176.gcc?
1096 //assert(Result->getType() == Ty && "Type specified is not correct!");
1097 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1099 if (HasLargeKey) // Remember the reverse mapping if needed.
1100 InverseMap.insert(std::make_pair(Result, I));
1102 // If the type of the constant is abstract, make sure that an entry exists
1103 // for it in the AbstractTypeMap.
1104 if (Ty->isAbstract()) {
1105 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
1107 if (TI == AbstractTypeMap.end()) {
1108 // Add ourselves to the ATU list of the type.
1109 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1111 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1117 void remove(ConstantClass *CP) {
1118 typename MapTy::iterator I = FindExistingElement(CP);
1119 assert(I != Map.end() && "Constant not found in constant table!");
1120 assert(I->second == CP && "Didn't find correct element?");
1122 if (HasLargeKey) // Remember the reverse mapping if needed.
1123 InverseMap.erase(CP);
1125 // Now that we found the entry, make sure this isn't the entry that
1126 // the AbstractTypeMap points to.
1127 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1128 if (Ty->isAbstract()) {
1129 assert(AbstractTypeMap.count(Ty) &&
1130 "Abstract type not in AbstractTypeMap?");
1131 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1132 if (ATMEntryIt == I) {
1133 // Yes, we are removing the representative entry for this type.
1134 // See if there are any other entries of the same type.
1135 typename MapTy::iterator TmpIt = ATMEntryIt;
1137 // First check the entry before this one...
1138 if (TmpIt != Map.begin()) {
1140 if (TmpIt->first.first != Ty) // Not the same type, move back...
1144 // If we didn't find the same type, try to move forward...
1145 if (TmpIt == ATMEntryIt) {
1147 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1148 --TmpIt; // No entry afterwards with the same type
1151 // If there is another entry in the map of the same abstract type,
1152 // update the AbstractTypeMap entry now.
1153 if (TmpIt != ATMEntryIt) {
1156 // Otherwise, we are removing the last instance of this type
1157 // from the table. Remove from the ATM, and from user list.
1158 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1159 AbstractTypeMap.erase(Ty);
1168 /// MoveConstantToNewSlot - If we are about to change C to be the element
1169 /// specified by I, update our internal data structures to reflect this
1171 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1172 // First, remove the old location of the specified constant in the map.
1173 typename MapTy::iterator OldI = FindExistingElement(C);
1174 assert(OldI != Map.end() && "Constant not found in constant table!");
1175 assert(OldI->second == C && "Didn't find correct element?");
1177 // If this constant is the representative element for its abstract type,
1178 // update the AbstractTypeMap so that the representative element is I.
1179 if (C->getType()->isAbstract()) {
1180 typename AbstractTypeMapTy::iterator ATI =
1181 AbstractTypeMap.find(C->getType());
1182 assert(ATI != AbstractTypeMap.end() &&
1183 "Abstract type not in AbstractTypeMap?");
1184 if (ATI->second == OldI)
1188 // Remove the old entry from the map.
1191 // Update the inverse map so that we know that this constant is now
1192 // located at descriptor I.
1194 assert(I->second == C && "Bad inversemap entry!");
1199 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1200 typename AbstractTypeMapTy::iterator I =
1201 AbstractTypeMap.find(cast<Type>(OldTy));
1203 assert(I != AbstractTypeMap.end() &&
1204 "Abstract type not in AbstractTypeMap?");
1206 // Convert a constant at a time until the last one is gone. The last one
1207 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1208 // eliminated eventually.
1210 ConvertConstantType<ConstantClass,
1211 TypeClass>::convert(
1212 static_cast<ConstantClass *>(I->second->second),
1213 cast<TypeClass>(NewTy));
1215 I = AbstractTypeMap.find(cast<Type>(OldTy));
1216 } while (I != AbstractTypeMap.end());
1219 // If the type became concrete without being refined to any other existing
1220 // type, we just remove ourselves from the ATU list.
1221 void typeBecameConcrete(const DerivedType *AbsTy) {
1222 AbsTy->removeAbstractTypeUser(this);
1226 DOUT << "Constant.cpp: ValueMap\n";
1233 //---- ConstantAggregateZero::get() implementation...
1236 // ConstantAggregateZero does not take extra "value" argument...
1237 template<class ValType>
1238 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1239 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1240 return new ConstantAggregateZero(Ty);
1245 struct ConvertConstantType<ConstantAggregateZero, Type> {
1246 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1247 // Make everyone now use a constant of the new type...
1248 Constant *New = ConstantAggregateZero::get(NewTy);
1249 assert(New != OldC && "Didn't replace constant??");
1250 OldC->uncheckedReplaceAllUsesWith(New);
1251 OldC->destroyConstant(); // This constant is now dead, destroy it.
1256 static ManagedStatic<ValueMap<char, Type,
1257 ConstantAggregateZero> > AggZeroConstants;
1259 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1261 Constant *ConstantAggregateZero::get(const Type *Ty) {
1262 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1263 "Cannot create an aggregate zero of non-aggregate type!");
1264 return AggZeroConstants->getOrCreate(Ty, 0);
1267 // destroyConstant - Remove the constant from the constant table...
1269 void ConstantAggregateZero::destroyConstant() {
1270 AggZeroConstants->remove(this);
1271 destroyConstantImpl();
1274 //---- ConstantArray::get() implementation...
1278 struct ConvertConstantType<ConstantArray, ArrayType> {
1279 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1280 // Make everyone now use a constant of the new type...
1281 std::vector<Constant*> C;
1282 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1283 C.push_back(cast<Constant>(OldC->getOperand(i)));
1284 Constant *New = ConstantArray::get(NewTy, C);
1285 assert(New != OldC && "Didn't replace constant??");
1286 OldC->uncheckedReplaceAllUsesWith(New);
1287 OldC->destroyConstant(); // This constant is now dead, destroy it.
1292 static std::vector<Constant*> getValType(ConstantArray *CA) {
1293 std::vector<Constant*> Elements;
1294 Elements.reserve(CA->getNumOperands());
1295 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1296 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1300 typedef ValueMap<std::vector<Constant*>, ArrayType,
1301 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1302 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1304 Constant *ConstantArray::get(const ArrayType *Ty,
1305 const std::vector<Constant*> &V) {
1306 // If this is an all-zero array, return a ConstantAggregateZero object
1309 if (!C->isNullValue())
1310 return ArrayConstants->getOrCreate(Ty, V);
1311 for (unsigned i = 1, e = V.size(); i != e; ++i)
1313 return ArrayConstants->getOrCreate(Ty, V);
1315 return ConstantAggregateZero::get(Ty);
1318 // destroyConstant - Remove the constant from the constant table...
1320 void ConstantArray::destroyConstant() {
1321 ArrayConstants->remove(this);
1322 destroyConstantImpl();
1325 /// ConstantArray::get(const string&) - Return an array that is initialized to
1326 /// contain the specified string. If length is zero then a null terminator is
1327 /// added to the specified string so that it may be used in a natural way.
1328 /// Otherwise, the length parameter specifies how much of the string to use
1329 /// and it won't be null terminated.
1331 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1332 std::vector<Constant*> ElementVals;
1333 for (unsigned i = 0; i < Str.length(); ++i)
1334 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1336 // Add a null terminator to the string...
1338 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1341 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1342 return ConstantArray::get(ATy, ElementVals);
1345 /// isString - This method returns true if the array is an array of i8, and
1346 /// if the elements of the array are all ConstantInt's.
1347 bool ConstantArray::isString() const {
1348 // Check the element type for i8...
1349 if (getType()->getElementType() != Type::Int8Ty)
1351 // Check the elements to make sure they are all integers, not constant
1353 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1354 if (!isa<ConstantInt>(getOperand(i)))
1359 /// isCString - This method returns true if the array is a string (see
1360 /// isString) and it ends in a null byte \0 and does not contains any other
1361 /// null bytes except its terminator.
1362 bool ConstantArray::isCString() const {
1363 // Check the element type for i8...
1364 if (getType()->getElementType() != Type::Int8Ty)
1366 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1367 // Last element must be a null.
1368 if (getOperand(getNumOperands()-1) != Zero)
1370 // Other elements must be non-null integers.
1371 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1372 if (!isa<ConstantInt>(getOperand(i)))
1374 if (getOperand(i) == Zero)
1381 // getAsString - If the sub-element type of this array is i8
1382 // then this method converts the array to an std::string and returns it.
1383 // Otherwise, it asserts out.
1385 std::string ConstantArray::getAsString() const {
1386 assert(isString() && "Not a string!");
1388 Result.reserve(getNumOperands());
1389 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1390 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1395 //---- ConstantStruct::get() implementation...
1400 struct ConvertConstantType<ConstantStruct, StructType> {
1401 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1402 // Make everyone now use a constant of the new type...
1403 std::vector<Constant*> C;
1404 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1405 C.push_back(cast<Constant>(OldC->getOperand(i)));
1406 Constant *New = ConstantStruct::get(NewTy, C);
1407 assert(New != OldC && "Didn't replace constant??");
1409 OldC->uncheckedReplaceAllUsesWith(New);
1410 OldC->destroyConstant(); // This constant is now dead, destroy it.
1415 typedef ValueMap<std::vector<Constant*>, StructType,
1416 ConstantStruct, true /*largekey*/> StructConstantsTy;
1417 static ManagedStatic<StructConstantsTy> StructConstants;
1419 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1420 std::vector<Constant*> Elements;
1421 Elements.reserve(CS->getNumOperands());
1422 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1423 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1427 Constant *ConstantStruct::get(const StructType *Ty,
1428 const std::vector<Constant*> &V) {
1429 // Create a ConstantAggregateZero value if all elements are zeros...
1430 for (unsigned i = 0, e = V.size(); i != e; ++i)
1431 if (!V[i]->isNullValue())
1432 return StructConstants->getOrCreate(Ty, V);
1434 return ConstantAggregateZero::get(Ty);
1437 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1438 std::vector<const Type*> StructEls;
1439 StructEls.reserve(V.size());
1440 for (unsigned i = 0, e = V.size(); i != e; ++i)
1441 StructEls.push_back(V[i]->getType());
1442 return get(StructType::get(StructEls, packed), V);
1445 // destroyConstant - Remove the constant from the constant table...
1447 void ConstantStruct::destroyConstant() {
1448 StructConstants->remove(this);
1449 destroyConstantImpl();
1452 //---- ConstantVector::get() implementation...
1456 struct ConvertConstantType<ConstantVector, VectorType> {
1457 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1458 // Make everyone now use a constant of the new type...
1459 std::vector<Constant*> C;
1460 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1461 C.push_back(cast<Constant>(OldC->getOperand(i)));
1462 Constant *New = ConstantVector::get(NewTy, C);
1463 assert(New != OldC && "Didn't replace constant??");
1464 OldC->uncheckedReplaceAllUsesWith(New);
1465 OldC->destroyConstant(); // This constant is now dead, destroy it.
1470 static std::vector<Constant*> getValType(ConstantVector *CP) {
1471 std::vector<Constant*> Elements;
1472 Elements.reserve(CP->getNumOperands());
1473 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1474 Elements.push_back(CP->getOperand(i));
1478 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1479 ConstantVector> > VectorConstants;
1481 Constant *ConstantVector::get(const VectorType *Ty,
1482 const std::vector<Constant*> &V) {
1483 assert(!V.empty() && "Vectors can't be empty");
1484 // If this is an all-undef or alll-zero vector, return a
1485 // ConstantAggregateZero or UndefValue.
1487 bool isZero = C->isNullValue();
1488 bool isUndef = isa<UndefValue>(C);
1490 if (isZero || isUndef) {
1491 for (unsigned i = 1, e = V.size(); i != e; ++i)
1493 isZero = isUndef = false;
1499 return ConstantAggregateZero::get(Ty);
1501 return UndefValue::get(Ty);
1502 return VectorConstants->getOrCreate(Ty, V);
1505 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1506 assert(!V.empty() && "Cannot infer type if V is empty");
1507 return get(VectorType::get(V.front()->getType(),V.size()), V);
1510 // destroyConstant - Remove the constant from the constant table...
1512 void ConstantVector::destroyConstant() {
1513 VectorConstants->remove(this);
1514 destroyConstantImpl();
1517 /// This function will return true iff every element in this vector constant
1518 /// is set to all ones.
1519 /// @returns true iff this constant's emements are all set to all ones.
1520 /// @brief Determine if the value is all ones.
1521 bool ConstantVector::isAllOnesValue() const {
1522 // Check out first element.
1523 const Constant *Elt = getOperand(0);
1524 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1525 if (!CI || !CI->isAllOnesValue()) return false;
1526 // Then make sure all remaining elements point to the same value.
1527 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1528 if (getOperand(I) != Elt) return false;
1533 /// getSplatValue - If this is a splat constant, where all of the
1534 /// elements have the same value, return that value. Otherwise return null.
1535 Constant *ConstantVector::getSplatValue() {
1536 // Check out first element.
1537 Constant *Elt = getOperand(0);
1538 // Then make sure all remaining elements point to the same value.
1539 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1540 if (getOperand(I) != Elt) return 0;
1544 //---- ConstantPointerNull::get() implementation...
1548 // ConstantPointerNull does not take extra "value" argument...
1549 template<class ValType>
1550 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1551 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1552 return new ConstantPointerNull(Ty);
1557 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1558 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1559 // Make everyone now use a constant of the new type...
1560 Constant *New = ConstantPointerNull::get(NewTy);
1561 assert(New != OldC && "Didn't replace constant??");
1562 OldC->uncheckedReplaceAllUsesWith(New);
1563 OldC->destroyConstant(); // This constant is now dead, destroy it.
1568 static ManagedStatic<ValueMap<char, PointerType,
1569 ConstantPointerNull> > NullPtrConstants;
1571 static char getValType(ConstantPointerNull *) {
1576 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1577 return NullPtrConstants->getOrCreate(Ty, 0);
1580 // destroyConstant - Remove the constant from the constant table...
1582 void ConstantPointerNull::destroyConstant() {
1583 NullPtrConstants->remove(this);
1584 destroyConstantImpl();
1588 //---- UndefValue::get() implementation...
1592 // UndefValue does not take extra "value" argument...
1593 template<class ValType>
1594 struct ConstantCreator<UndefValue, Type, ValType> {
1595 static UndefValue *create(const Type *Ty, const ValType &V) {
1596 return new UndefValue(Ty);
1601 struct ConvertConstantType<UndefValue, Type> {
1602 static void convert(UndefValue *OldC, const Type *NewTy) {
1603 // Make everyone now use a constant of the new type.
1604 Constant *New = UndefValue::get(NewTy);
1605 assert(New != OldC && "Didn't replace constant??");
1606 OldC->uncheckedReplaceAllUsesWith(New);
1607 OldC->destroyConstant(); // This constant is now dead, destroy it.
1612 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1614 static char getValType(UndefValue *) {
1619 UndefValue *UndefValue::get(const Type *Ty) {
1620 return UndefValueConstants->getOrCreate(Ty, 0);
1623 // destroyConstant - Remove the constant from the constant table.
1625 void UndefValue::destroyConstant() {
1626 UndefValueConstants->remove(this);
1627 destroyConstantImpl();
1631 //---- ConstantExpr::get() implementations...
1636 struct ExprMapKeyType {
1637 typedef SmallVector<unsigned, 4> IndexList;
1639 ExprMapKeyType(unsigned opc,
1640 const std::vector<Constant*> &ops,
1641 unsigned short pred = 0,
1642 const IndexList &inds = IndexList())
1643 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1646 std::vector<Constant*> operands;
1648 bool operator==(const ExprMapKeyType& that) const {
1649 return this->opcode == that.opcode &&
1650 this->predicate == that.predicate &&
1651 this->operands == that.operands;
1652 this->indices == that.indices;
1654 bool operator<(const ExprMapKeyType & that) const {
1655 return this->opcode < that.opcode ||
1656 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1657 (this->opcode == that.opcode && this->predicate == that.predicate &&
1658 this->operands < that.operands) ||
1659 (this->opcode == that.opcode && this->predicate == that.predicate &&
1660 this->operands == that.operands && this->indices < that.indices);
1663 bool operator!=(const ExprMapKeyType& that) const {
1664 return !(*this == that);
1672 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1673 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1674 unsigned short pred = 0) {
1675 if (Instruction::isCast(V.opcode))
1676 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1677 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1678 V.opcode < Instruction::BinaryOpsEnd))
1679 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1680 if (V.opcode == Instruction::Select)
1681 return new SelectConstantExpr(V.operands[0], V.operands[1],
1683 if (V.opcode == Instruction::ExtractElement)
1684 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1685 if (V.opcode == Instruction::InsertElement)
1686 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1688 if (V.opcode == Instruction::ShuffleVector)
1689 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1691 if (V.opcode == Instruction::InsertValue)
1692 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1694 if (V.opcode == Instruction::ExtractValue)
1695 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1696 if (V.opcode == Instruction::GetElementPtr) {
1697 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1698 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1701 // The compare instructions are weird. We have to encode the predicate
1702 // value and it is combined with the instruction opcode by multiplying
1703 // the opcode by one hundred. We must decode this to get the predicate.
1704 if (V.opcode == Instruction::ICmp)
1705 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1706 V.operands[0], V.operands[1]);
1707 if (V.opcode == Instruction::FCmp)
1708 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1709 V.operands[0], V.operands[1]);
1710 if (V.opcode == Instruction::VICmp)
1711 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1712 V.operands[0], V.operands[1]);
1713 if (V.opcode == Instruction::VFCmp)
1714 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1715 V.operands[0], V.operands[1]);
1716 assert(0 && "Invalid ConstantExpr!");
1722 struct ConvertConstantType<ConstantExpr, Type> {
1723 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1725 switch (OldC->getOpcode()) {
1726 case Instruction::Trunc:
1727 case Instruction::ZExt:
1728 case Instruction::SExt:
1729 case Instruction::FPTrunc:
1730 case Instruction::FPExt:
1731 case Instruction::UIToFP:
1732 case Instruction::SIToFP:
1733 case Instruction::FPToUI:
1734 case Instruction::FPToSI:
1735 case Instruction::PtrToInt:
1736 case Instruction::IntToPtr:
1737 case Instruction::BitCast:
1738 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1741 case Instruction::Select:
1742 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1743 OldC->getOperand(1),
1744 OldC->getOperand(2));
1747 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1748 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1749 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1750 OldC->getOperand(1));
1752 case Instruction::GetElementPtr:
1753 // Make everyone now use a constant of the new type...
1754 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1755 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1756 &Idx[0], Idx.size());
1760 assert(New != OldC && "Didn't replace constant??");
1761 OldC->uncheckedReplaceAllUsesWith(New);
1762 OldC->destroyConstant(); // This constant is now dead, destroy it.
1765 } // end namespace llvm
1768 static ExprMapKeyType getValType(ConstantExpr *CE) {
1769 std::vector<Constant*> Operands;
1770 Operands.reserve(CE->getNumOperands());
1771 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1772 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1773 return ExprMapKeyType(CE->getOpcode(), Operands,
1774 CE->isCompare() ? CE->getPredicate() : 0,
1776 CE->getIndices() : SmallVector<unsigned, 4>());
1779 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1780 ConstantExpr> > ExprConstants;
1782 /// This is a utility function to handle folding of casts and lookup of the
1783 /// cast in the ExprConstants map. It is used by the various get* methods below.
1784 static inline Constant *getFoldedCast(
1785 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1786 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1787 // Fold a few common cases
1788 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1791 // Look up the constant in the table first to ensure uniqueness
1792 std::vector<Constant*> argVec(1, C);
1793 ExprMapKeyType Key(opc, argVec);
1794 return ExprConstants->getOrCreate(Ty, Key);
1797 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1798 Instruction::CastOps opc = Instruction::CastOps(oc);
1799 assert(Instruction::isCast(opc) && "opcode out of range");
1800 assert(C && Ty && "Null arguments to getCast");
1801 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1805 assert(0 && "Invalid cast opcode");
1807 case Instruction::Trunc: return getTrunc(C, Ty);
1808 case Instruction::ZExt: return getZExt(C, Ty);
1809 case Instruction::SExt: return getSExt(C, Ty);
1810 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1811 case Instruction::FPExt: return getFPExtend(C, Ty);
1812 case Instruction::UIToFP: return getUIToFP(C, Ty);
1813 case Instruction::SIToFP: return getSIToFP(C, Ty);
1814 case Instruction::FPToUI: return getFPToUI(C, Ty);
1815 case Instruction::FPToSI: return getFPToSI(C, Ty);
1816 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1817 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1818 case Instruction::BitCast: return getBitCast(C, Ty);
1823 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1824 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1825 return getCast(Instruction::BitCast, C, Ty);
1826 return getCast(Instruction::ZExt, C, Ty);
1829 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1830 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1831 return getCast(Instruction::BitCast, C, Ty);
1832 return getCast(Instruction::SExt, C, Ty);
1835 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1836 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1837 return getCast(Instruction::BitCast, C, Ty);
1838 return getCast(Instruction::Trunc, C, Ty);
1841 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1842 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1843 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1845 if (Ty->isInteger())
1846 return getCast(Instruction::PtrToInt, S, Ty);
1847 return getCast(Instruction::BitCast, S, Ty);
1850 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1852 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1853 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1854 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1855 Instruction::CastOps opcode =
1856 (SrcBits == DstBits ? Instruction::BitCast :
1857 (SrcBits > DstBits ? Instruction::Trunc :
1858 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1859 return getCast(opcode, C, Ty);
1862 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1863 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1865 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1866 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1867 if (SrcBits == DstBits)
1868 return C; // Avoid a useless cast
1869 Instruction::CastOps opcode =
1870 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1871 return getCast(opcode, C, Ty);
1874 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1875 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1876 assert(Ty->isInteger() && "Trunc produces only integral");
1877 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1878 "SrcTy must be larger than DestTy for Trunc!");
1880 return getFoldedCast(Instruction::Trunc, C, Ty);
1883 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1884 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1885 assert(Ty->isInteger() && "SExt produces only integer");
1886 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1887 "SrcTy must be smaller than DestTy for SExt!");
1889 return getFoldedCast(Instruction::SExt, C, Ty);
1892 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1893 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1894 assert(Ty->isInteger() && "ZExt produces only integer");
1895 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1896 "SrcTy must be smaller than DestTy for ZExt!");
1898 return getFoldedCast(Instruction::ZExt, C, Ty);
1901 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1902 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1903 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1904 "This is an illegal floating point truncation!");
1905 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1908 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1909 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1910 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1911 "This is an illegal floating point extension!");
1912 return getFoldedCast(Instruction::FPExt, C, Ty);
1915 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1916 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1917 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1918 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1919 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1920 "This is an illegal uint to floating point cast!");
1921 return getFoldedCast(Instruction::UIToFP, C, Ty);
1924 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1925 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1926 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1927 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1928 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1929 "This is an illegal sint to floating point cast!");
1930 return getFoldedCast(Instruction::SIToFP, C, Ty);
1933 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1934 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1935 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1936 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1937 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1938 "This is an illegal floating point to uint cast!");
1939 return getFoldedCast(Instruction::FPToUI, C, Ty);
1942 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1943 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1944 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1945 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1946 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1947 "This is an illegal floating point to sint cast!");
1948 return getFoldedCast(Instruction::FPToSI, C, Ty);
1951 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1952 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1953 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1954 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1957 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1958 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1959 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1960 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1963 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1964 // BitCast implies a no-op cast of type only. No bits change. However, you
1965 // can't cast pointers to anything but pointers.
1966 const Type *SrcTy = C->getType();
1967 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1968 "BitCast cannot cast pointer to non-pointer and vice versa");
1970 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1971 // or nonptr->ptr). For all the other types, the cast is okay if source and
1972 // destination bit widths are identical.
1973 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1974 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1975 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1976 return getFoldedCast(Instruction::BitCast, C, DstTy);
1979 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
1980 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1981 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
1983 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1984 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
1987 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1988 Constant *C1, Constant *C2) {
1989 // Check the operands for consistency first
1990 assert(Opcode >= Instruction::BinaryOpsBegin &&
1991 Opcode < Instruction::BinaryOpsEnd &&
1992 "Invalid opcode in binary constant expression");
1993 assert(C1->getType() == C2->getType() &&
1994 "Operand types in binary constant expression should match");
1996 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1997 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1998 return FC; // Fold a few common cases...
2000 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2001 ExprMapKeyType Key(Opcode, argVec);
2002 return ExprConstants->getOrCreate(ReqTy, Key);
2005 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2006 Constant *C1, Constant *C2,
2008 switch (predicate) {
2009 default: assert(0 && "Invalid CmpInst predicate");
2010 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2011 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2012 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2013 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2014 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2015 case CmpInst::FCMP_TRUE:
2016 return isVecCmp ? getVFCmp(predicate, C1, C2)
2017 : getFCmp(predicate, C1, C2);
2018 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2019 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2020 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2021 case CmpInst::ICMP_SLE:
2022 return isVecCmp ? getVICmp(predicate, C1, C2)
2023 : getICmp(predicate, C1, C2);
2027 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2030 case Instruction::Add:
2031 case Instruction::Sub:
2032 case Instruction::Mul:
2033 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2034 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
2035 isa<VectorType>(C1->getType())) &&
2036 "Tried to create an arithmetic operation on a non-arithmetic type!");
2038 case Instruction::UDiv:
2039 case Instruction::SDiv:
2040 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2041 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2042 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2043 "Tried to create an arithmetic operation on a non-arithmetic type!");
2045 case Instruction::FDiv:
2046 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2047 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2048 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2049 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2051 case Instruction::URem:
2052 case Instruction::SRem:
2053 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2054 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2055 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2056 "Tried to create an arithmetic operation on a non-arithmetic type!");
2058 case Instruction::FRem:
2059 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2060 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2061 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2062 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2064 case Instruction::And:
2065 case Instruction::Or:
2066 case Instruction::Xor:
2067 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2068 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
2069 "Tried to create a logical operation on a non-integral type!");
2071 case Instruction::Shl:
2072 case Instruction::LShr:
2073 case Instruction::AShr:
2074 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2075 assert(C1->getType()->isInteger() &&
2076 "Tried to create a shift operation on a non-integer type!");
2083 return getTy(C1->getType(), Opcode, C1, C2);
2086 Constant *ConstantExpr::getCompare(unsigned short pred,
2087 Constant *C1, Constant *C2) {
2088 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2089 return getCompareTy(pred, C1, C2);
2092 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2093 Constant *V1, Constant *V2) {
2094 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
2095 assert(V1->getType() == V2->getType() && "Select value types must match!");
2096 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
2098 if (ReqTy == V1->getType())
2099 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2100 return SC; // Fold common cases
2102 std::vector<Constant*> argVec(3, C);
2105 ExprMapKeyType Key(Instruction::Select, argVec);
2106 return ExprConstants->getOrCreate(ReqTy, Key);
2109 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2112 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2114 cast<PointerType>(ReqTy)->getElementType() &&
2115 "GEP indices invalid!");
2117 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2118 return FC; // Fold a few common cases...
2120 assert(isa<PointerType>(C->getType()) &&
2121 "Non-pointer type for constant GetElementPtr expression");
2122 // Look up the constant in the table first to ensure uniqueness
2123 std::vector<Constant*> ArgVec;
2124 ArgVec.reserve(NumIdx+1);
2125 ArgVec.push_back(C);
2126 for (unsigned i = 0; i != NumIdx; ++i)
2127 ArgVec.push_back(cast<Constant>(Idxs[i]));
2128 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2129 return ExprConstants->getOrCreate(ReqTy, Key);
2132 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2134 // Get the result type of the getelementptr!
2136 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2137 assert(Ty && "GEP indices invalid!");
2138 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2139 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2142 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2144 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2149 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2150 assert(LHS->getType() == RHS->getType());
2151 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2152 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2154 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2155 return FC; // Fold a few common cases...
2157 // Look up the constant in the table first to ensure uniqueness
2158 std::vector<Constant*> ArgVec;
2159 ArgVec.push_back(LHS);
2160 ArgVec.push_back(RHS);
2161 // Get the key type with both the opcode and predicate
2162 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2163 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2167 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2168 assert(LHS->getType() == RHS->getType());
2169 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2171 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2172 return FC; // Fold a few common cases...
2174 // Look up the constant in the table first to ensure uniqueness
2175 std::vector<Constant*> ArgVec;
2176 ArgVec.push_back(LHS);
2177 ArgVec.push_back(RHS);
2178 // Get the key type with both the opcode and predicate
2179 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2180 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2184 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2185 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
2186 "Tried to create vicmp operation on non-vector type!");
2187 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2188 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2190 const VectorType *VTy = cast<VectorType>(LHS->getType());
2191 const Type *EltTy = VTy->getElementType();
2192 unsigned NumElts = VTy->getNumElements();
2194 // See if we can fold the element-wise comparison of the LHS and RHS.
2195 SmallVector<Constant *, 16> LHSElts, RHSElts;
2196 LHS->getVectorElements(LHSElts);
2197 RHS->getVectorElements(RHSElts);
2199 if (!LHSElts.empty() && !RHSElts.empty()) {
2200 SmallVector<Constant *, 16> Elts;
2201 for (unsigned i = 0; i != NumElts; ++i) {
2202 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2204 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2205 if (FCI->getZExtValue())
2206 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2208 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2209 } else if (FC && isa<UndefValue>(FC)) {
2210 Elts.push_back(UndefValue::get(EltTy));
2215 if (Elts.size() == NumElts)
2216 return ConstantVector::get(&Elts[0], Elts.size());
2219 // Look up the constant in the table first to ensure uniqueness
2220 std::vector<Constant*> ArgVec;
2221 ArgVec.push_back(LHS);
2222 ArgVec.push_back(RHS);
2223 // Get the key type with both the opcode and predicate
2224 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2225 return ExprConstants->getOrCreate(LHS->getType(), Key);
2229 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2230 assert(isa<VectorType>(LHS->getType()) &&
2231 "Tried to create vfcmp operation on non-vector type!");
2232 assert(LHS->getType() == RHS->getType());
2233 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2235 const VectorType *VTy = cast<VectorType>(LHS->getType());
2236 unsigned NumElts = VTy->getNumElements();
2237 const Type *EltTy = VTy->getElementType();
2238 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2239 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2241 // See if we can fold the element-wise comparison of the LHS and RHS.
2242 SmallVector<Constant *, 16> LHSElts, RHSElts;
2243 LHS->getVectorElements(LHSElts);
2244 RHS->getVectorElements(RHSElts);
2246 if (!LHSElts.empty() && !RHSElts.empty()) {
2247 SmallVector<Constant *, 16> Elts;
2248 for (unsigned i = 0; i != NumElts; ++i) {
2249 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2251 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2252 if (FCI->getZExtValue())
2253 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2255 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2256 } else if (FC && isa<UndefValue>(FC)) {
2257 Elts.push_back(UndefValue::get(REltTy));
2262 if (Elts.size() == NumElts)
2263 return ConstantVector::get(&Elts[0], Elts.size());
2266 // Look up the constant in the table first to ensure uniqueness
2267 std::vector<Constant*> ArgVec;
2268 ArgVec.push_back(LHS);
2269 ArgVec.push_back(RHS);
2270 // Get the key type with both the opcode and predicate
2271 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2272 return ExprConstants->getOrCreate(ResultTy, Key);
2275 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2277 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2278 return FC; // Fold a few common cases...
2279 // Look up the constant in the table first to ensure uniqueness
2280 std::vector<Constant*> ArgVec(1, Val);
2281 ArgVec.push_back(Idx);
2282 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2283 return ExprConstants->getOrCreate(ReqTy, Key);
2286 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2287 assert(isa<VectorType>(Val->getType()) &&
2288 "Tried to create extractelement operation on non-vector type!");
2289 assert(Idx->getType() == Type::Int32Ty &&
2290 "Extractelement index must be i32 type!");
2291 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2295 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2296 Constant *Elt, Constant *Idx) {
2297 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2298 return FC; // Fold a few common cases...
2299 // Look up the constant in the table first to ensure uniqueness
2300 std::vector<Constant*> ArgVec(1, Val);
2301 ArgVec.push_back(Elt);
2302 ArgVec.push_back(Idx);
2303 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2304 return ExprConstants->getOrCreate(ReqTy, Key);
2307 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2309 assert(isa<VectorType>(Val->getType()) &&
2310 "Tried to create insertelement operation on non-vector type!");
2311 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2312 && "Insertelement types must match!");
2313 assert(Idx->getType() == Type::Int32Ty &&
2314 "Insertelement index must be i32 type!");
2315 return getInsertElementTy(cast<VectorType>(Val->getType())->getElementType(),
2319 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2320 Constant *V2, Constant *Mask) {
2321 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2322 return FC; // Fold a few common cases...
2323 // Look up the constant in the table first to ensure uniqueness
2324 std::vector<Constant*> ArgVec(1, V1);
2325 ArgVec.push_back(V2);
2326 ArgVec.push_back(Mask);
2327 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2328 return ExprConstants->getOrCreate(ReqTy, Key);
2331 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2333 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2334 "Invalid shuffle vector constant expr operands!");
2335 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2338 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2340 const unsigned *Idxs, unsigned NumIdx) {
2341 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2342 Idxs+NumIdx) == Val->getType() &&
2343 "insertvalue indices invalid!");
2344 assert(Agg->getType() == ReqTy &&
2345 "insertvalue type invalid!");
2346 assert(Agg->getType()->isFirstClassType() &&
2347 "Non-first-class type for constant InsertValue expression");
2348 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2349 assert(FC && "InsertValue constant expr couldn't be folded!");
2353 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2354 const unsigned *IdxList, unsigned NumIdx) {
2355 assert(Agg->getType()->isFirstClassType() &&
2356 "Tried to create insertelement operation on non-first-class type!");
2358 const Type *ReqTy = Agg->getType();
2360 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2361 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2362 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2365 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2366 const unsigned *Idxs, unsigned NumIdx) {
2367 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2368 Idxs+NumIdx) == ReqTy &&
2369 "extractvalue indices invalid!");
2370 assert(Agg->getType()->isFirstClassType() &&
2371 "Non-first-class type for constant extractvalue expression");
2372 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2373 assert(FC && "ExtractValue constant expr couldn't be folded!");
2377 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2378 const unsigned *IdxList, unsigned NumIdx) {
2379 assert(Agg->getType()->isFirstClassType() &&
2380 "Tried to create extractelement operation on non-first-class type!");
2383 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2384 assert(ReqTy && "extractvalue indices invalid!");
2385 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2388 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2389 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2390 if (PTy->getElementType()->isFloatingPoint()) {
2391 std::vector<Constant*> zeros(PTy->getNumElements(),
2392 ConstantFP::getNegativeZero(PTy->getElementType()));
2393 return ConstantVector::get(PTy, zeros);
2396 if (Ty->isFloatingPoint())
2397 return ConstantFP::getNegativeZero(Ty);
2399 return Constant::getNullValue(Ty);
2402 // destroyConstant - Remove the constant from the constant table...
2404 void ConstantExpr::destroyConstant() {
2405 ExprConstants->remove(this);
2406 destroyConstantImpl();
2409 const char *ConstantExpr::getOpcodeName() const {
2410 return Instruction::getOpcodeName(getOpcode());
2413 //===----------------------------------------------------------------------===//
2414 // replaceUsesOfWithOnConstant implementations
2416 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2417 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2420 /// Note that we intentionally replace all uses of From with To here. Consider
2421 /// a large array that uses 'From' 1000 times. By handling this case all here,
2422 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2423 /// single invocation handles all 1000 uses. Handling them one at a time would
2424 /// work, but would be really slow because it would have to unique each updated
2426 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2428 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2429 Constant *ToC = cast<Constant>(To);
2431 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2432 Lookup.first.first = getType();
2433 Lookup.second = this;
2435 std::vector<Constant*> &Values = Lookup.first.second;
2436 Values.reserve(getNumOperands()); // Build replacement array.
2438 // Fill values with the modified operands of the constant array. Also,
2439 // compute whether this turns into an all-zeros array.
2440 bool isAllZeros = false;
2441 unsigned NumUpdated = 0;
2442 if (!ToC->isNullValue()) {
2443 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2444 Constant *Val = cast<Constant>(O->get());
2449 Values.push_back(Val);
2453 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2454 Constant *Val = cast<Constant>(O->get());
2459 Values.push_back(Val);
2460 if (isAllZeros) isAllZeros = Val->isNullValue();
2464 Constant *Replacement = 0;
2466 Replacement = ConstantAggregateZero::get(getType());
2468 // Check to see if we have this array type already.
2470 ArrayConstantsTy::MapTy::iterator I =
2471 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2474 Replacement = I->second;
2476 // Okay, the new shape doesn't exist in the system yet. Instead of
2477 // creating a new constant array, inserting it, replaceallusesof'ing the
2478 // old with the new, then deleting the old... just update the current one
2480 ArrayConstants->MoveConstantToNewSlot(this, I);
2482 // Update to the new value. Optimize for the case when we have a single
2483 // operand that we're changing, but handle bulk updates efficiently.
2484 if (NumUpdated == 1) {
2485 unsigned OperandToUpdate = U-OperandList;
2486 assert(getOperand(OperandToUpdate) == From &&
2487 "ReplaceAllUsesWith broken!");
2488 setOperand(OperandToUpdate, ToC);
2490 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2491 if (getOperand(i) == From)
2498 // Otherwise, I do need to replace this with an existing value.
2499 assert(Replacement != this && "I didn't contain From!");
2501 // Everyone using this now uses the replacement.
2502 uncheckedReplaceAllUsesWith(Replacement);
2504 // Delete the old constant!
2508 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2510 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2511 Constant *ToC = cast<Constant>(To);
2513 unsigned OperandToUpdate = U-OperandList;
2514 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2516 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2517 Lookup.first.first = getType();
2518 Lookup.second = this;
2519 std::vector<Constant*> &Values = Lookup.first.second;
2520 Values.reserve(getNumOperands()); // Build replacement struct.
2523 // Fill values with the modified operands of the constant struct. Also,
2524 // compute whether this turns into an all-zeros struct.
2525 bool isAllZeros = false;
2526 if (!ToC->isNullValue()) {
2527 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2528 Values.push_back(cast<Constant>(O->get()));
2531 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2532 Constant *Val = cast<Constant>(O->get());
2533 Values.push_back(Val);
2534 if (isAllZeros) isAllZeros = Val->isNullValue();
2537 Values[OperandToUpdate] = ToC;
2539 Constant *Replacement = 0;
2541 Replacement = ConstantAggregateZero::get(getType());
2543 // Check to see if we have this array type already.
2545 StructConstantsTy::MapTy::iterator I =
2546 StructConstants->InsertOrGetItem(Lookup, Exists);
2549 Replacement = I->second;
2551 // Okay, the new shape doesn't exist in the system yet. Instead of
2552 // creating a new constant struct, inserting it, replaceallusesof'ing the
2553 // old with the new, then deleting the old... just update the current one
2555 StructConstants->MoveConstantToNewSlot(this, I);
2557 // Update to the new value.
2558 setOperand(OperandToUpdate, ToC);
2563 assert(Replacement != this && "I didn't contain From!");
2565 // Everyone using this now uses the replacement.
2566 uncheckedReplaceAllUsesWith(Replacement);
2568 // Delete the old constant!
2572 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2574 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2576 std::vector<Constant*> Values;
2577 Values.reserve(getNumOperands()); // Build replacement array...
2578 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2579 Constant *Val = getOperand(i);
2580 if (Val == From) Val = cast<Constant>(To);
2581 Values.push_back(Val);
2584 Constant *Replacement = ConstantVector::get(getType(), Values);
2585 assert(Replacement != this && "I didn't contain From!");
2587 // Everyone using this now uses the replacement.
2588 uncheckedReplaceAllUsesWith(Replacement);
2590 // Delete the old constant!
2594 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2596 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2597 Constant *To = cast<Constant>(ToV);
2599 Constant *Replacement = 0;
2600 if (getOpcode() == Instruction::GetElementPtr) {
2601 SmallVector<Constant*, 8> Indices;
2602 Constant *Pointer = getOperand(0);
2603 Indices.reserve(getNumOperands()-1);
2604 if (Pointer == From) Pointer = To;
2606 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2607 Constant *Val = getOperand(i);
2608 if (Val == From) Val = To;
2609 Indices.push_back(Val);
2611 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2612 &Indices[0], Indices.size());
2613 } else if (getOpcode() == Instruction::ExtractValue) {
2614 Constant *Agg = getOperand(0);
2615 if (Agg == From) Agg = To;
2617 const SmallVector<unsigned, 4> &Indices = getIndices();
2618 Replacement = ConstantExpr::getExtractValue(Agg,
2619 &Indices[0], Indices.size());
2620 } else if (getOpcode() == Instruction::InsertValue) {
2621 Constant *Agg = getOperand(0);
2622 Constant *Val = getOperand(1);
2623 if (Agg == From) Agg = To;
2624 if (Val == From) Val = To;
2626 const SmallVector<unsigned, 4> &Indices = getIndices();
2627 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2628 &Indices[0], Indices.size());
2629 } else if (isCast()) {
2630 assert(getOperand(0) == From && "Cast only has one use!");
2631 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2632 } else if (getOpcode() == Instruction::Select) {
2633 Constant *C1 = getOperand(0);
2634 Constant *C2 = getOperand(1);
2635 Constant *C3 = getOperand(2);
2636 if (C1 == From) C1 = To;
2637 if (C2 == From) C2 = To;
2638 if (C3 == From) C3 = To;
2639 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2640 } else if (getOpcode() == Instruction::ExtractElement) {
2641 Constant *C1 = getOperand(0);
2642 Constant *C2 = getOperand(1);
2643 if (C1 == From) C1 = To;
2644 if (C2 == From) C2 = To;
2645 Replacement = ConstantExpr::getExtractElement(C1, C2);
2646 } else if (getOpcode() == Instruction::InsertElement) {
2647 Constant *C1 = getOperand(0);
2648 Constant *C2 = getOperand(1);
2649 Constant *C3 = getOperand(1);
2650 if (C1 == From) C1 = To;
2651 if (C2 == From) C2 = To;
2652 if (C3 == From) C3 = To;
2653 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2654 } else if (getOpcode() == Instruction::ShuffleVector) {
2655 Constant *C1 = getOperand(0);
2656 Constant *C2 = getOperand(1);
2657 Constant *C3 = getOperand(2);
2658 if (C1 == From) C1 = To;
2659 if (C2 == From) C2 = To;
2660 if (C3 == From) C3 = To;
2661 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2662 } else if (isCompare()) {
2663 Constant *C1 = getOperand(0);
2664 Constant *C2 = getOperand(1);
2665 if (C1 == From) C1 = To;
2666 if (C2 == From) C2 = To;
2667 if (getOpcode() == Instruction::ICmp)
2668 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2669 else if (getOpcode() == Instruction::FCmp)
2670 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2671 else if (getOpcode() == Instruction::VICmp)
2672 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2674 assert(getOpcode() == Instruction::VFCmp);
2675 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
2677 } else if (getNumOperands() == 2) {
2678 Constant *C1 = getOperand(0);
2679 Constant *C2 = getOperand(1);
2680 if (C1 == From) C1 = To;
2681 if (C2 == From) C2 = To;
2682 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2684 assert(0 && "Unknown ConstantExpr type!");
2688 assert(Replacement != this && "I didn't contain From!");
2690 // Everyone using this now uses the replacement.
2691 uncheckedReplaceAllUsesWith(Replacement);
2693 // Delete the old constant!