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) {
377 FV.convert(*TypeToFloatSemantics(Ty), APFloat::rmNearestTiesToEven, &ignored);
381 //===----------------------------------------------------------------------===//
382 // ConstantXXX Classes
383 //===----------------------------------------------------------------------===//
386 ConstantArray::ConstantArray(const ArrayType *T,
387 const std::vector<Constant*> &V)
388 : Constant(T, ConstantArrayVal,
389 OperandTraits<ConstantArray>::op_end(this) - V.size(),
391 assert(V.size() == T->getNumElements() &&
392 "Invalid initializer vector for constant array");
393 Use *OL = OperandList;
394 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
397 assert((C->getType() == T->getElementType() ||
399 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
400 "Initializer for array element doesn't match array element type!");
406 ConstantStruct::ConstantStruct(const StructType *T,
407 const std::vector<Constant*> &V)
408 : Constant(T, ConstantStructVal,
409 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
411 assert(V.size() == T->getNumElements() &&
412 "Invalid initializer vector for constant structure");
413 Use *OL = OperandList;
414 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
417 assert((C->getType() == T->getElementType(I-V.begin()) ||
418 ((T->getElementType(I-V.begin())->isAbstract() ||
419 C->getType()->isAbstract()) &&
420 T->getElementType(I-V.begin())->getTypeID() ==
421 C->getType()->getTypeID())) &&
422 "Initializer for struct element doesn't match struct element type!");
428 ConstantVector::ConstantVector(const VectorType *T,
429 const std::vector<Constant*> &V)
430 : Constant(T, ConstantVectorVal,
431 OperandTraits<ConstantVector>::op_end(this) - V.size(),
433 Use *OL = OperandList;
434 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
437 assert((C->getType() == T->getElementType() ||
439 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
440 "Initializer for vector element doesn't match vector element type!");
447 // We declare several classes private to this file, so use an anonymous
451 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
452 /// behind the scenes to implement unary constant exprs.
453 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
454 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
456 // allocate space for exactly one operand
457 void *operator new(size_t s) {
458 return User::operator new(s, 1);
460 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
461 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
464 /// Transparently provide more efficient getOperand methods.
465 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
468 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
469 /// behind the scenes to implement binary constant exprs.
470 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
471 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
473 // allocate space for exactly two operands
474 void *operator new(size_t s) {
475 return User::operator new(s, 2);
477 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
478 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
482 /// Transparently provide more efficient getOperand methods.
483 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
486 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
487 /// behind the scenes to implement select constant exprs.
488 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
489 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
491 // allocate space for exactly three operands
492 void *operator new(size_t s) {
493 return User::operator new(s, 3);
495 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
496 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
501 /// Transparently provide more efficient getOperand methods.
502 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
505 /// ExtractElementConstantExpr - This class is private to
506 /// Constants.cpp, and is used behind the scenes to implement
507 /// extractelement constant exprs.
508 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
509 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
511 // allocate space for exactly two operands
512 void *operator new(size_t s) {
513 return User::operator new(s, 2);
515 ExtractElementConstantExpr(Constant *C1, Constant *C2)
516 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
517 Instruction::ExtractElement, &Op<0>(), 2) {
521 /// Transparently provide more efficient getOperand methods.
522 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
525 /// InsertElementConstantExpr - This class is private to
526 /// Constants.cpp, and is used behind the scenes to implement
527 /// insertelement constant exprs.
528 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
529 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
531 // allocate space for exactly three operands
532 void *operator new(size_t s) {
533 return User::operator new(s, 3);
535 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
536 : ConstantExpr(C1->getType(), Instruction::InsertElement,
542 /// Transparently provide more efficient getOperand methods.
543 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
546 /// ShuffleVectorConstantExpr - This class is private to
547 /// Constants.cpp, and is used behind the scenes to implement
548 /// shufflevector constant exprs.
549 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
550 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
552 // allocate space for exactly three operands
553 void *operator new(size_t s) {
554 return User::operator new(s, 3);
556 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
557 : ConstantExpr(C1->getType(), Instruction::ShuffleVector,
563 /// Transparently provide more efficient getOperand methods.
564 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
567 /// ExtractValueConstantExpr - This class is private to
568 /// Constants.cpp, and is used behind the scenes to implement
569 /// extractvalue constant exprs.
570 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
571 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
573 // allocate space for exactly one operand
574 void *operator new(size_t s) {
575 return User::operator new(s, 1);
577 ExtractValueConstantExpr(Constant *Agg,
578 const SmallVector<unsigned, 4> &IdxList,
580 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
585 /// Indices - These identify which value to extract.
586 const SmallVector<unsigned, 4> Indices;
588 /// Transparently provide more efficient getOperand methods.
589 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
592 /// InsertValueConstantExpr - This class is private to
593 /// Constants.cpp, and is used behind the scenes to implement
594 /// insertvalue constant exprs.
595 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
596 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
598 // allocate space for exactly one operand
599 void *operator new(size_t s) {
600 return User::operator new(s, 2);
602 InsertValueConstantExpr(Constant *Agg, Constant *Val,
603 const SmallVector<unsigned, 4> &IdxList,
605 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
611 /// Indices - These identify the position for the insertion.
612 const SmallVector<unsigned, 4> Indices;
614 /// Transparently provide more efficient getOperand methods.
615 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
619 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
620 /// used behind the scenes to implement getelementpr constant exprs.
621 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
622 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
625 static GetElementPtrConstantExpr *Create(Constant *C,
626 const std::vector<Constant*>&IdxList,
627 const Type *DestTy) {
628 return new(IdxList.size() + 1)
629 GetElementPtrConstantExpr(C, IdxList, DestTy);
631 /// Transparently provide more efficient getOperand methods.
632 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
635 // CompareConstantExpr - This class is private to Constants.cpp, and is used
636 // behind the scenes to implement ICmp and FCmp constant expressions. This is
637 // needed in order to store the predicate value for these instructions.
638 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
639 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
640 // allocate space for exactly two operands
641 void *operator new(size_t s) {
642 return User::operator new(s, 2);
644 unsigned short predicate;
645 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
646 unsigned short pred, Constant* LHS, Constant* RHS)
647 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
651 /// Transparently provide more efficient getOperand methods.
652 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
655 } // end anonymous namespace
658 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
660 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
663 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
665 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
668 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
670 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
673 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
675 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
678 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
680 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
683 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
685 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
688 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
690 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
693 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
695 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
698 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
701 GetElementPtrConstantExpr::GetElementPtrConstantExpr
703 const std::vector<Constant*> &IdxList,
705 : ConstantExpr(DestTy, Instruction::GetElementPtr,
706 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
707 - (IdxList.size()+1),
710 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
711 OperandList[i+1] = IdxList[i];
714 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
718 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
720 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
723 } // End llvm namespace
726 // Utility function for determining if a ConstantExpr is a CastOp or not. This
727 // can't be inline because we don't want to #include Instruction.h into
729 bool ConstantExpr::isCast() const {
730 return Instruction::isCast(getOpcode());
733 bool ConstantExpr::isCompare() const {
734 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp ||
735 getOpcode() == Instruction::VICmp || getOpcode() == Instruction::VFCmp;
738 bool ConstantExpr::hasIndices() const {
739 return getOpcode() == Instruction::ExtractValue ||
740 getOpcode() == Instruction::InsertValue;
743 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
744 if (const ExtractValueConstantExpr *EVCE =
745 dyn_cast<ExtractValueConstantExpr>(this))
746 return EVCE->Indices;
748 return cast<InsertValueConstantExpr>(this)->Indices;
751 /// ConstantExpr::get* - Return some common constants without having to
752 /// specify the full Instruction::OPCODE identifier.
754 Constant *ConstantExpr::getNeg(Constant *C) {
755 return get(Instruction::Sub,
756 ConstantExpr::getZeroValueForNegationExpr(C->getType()),
759 Constant *ConstantExpr::getNot(Constant *C) {
760 assert((isa<IntegerType>(C->getType()) ||
761 cast<VectorType>(C->getType())->getElementType()->isInteger()) &&
762 "Cannot NOT a nonintegral value!");
763 return get(Instruction::Xor, C,
764 Constant::getAllOnesValue(C->getType()));
766 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
767 return get(Instruction::Add, C1, C2);
769 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
770 return get(Instruction::Sub, C1, C2);
772 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
773 return get(Instruction::Mul, C1, C2);
775 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2) {
776 return get(Instruction::UDiv, C1, C2);
778 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2) {
779 return get(Instruction::SDiv, C1, C2);
781 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
782 return get(Instruction::FDiv, C1, C2);
784 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
785 return get(Instruction::URem, C1, C2);
787 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
788 return get(Instruction::SRem, C1, C2);
790 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
791 return get(Instruction::FRem, C1, C2);
793 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
794 return get(Instruction::And, C1, C2);
796 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
797 return get(Instruction::Or, C1, C2);
799 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
800 return get(Instruction::Xor, C1, C2);
802 unsigned ConstantExpr::getPredicate() const {
803 assert(getOpcode() == Instruction::FCmp ||
804 getOpcode() == Instruction::ICmp ||
805 getOpcode() == Instruction::VFCmp ||
806 getOpcode() == Instruction::VICmp);
807 return ((const CompareConstantExpr*)this)->predicate;
809 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
810 return get(Instruction::Shl, C1, C2);
812 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
813 return get(Instruction::LShr, C1, C2);
815 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
816 return get(Instruction::AShr, C1, C2);
819 /// getWithOperandReplaced - Return a constant expression identical to this
820 /// one, but with the specified operand set to the specified value.
822 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
823 assert(OpNo < getNumOperands() && "Operand num is out of range!");
824 assert(Op->getType() == getOperand(OpNo)->getType() &&
825 "Replacing operand with value of different type!");
826 if (getOperand(OpNo) == Op)
827 return const_cast<ConstantExpr*>(this);
829 Constant *Op0, *Op1, *Op2;
830 switch (getOpcode()) {
831 case Instruction::Trunc:
832 case Instruction::ZExt:
833 case Instruction::SExt:
834 case Instruction::FPTrunc:
835 case Instruction::FPExt:
836 case Instruction::UIToFP:
837 case Instruction::SIToFP:
838 case Instruction::FPToUI:
839 case Instruction::FPToSI:
840 case Instruction::PtrToInt:
841 case Instruction::IntToPtr:
842 case Instruction::BitCast:
843 return ConstantExpr::getCast(getOpcode(), Op, getType());
844 case Instruction::Select:
845 Op0 = (OpNo == 0) ? Op : getOperand(0);
846 Op1 = (OpNo == 1) ? Op : getOperand(1);
847 Op2 = (OpNo == 2) ? Op : getOperand(2);
848 return ConstantExpr::getSelect(Op0, Op1, Op2);
849 case Instruction::InsertElement:
850 Op0 = (OpNo == 0) ? Op : getOperand(0);
851 Op1 = (OpNo == 1) ? Op : getOperand(1);
852 Op2 = (OpNo == 2) ? Op : getOperand(2);
853 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
854 case Instruction::ExtractElement:
855 Op0 = (OpNo == 0) ? Op : getOperand(0);
856 Op1 = (OpNo == 1) ? Op : getOperand(1);
857 return ConstantExpr::getExtractElement(Op0, Op1);
858 case Instruction::ShuffleVector:
859 Op0 = (OpNo == 0) ? Op : getOperand(0);
860 Op1 = (OpNo == 1) ? Op : getOperand(1);
861 Op2 = (OpNo == 2) ? Op : getOperand(2);
862 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
863 case Instruction::GetElementPtr: {
864 SmallVector<Constant*, 8> Ops;
865 Ops.resize(getNumOperands()-1);
866 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
867 Ops[i-1] = getOperand(i);
869 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
871 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
874 assert(getNumOperands() == 2 && "Must be binary operator?");
875 Op0 = (OpNo == 0) ? Op : getOperand(0);
876 Op1 = (OpNo == 1) ? Op : getOperand(1);
877 return ConstantExpr::get(getOpcode(), Op0, Op1);
881 /// getWithOperands - This returns the current constant expression with the
882 /// operands replaced with the specified values. The specified operands must
883 /// match count and type with the existing ones.
884 Constant *ConstantExpr::
885 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
886 assert(NumOps == getNumOperands() && "Operand count mismatch!");
887 bool AnyChange = false;
888 for (unsigned i = 0; i != NumOps; ++i) {
889 assert(Ops[i]->getType() == getOperand(i)->getType() &&
890 "Operand type mismatch!");
891 AnyChange |= Ops[i] != getOperand(i);
893 if (!AnyChange) // No operands changed, return self.
894 return const_cast<ConstantExpr*>(this);
896 switch (getOpcode()) {
897 case Instruction::Trunc:
898 case Instruction::ZExt:
899 case Instruction::SExt:
900 case Instruction::FPTrunc:
901 case Instruction::FPExt:
902 case Instruction::UIToFP:
903 case Instruction::SIToFP:
904 case Instruction::FPToUI:
905 case Instruction::FPToSI:
906 case Instruction::PtrToInt:
907 case Instruction::IntToPtr:
908 case Instruction::BitCast:
909 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
910 case Instruction::Select:
911 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
912 case Instruction::InsertElement:
913 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
914 case Instruction::ExtractElement:
915 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
916 case Instruction::ShuffleVector:
917 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
918 case Instruction::GetElementPtr:
919 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
920 case Instruction::ICmp:
921 case Instruction::FCmp:
922 case Instruction::VICmp:
923 case Instruction::VFCmp:
924 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
926 assert(getNumOperands() == 2 && "Must be binary operator?");
927 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
932 //===----------------------------------------------------------------------===//
933 // isValueValidForType implementations
935 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
936 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
937 if (Ty == Type::Int1Ty)
938 return Val == 0 || Val == 1;
940 return true; // always true, has to fit in largest type
941 uint64_t Max = (1ll << NumBits) - 1;
945 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
946 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
947 if (Ty == Type::Int1Ty)
948 return Val == 0 || Val == 1 || Val == -1;
950 return true; // always true, has to fit in largest type
951 int64_t Min = -(1ll << (NumBits-1));
952 int64_t Max = (1ll << (NumBits-1)) - 1;
953 return (Val >= Min && Val <= Max);
956 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
957 // convert modifies in place, so make a copy.
958 APFloat Val2 = APFloat(Val);
960 switch (Ty->getTypeID()) {
962 return false; // These can't be represented as floating point!
964 // FIXME rounding mode needs to be more flexible
965 case Type::FloatTyID: {
966 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
968 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
971 case Type::DoubleTyID: {
972 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
973 &Val2.getSemantics() == &APFloat::IEEEdouble)
975 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
978 case Type::X86_FP80TyID:
979 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
980 &Val2.getSemantics() == &APFloat::IEEEdouble ||
981 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
982 case Type::FP128TyID:
983 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
984 &Val2.getSemantics() == &APFloat::IEEEdouble ||
985 &Val2.getSemantics() == &APFloat::IEEEquad;
986 case Type::PPC_FP128TyID:
987 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
988 &Val2.getSemantics() == &APFloat::IEEEdouble ||
989 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
993 //===----------------------------------------------------------------------===//
994 // Factory Function Implementation
997 // The number of operands for each ConstantCreator::create method is
998 // determined by the ConstantTraits template.
999 // ConstantCreator - A class that is used to create constants by
1000 // ValueMap*. This class should be partially specialized if there is
1001 // something strange that needs to be done to interface to the ctor for the
1005 template<class ValType>
1006 struct ConstantTraits;
1008 template<typename T, typename Alloc>
1009 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1010 static unsigned uses(const std::vector<T, Alloc>& v) {
1015 template<class ConstantClass, class TypeClass, class ValType>
1016 struct VISIBILITY_HIDDEN ConstantCreator {
1017 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1018 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1022 template<class ConstantClass, class TypeClass>
1023 struct VISIBILITY_HIDDEN ConvertConstantType {
1024 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1025 assert(0 && "This type cannot be converted!\n");
1030 template<class ValType, class TypeClass, class ConstantClass,
1031 bool HasLargeKey = false /*true for arrays and structs*/ >
1032 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1034 typedef std::pair<const Type*, ValType> MapKey;
1035 typedef std::map<MapKey, Constant *> MapTy;
1036 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1037 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1039 /// Map - This is the main map from the element descriptor to the Constants.
1040 /// This is the primary way we avoid creating two of the same shape
1044 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1045 /// from the constants to their element in Map. This is important for
1046 /// removal of constants from the array, which would otherwise have to scan
1047 /// through the map with very large keys.
1048 InverseMapTy InverseMap;
1050 /// AbstractTypeMap - Map for abstract type constants.
1052 AbstractTypeMapTy AbstractTypeMap;
1055 typename MapTy::iterator map_end() { return Map.end(); }
1057 /// InsertOrGetItem - Return an iterator for the specified element.
1058 /// If the element exists in the map, the returned iterator points to the
1059 /// entry and Exists=true. If not, the iterator points to the newly
1060 /// inserted entry and returns Exists=false. Newly inserted entries have
1061 /// I->second == 0, and should be filled in.
1062 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1065 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1066 Exists = !IP.second;
1071 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1073 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1074 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1075 IMI->second->second == CP &&
1076 "InverseMap corrupt!");
1080 typename MapTy::iterator I =
1081 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1083 if (I == Map.end() || I->second != CP) {
1084 // FIXME: This should not use a linear scan. If this gets to be a
1085 // performance problem, someone should look at this.
1086 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1093 /// getOrCreate - Return the specified constant from the map, creating it if
1095 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1096 MapKey Lookup(Ty, V);
1097 typename MapTy::iterator I = Map.find(Lookup);
1098 // Is it in the map?
1100 return static_cast<ConstantClass *>(I->second);
1102 // If no preexisting value, create one now...
1103 ConstantClass *Result =
1104 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1106 assert(Result->getType() == Ty && "Type specified is not correct!");
1107 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1109 if (HasLargeKey) // Remember the reverse mapping if needed.
1110 InverseMap.insert(std::make_pair(Result, I));
1112 // If the type of the constant is abstract, make sure that an entry exists
1113 // for it in the AbstractTypeMap.
1114 if (Ty->isAbstract()) {
1115 typename AbstractTypeMapTy::iterator TI = AbstractTypeMap.find(Ty);
1117 if (TI == AbstractTypeMap.end()) {
1118 // Add ourselves to the ATU list of the type.
1119 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1121 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1127 void remove(ConstantClass *CP) {
1128 typename MapTy::iterator I = FindExistingElement(CP);
1129 assert(I != Map.end() && "Constant not found in constant table!");
1130 assert(I->second == CP && "Didn't find correct element?");
1132 if (HasLargeKey) // Remember the reverse mapping if needed.
1133 InverseMap.erase(CP);
1135 // Now that we found the entry, make sure this isn't the entry that
1136 // the AbstractTypeMap points to.
1137 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1138 if (Ty->isAbstract()) {
1139 assert(AbstractTypeMap.count(Ty) &&
1140 "Abstract type not in AbstractTypeMap?");
1141 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1142 if (ATMEntryIt == I) {
1143 // Yes, we are removing the representative entry for this type.
1144 // See if there are any other entries of the same type.
1145 typename MapTy::iterator TmpIt = ATMEntryIt;
1147 // First check the entry before this one...
1148 if (TmpIt != Map.begin()) {
1150 if (TmpIt->first.first != Ty) // Not the same type, move back...
1154 // If we didn't find the same type, try to move forward...
1155 if (TmpIt == ATMEntryIt) {
1157 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1158 --TmpIt; // No entry afterwards with the same type
1161 // If there is another entry in the map of the same abstract type,
1162 // update the AbstractTypeMap entry now.
1163 if (TmpIt != ATMEntryIt) {
1166 // Otherwise, we are removing the last instance of this type
1167 // from the table. Remove from the ATM, and from user list.
1168 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1169 AbstractTypeMap.erase(Ty);
1178 /// MoveConstantToNewSlot - If we are about to change C to be the element
1179 /// specified by I, update our internal data structures to reflect this
1181 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1182 // First, remove the old location of the specified constant in the map.
1183 typename MapTy::iterator OldI = FindExistingElement(C);
1184 assert(OldI != Map.end() && "Constant not found in constant table!");
1185 assert(OldI->second == C && "Didn't find correct element?");
1187 // If this constant is the representative element for its abstract type,
1188 // update the AbstractTypeMap so that the representative element is I.
1189 if (C->getType()->isAbstract()) {
1190 typename AbstractTypeMapTy::iterator ATI =
1191 AbstractTypeMap.find(C->getType());
1192 assert(ATI != AbstractTypeMap.end() &&
1193 "Abstract type not in AbstractTypeMap?");
1194 if (ATI->second == OldI)
1198 // Remove the old entry from the map.
1201 // Update the inverse map so that we know that this constant is now
1202 // located at descriptor I.
1204 assert(I->second == C && "Bad inversemap entry!");
1209 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1210 typename AbstractTypeMapTy::iterator I =
1211 AbstractTypeMap.find(cast<Type>(OldTy));
1213 assert(I != AbstractTypeMap.end() &&
1214 "Abstract type not in AbstractTypeMap?");
1216 // Convert a constant at a time until the last one is gone. The last one
1217 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1218 // eliminated eventually.
1220 ConvertConstantType<ConstantClass,
1221 TypeClass>::convert(
1222 static_cast<ConstantClass *>(I->second->second),
1223 cast<TypeClass>(NewTy));
1225 I = AbstractTypeMap.find(cast<Type>(OldTy));
1226 } while (I != AbstractTypeMap.end());
1229 // If the type became concrete without being refined to any other existing
1230 // type, we just remove ourselves from the ATU list.
1231 void typeBecameConcrete(const DerivedType *AbsTy) {
1232 AbsTy->removeAbstractTypeUser(this);
1236 DOUT << "Constant.cpp: ValueMap\n";
1243 //---- ConstantAggregateZero::get() implementation...
1246 // ConstantAggregateZero does not take extra "value" argument...
1247 template<class ValType>
1248 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1249 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1250 return new ConstantAggregateZero(Ty);
1255 struct ConvertConstantType<ConstantAggregateZero, Type> {
1256 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1257 // Make everyone now use a constant of the new type...
1258 Constant *New = ConstantAggregateZero::get(NewTy);
1259 assert(New != OldC && "Didn't replace constant??");
1260 OldC->uncheckedReplaceAllUsesWith(New);
1261 OldC->destroyConstant(); // This constant is now dead, destroy it.
1266 static ManagedStatic<ValueMap<char, Type,
1267 ConstantAggregateZero> > AggZeroConstants;
1269 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1271 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1272 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1273 "Cannot create an aggregate zero of non-aggregate type!");
1274 return AggZeroConstants->getOrCreate(Ty, 0);
1277 // destroyConstant - Remove the constant from the constant table...
1279 void ConstantAggregateZero::destroyConstant() {
1280 AggZeroConstants->remove(this);
1281 destroyConstantImpl();
1284 //---- ConstantArray::get() implementation...
1288 struct ConvertConstantType<ConstantArray, ArrayType> {
1289 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1290 // Make everyone now use a constant of the new type...
1291 std::vector<Constant*> C;
1292 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1293 C.push_back(cast<Constant>(OldC->getOperand(i)));
1294 Constant *New = ConstantArray::get(NewTy, C);
1295 assert(New != OldC && "Didn't replace constant??");
1296 OldC->uncheckedReplaceAllUsesWith(New);
1297 OldC->destroyConstant(); // This constant is now dead, destroy it.
1302 static std::vector<Constant*> getValType(ConstantArray *CA) {
1303 std::vector<Constant*> Elements;
1304 Elements.reserve(CA->getNumOperands());
1305 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1306 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1310 typedef ValueMap<std::vector<Constant*>, ArrayType,
1311 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1312 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1314 Constant *ConstantArray::get(const ArrayType *Ty,
1315 const std::vector<Constant*> &V) {
1316 // If this is an all-zero array, return a ConstantAggregateZero object
1319 if (!C->isNullValue())
1320 return ArrayConstants->getOrCreate(Ty, V);
1321 for (unsigned i = 1, e = V.size(); i != e; ++i)
1323 return ArrayConstants->getOrCreate(Ty, V);
1325 return ConstantAggregateZero::get(Ty);
1328 // destroyConstant - Remove the constant from the constant table...
1330 void ConstantArray::destroyConstant() {
1331 ArrayConstants->remove(this);
1332 destroyConstantImpl();
1335 /// ConstantArray::get(const string&) - Return an array that is initialized to
1336 /// contain the specified string. If length is zero then a null terminator is
1337 /// added to the specified string so that it may be used in a natural way.
1338 /// Otherwise, the length parameter specifies how much of the string to use
1339 /// and it won't be null terminated.
1341 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1342 std::vector<Constant*> ElementVals;
1343 for (unsigned i = 0; i < Str.length(); ++i)
1344 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1346 // Add a null terminator to the string...
1348 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1351 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1352 return ConstantArray::get(ATy, ElementVals);
1355 /// isString - This method returns true if the array is an array of i8, and
1356 /// if the elements of the array are all ConstantInt's.
1357 bool ConstantArray::isString() const {
1358 // Check the element type for i8...
1359 if (getType()->getElementType() != Type::Int8Ty)
1361 // Check the elements to make sure they are all integers, not constant
1363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1364 if (!isa<ConstantInt>(getOperand(i)))
1369 /// isCString - This method returns true if the array is a string (see
1370 /// isString) and it ends in a null byte \0 and does not contains any other
1371 /// null bytes except its terminator.
1372 bool ConstantArray::isCString() const {
1373 // Check the element type for i8...
1374 if (getType()->getElementType() != Type::Int8Ty)
1376 Constant *Zero = Constant::getNullValue(getOperand(0)->getType());
1377 // Last element must be a null.
1378 if (getOperand(getNumOperands()-1) != Zero)
1380 // Other elements must be non-null integers.
1381 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1382 if (!isa<ConstantInt>(getOperand(i)))
1384 if (getOperand(i) == Zero)
1391 // getAsString - If the sub-element type of this array is i8
1392 // then this method converts the array to an std::string and returns it.
1393 // Otherwise, it asserts out.
1395 std::string ConstantArray::getAsString() const {
1396 assert(isString() && "Not a string!");
1398 Result.reserve(getNumOperands());
1399 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1400 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1405 //---- ConstantStruct::get() implementation...
1410 struct ConvertConstantType<ConstantStruct, StructType> {
1411 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1412 // Make everyone now use a constant of the new type...
1413 std::vector<Constant*> C;
1414 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1415 C.push_back(cast<Constant>(OldC->getOperand(i)));
1416 Constant *New = ConstantStruct::get(NewTy, C);
1417 assert(New != OldC && "Didn't replace constant??");
1419 OldC->uncheckedReplaceAllUsesWith(New);
1420 OldC->destroyConstant(); // This constant is now dead, destroy it.
1425 typedef ValueMap<std::vector<Constant*>, StructType,
1426 ConstantStruct, true /*largekey*/> StructConstantsTy;
1427 static ManagedStatic<StructConstantsTy> StructConstants;
1429 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1430 std::vector<Constant*> Elements;
1431 Elements.reserve(CS->getNumOperands());
1432 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1433 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1437 Constant *ConstantStruct::get(const StructType *Ty,
1438 const std::vector<Constant*> &V) {
1439 // Create a ConstantAggregateZero value if all elements are zeros...
1440 for (unsigned i = 0, e = V.size(); i != e; ++i)
1441 if (!V[i]->isNullValue())
1442 return StructConstants->getOrCreate(Ty, V);
1444 return ConstantAggregateZero::get(Ty);
1447 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1448 std::vector<const Type*> StructEls;
1449 StructEls.reserve(V.size());
1450 for (unsigned i = 0, e = V.size(); i != e; ++i)
1451 StructEls.push_back(V[i]->getType());
1452 return get(StructType::get(StructEls, packed), V);
1455 // destroyConstant - Remove the constant from the constant table...
1457 void ConstantStruct::destroyConstant() {
1458 StructConstants->remove(this);
1459 destroyConstantImpl();
1462 //---- ConstantVector::get() implementation...
1466 struct ConvertConstantType<ConstantVector, VectorType> {
1467 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1468 // Make everyone now use a constant of the new type...
1469 std::vector<Constant*> C;
1470 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1471 C.push_back(cast<Constant>(OldC->getOperand(i)));
1472 Constant *New = ConstantVector::get(NewTy, C);
1473 assert(New != OldC && "Didn't replace constant??");
1474 OldC->uncheckedReplaceAllUsesWith(New);
1475 OldC->destroyConstant(); // This constant is now dead, destroy it.
1480 static std::vector<Constant*> getValType(ConstantVector *CP) {
1481 std::vector<Constant*> Elements;
1482 Elements.reserve(CP->getNumOperands());
1483 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1484 Elements.push_back(CP->getOperand(i));
1488 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1489 ConstantVector> > VectorConstants;
1491 Constant *ConstantVector::get(const VectorType *Ty,
1492 const std::vector<Constant*> &V) {
1493 assert(!V.empty() && "Vectors can't be empty");
1494 // If this is an all-undef or alll-zero vector, return a
1495 // ConstantAggregateZero or UndefValue.
1497 bool isZero = C->isNullValue();
1498 bool isUndef = isa<UndefValue>(C);
1500 if (isZero || isUndef) {
1501 for (unsigned i = 1, e = V.size(); i != e; ++i)
1503 isZero = isUndef = false;
1509 return ConstantAggregateZero::get(Ty);
1511 return UndefValue::get(Ty);
1512 return VectorConstants->getOrCreate(Ty, V);
1515 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1516 assert(!V.empty() && "Cannot infer type if V is empty");
1517 return get(VectorType::get(V.front()->getType(),V.size()), V);
1520 // destroyConstant - Remove the constant from the constant table...
1522 void ConstantVector::destroyConstant() {
1523 VectorConstants->remove(this);
1524 destroyConstantImpl();
1527 /// This function will return true iff every element in this vector constant
1528 /// is set to all ones.
1529 /// @returns true iff this constant's emements are all set to all ones.
1530 /// @brief Determine if the value is all ones.
1531 bool ConstantVector::isAllOnesValue() const {
1532 // Check out first element.
1533 const Constant *Elt = getOperand(0);
1534 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1535 if (!CI || !CI->isAllOnesValue()) return false;
1536 // Then make sure all remaining elements point to the same value.
1537 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1538 if (getOperand(I) != Elt) return false;
1543 /// getSplatValue - If this is a splat constant, where all of the
1544 /// elements have the same value, return that value. Otherwise return null.
1545 Constant *ConstantVector::getSplatValue() {
1546 // Check out first element.
1547 Constant *Elt = getOperand(0);
1548 // Then make sure all remaining elements point to the same value.
1549 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1550 if (getOperand(I) != Elt) return 0;
1554 //---- ConstantPointerNull::get() implementation...
1558 // ConstantPointerNull does not take extra "value" argument...
1559 template<class ValType>
1560 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1561 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1562 return new ConstantPointerNull(Ty);
1567 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1568 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1569 // Make everyone now use a constant of the new type...
1570 Constant *New = ConstantPointerNull::get(NewTy);
1571 assert(New != OldC && "Didn't replace constant??");
1572 OldC->uncheckedReplaceAllUsesWith(New);
1573 OldC->destroyConstant(); // This constant is now dead, destroy it.
1578 static ManagedStatic<ValueMap<char, PointerType,
1579 ConstantPointerNull> > NullPtrConstants;
1581 static char getValType(ConstantPointerNull *) {
1586 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1587 return NullPtrConstants->getOrCreate(Ty, 0);
1590 // destroyConstant - Remove the constant from the constant table...
1592 void ConstantPointerNull::destroyConstant() {
1593 NullPtrConstants->remove(this);
1594 destroyConstantImpl();
1598 //---- UndefValue::get() implementation...
1602 // UndefValue does not take extra "value" argument...
1603 template<class ValType>
1604 struct ConstantCreator<UndefValue, Type, ValType> {
1605 static UndefValue *create(const Type *Ty, const ValType &V) {
1606 return new UndefValue(Ty);
1611 struct ConvertConstantType<UndefValue, Type> {
1612 static void convert(UndefValue *OldC, const Type *NewTy) {
1613 // Make everyone now use a constant of the new type.
1614 Constant *New = UndefValue::get(NewTy);
1615 assert(New != OldC && "Didn't replace constant??");
1616 OldC->uncheckedReplaceAllUsesWith(New);
1617 OldC->destroyConstant(); // This constant is now dead, destroy it.
1622 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1624 static char getValType(UndefValue *) {
1629 UndefValue *UndefValue::get(const Type *Ty) {
1630 return UndefValueConstants->getOrCreate(Ty, 0);
1633 // destroyConstant - Remove the constant from the constant table.
1635 void UndefValue::destroyConstant() {
1636 UndefValueConstants->remove(this);
1637 destroyConstantImpl();
1641 //---- ConstantExpr::get() implementations...
1646 struct ExprMapKeyType {
1647 typedef SmallVector<unsigned, 4> IndexList;
1649 ExprMapKeyType(unsigned opc,
1650 const std::vector<Constant*> &ops,
1651 unsigned short pred = 0,
1652 const IndexList &inds = IndexList())
1653 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1656 std::vector<Constant*> operands;
1658 bool operator==(const ExprMapKeyType& that) const {
1659 return this->opcode == that.opcode &&
1660 this->predicate == that.predicate &&
1661 this->operands == that.operands &&
1662 this->indices == that.indices;
1664 bool operator<(const ExprMapKeyType & that) const {
1665 return this->opcode < that.opcode ||
1666 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1667 (this->opcode == that.opcode && this->predicate == that.predicate &&
1668 this->operands < that.operands) ||
1669 (this->opcode == that.opcode && this->predicate == that.predicate &&
1670 this->operands == that.operands && this->indices < that.indices);
1673 bool operator!=(const ExprMapKeyType& that) const {
1674 return !(*this == that);
1682 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1683 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1684 unsigned short pred = 0) {
1685 if (Instruction::isCast(V.opcode))
1686 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1687 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1688 V.opcode < Instruction::BinaryOpsEnd))
1689 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1690 if (V.opcode == Instruction::Select)
1691 return new SelectConstantExpr(V.operands[0], V.operands[1],
1693 if (V.opcode == Instruction::ExtractElement)
1694 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1695 if (V.opcode == Instruction::InsertElement)
1696 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1698 if (V.opcode == Instruction::ShuffleVector)
1699 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1701 if (V.opcode == Instruction::InsertValue)
1702 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1704 if (V.opcode == Instruction::ExtractValue)
1705 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1706 if (V.opcode == Instruction::GetElementPtr) {
1707 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1708 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1711 // The compare instructions are weird. We have to encode the predicate
1712 // value and it is combined with the instruction opcode by multiplying
1713 // the opcode by one hundred. We must decode this to get the predicate.
1714 if (V.opcode == Instruction::ICmp)
1715 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1716 V.operands[0], V.operands[1]);
1717 if (V.opcode == Instruction::FCmp)
1718 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1719 V.operands[0], V.operands[1]);
1720 if (V.opcode == Instruction::VICmp)
1721 return new CompareConstantExpr(Ty, Instruction::VICmp, V.predicate,
1722 V.operands[0], V.operands[1]);
1723 if (V.opcode == Instruction::VFCmp)
1724 return new CompareConstantExpr(Ty, Instruction::VFCmp, V.predicate,
1725 V.operands[0], V.operands[1]);
1726 assert(0 && "Invalid ConstantExpr!");
1732 struct ConvertConstantType<ConstantExpr, Type> {
1733 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1735 switch (OldC->getOpcode()) {
1736 case Instruction::Trunc:
1737 case Instruction::ZExt:
1738 case Instruction::SExt:
1739 case Instruction::FPTrunc:
1740 case Instruction::FPExt:
1741 case Instruction::UIToFP:
1742 case Instruction::SIToFP:
1743 case Instruction::FPToUI:
1744 case Instruction::FPToSI:
1745 case Instruction::PtrToInt:
1746 case Instruction::IntToPtr:
1747 case Instruction::BitCast:
1748 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1751 case Instruction::Select:
1752 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1753 OldC->getOperand(1),
1754 OldC->getOperand(2));
1757 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1758 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1759 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1760 OldC->getOperand(1));
1762 case Instruction::GetElementPtr:
1763 // Make everyone now use a constant of the new type...
1764 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1765 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1766 &Idx[0], Idx.size());
1770 assert(New != OldC && "Didn't replace constant??");
1771 OldC->uncheckedReplaceAllUsesWith(New);
1772 OldC->destroyConstant(); // This constant is now dead, destroy it.
1775 } // end namespace llvm
1778 static ExprMapKeyType getValType(ConstantExpr *CE) {
1779 std::vector<Constant*> Operands;
1780 Operands.reserve(CE->getNumOperands());
1781 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1782 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1783 return ExprMapKeyType(CE->getOpcode(), Operands,
1784 CE->isCompare() ? CE->getPredicate() : 0,
1786 CE->getIndices() : SmallVector<unsigned, 4>());
1789 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1790 ConstantExpr> > ExprConstants;
1792 /// This is a utility function to handle folding of casts and lookup of the
1793 /// cast in the ExprConstants map. It is used by the various get* methods below.
1794 static inline Constant *getFoldedCast(
1795 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1796 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1797 // Fold a few common cases
1798 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1801 // Look up the constant in the table first to ensure uniqueness
1802 std::vector<Constant*> argVec(1, C);
1803 ExprMapKeyType Key(opc, argVec);
1804 return ExprConstants->getOrCreate(Ty, Key);
1807 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1808 Instruction::CastOps opc = Instruction::CastOps(oc);
1809 assert(Instruction::isCast(opc) && "opcode out of range");
1810 assert(C && Ty && "Null arguments to getCast");
1811 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1815 assert(0 && "Invalid cast opcode");
1817 case Instruction::Trunc: return getTrunc(C, Ty);
1818 case Instruction::ZExt: return getZExt(C, Ty);
1819 case Instruction::SExt: return getSExt(C, Ty);
1820 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1821 case Instruction::FPExt: return getFPExtend(C, Ty);
1822 case Instruction::UIToFP: return getUIToFP(C, Ty);
1823 case Instruction::SIToFP: return getSIToFP(C, Ty);
1824 case Instruction::FPToUI: return getFPToUI(C, Ty);
1825 case Instruction::FPToSI: return getFPToSI(C, Ty);
1826 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1827 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1828 case Instruction::BitCast: return getBitCast(C, Ty);
1833 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1834 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1835 return getCast(Instruction::BitCast, C, Ty);
1836 return getCast(Instruction::ZExt, C, Ty);
1839 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1840 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1841 return getCast(Instruction::BitCast, C, Ty);
1842 return getCast(Instruction::SExt, C, Ty);
1845 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1846 if (C->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1847 return getCast(Instruction::BitCast, C, Ty);
1848 return getCast(Instruction::Trunc, C, Ty);
1851 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1852 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1853 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1855 if (Ty->isInteger())
1856 return getCast(Instruction::PtrToInt, S, Ty);
1857 return getCast(Instruction::BitCast, S, Ty);
1860 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1862 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1863 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1864 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1865 Instruction::CastOps opcode =
1866 (SrcBits == DstBits ? Instruction::BitCast :
1867 (SrcBits > DstBits ? Instruction::Trunc :
1868 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1869 return getCast(opcode, C, Ty);
1872 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1873 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1875 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1876 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1877 if (SrcBits == DstBits)
1878 return C; // Avoid a useless cast
1879 Instruction::CastOps opcode =
1880 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1881 return getCast(opcode, C, Ty);
1884 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1885 assert(C->getType()->isInteger() && "Trunc operand must be integer");
1886 assert(Ty->isInteger() && "Trunc produces only integral");
1887 assert(C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1888 "SrcTy must be larger than DestTy for Trunc!");
1890 return getFoldedCast(Instruction::Trunc, C, Ty);
1893 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1894 assert(C->getType()->isInteger() && "SEXt operand must be integral");
1895 assert(Ty->isInteger() && "SExt produces only integer");
1896 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1897 "SrcTy must be smaller than DestTy for SExt!");
1899 return getFoldedCast(Instruction::SExt, C, Ty);
1902 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1903 assert(C->getType()->isInteger() && "ZEXt operand must be integral");
1904 assert(Ty->isInteger() && "ZExt produces only integer");
1905 assert(C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1906 "SrcTy must be smaller than DestTy for ZExt!");
1908 return getFoldedCast(Instruction::ZExt, C, Ty);
1911 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1912 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1913 C->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()&&
1914 "This is an illegal floating point truncation!");
1915 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1918 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1919 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1920 C->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()&&
1921 "This is an illegal floating point extension!");
1922 return getFoldedCast(Instruction::FPExt, C, Ty);
1925 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1927 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1928 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1930 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1931 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1932 "This is an illegal uint to floating point cast!");
1933 return getFoldedCast(Instruction::UIToFP, C, Ty);
1936 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1938 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1939 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1941 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1942 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1943 "This is an illegal sint to floating point cast!");
1944 return getFoldedCast(Instruction::SIToFP, C, Ty);
1947 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1949 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1950 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1952 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1953 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1954 "This is an illegal floating point to uint cast!");
1955 return getFoldedCast(Instruction::FPToUI, C, Ty);
1958 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1960 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1961 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1963 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1964 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1965 "This is an illegal floating point to sint cast!");
1966 return getFoldedCast(Instruction::FPToSI, C, Ty);
1969 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1970 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1971 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1972 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1975 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1976 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1977 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1978 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1981 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1982 // BitCast implies a no-op cast of type only. No bits change. However, you
1983 // can't cast pointers to anything but pointers.
1985 const Type *SrcTy = C->getType();
1986 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1987 "BitCast cannot cast pointer to non-pointer and vice versa");
1989 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1990 // or nonptr->ptr). For all the other types, the cast is okay if source and
1991 // destination bit widths are identical.
1992 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1993 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1995 assert(SrcBitSize == DstBitSize && "BitCast requies types of same width");
1996 return getFoldedCast(Instruction::BitCast, C, DstTy);
1999 Constant *ConstantExpr::getSizeOf(const Type *Ty) {
2000 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2001 Constant *GEPIdx = ConstantInt::get(Type::Int32Ty, 1);
2003 getGetElementPtr(getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
2004 return getCast(Instruction::PtrToInt, GEP, Type::Int64Ty);
2007 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2008 Constant *C1, Constant *C2) {
2009 // Check the operands for consistency first
2010 assert(Opcode >= Instruction::BinaryOpsBegin &&
2011 Opcode < Instruction::BinaryOpsEnd &&
2012 "Invalid opcode in binary constant expression");
2013 assert(C1->getType() == C2->getType() &&
2014 "Operand types in binary constant expression should match");
2016 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2017 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2018 return FC; // Fold a few common cases...
2020 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2021 ExprMapKeyType Key(Opcode, argVec);
2022 return ExprConstants->getOrCreate(ReqTy, Key);
2025 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2026 Constant *C1, Constant *C2) {
2027 bool isVectorType = C1->getType()->getTypeID() == Type::VectorTyID;
2028 switch (predicate) {
2029 default: assert(0 && "Invalid CmpInst predicate");
2030 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2031 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2032 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2033 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2034 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2035 case CmpInst::FCMP_TRUE:
2036 return isVectorType ? getVFCmp(predicate, C1, C2)
2037 : getFCmp(predicate, C1, C2);
2038 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2039 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2040 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2041 case CmpInst::ICMP_SLE:
2042 return isVectorType ? getVICmp(predicate, C1, C2)
2043 : getICmp(predicate, C1, C2);
2047 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2050 case Instruction::Add:
2051 case Instruction::Sub:
2052 case Instruction::Mul:
2053 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2054 assert((C1->getType()->isInteger() || C1->getType()->isFloatingPoint() ||
2055 isa<VectorType>(C1->getType())) &&
2056 "Tried to create an arithmetic operation on a non-arithmetic type!");
2058 case Instruction::UDiv:
2059 case Instruction::SDiv:
2060 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2061 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2062 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2063 "Tried to create an arithmetic operation on a non-arithmetic type!");
2065 case Instruction::FDiv:
2066 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2067 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2068 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2069 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2071 case Instruction::URem:
2072 case Instruction::SRem:
2073 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2074 assert((C1->getType()->isInteger() || (isa<VectorType>(C1->getType()) &&
2075 cast<VectorType>(C1->getType())->getElementType()->isInteger())) &&
2076 "Tried to create an arithmetic operation on a non-arithmetic type!");
2078 case Instruction::FRem:
2079 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2080 assert((C1->getType()->isFloatingPoint() || (isa<VectorType>(C1->getType())
2081 && cast<VectorType>(C1->getType())->getElementType()->isFloatingPoint()))
2082 && "Tried to create an arithmetic operation on a non-arithmetic type!");
2084 case Instruction::And:
2085 case Instruction::Or:
2086 case Instruction::Xor:
2087 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2088 assert((C1->getType()->isInteger() || isa<VectorType>(C1->getType())) &&
2089 "Tried to create a logical operation on a non-integral type!");
2091 case Instruction::Shl:
2092 case Instruction::LShr:
2093 case Instruction::AShr:
2094 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2095 assert(C1->getType()->isInteger() &&
2096 "Tried to create a shift operation on a non-integer type!");
2103 return getTy(C1->getType(), Opcode, C1, C2);
2106 Constant *ConstantExpr::getCompare(unsigned short pred,
2107 Constant *C1, Constant *C2) {
2108 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2109 return getCompareTy(pred, C1, C2);
2112 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2113 Constant *V1, Constant *V2) {
2114 assert(C->getType() == Type::Int1Ty && "Select condition must be i1!");
2115 assert(V1->getType() == V2->getType() && "Select value types must match!");
2116 assert(V1->getType()->isFirstClassType() && "Cannot select aggregate type!");
2118 if (ReqTy == V1->getType())
2119 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
2120 return SC; // Fold common cases
2122 std::vector<Constant*> argVec(3, C);
2125 ExprMapKeyType Key(Instruction::Select, argVec);
2126 return ExprConstants->getOrCreate(ReqTy, Key);
2129 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2132 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2134 cast<PointerType>(ReqTy)->getElementType() &&
2135 "GEP indices invalid!");
2137 if (Constant *FC = ConstantFoldGetElementPtr(C, (Constant**)Idxs, NumIdx))
2138 return FC; // Fold a few common cases...
2140 assert(isa<PointerType>(C->getType()) &&
2141 "Non-pointer type for constant GetElementPtr expression");
2142 // Look up the constant in the table first to ensure uniqueness
2143 std::vector<Constant*> ArgVec;
2144 ArgVec.reserve(NumIdx+1);
2145 ArgVec.push_back(C);
2146 for (unsigned i = 0; i != NumIdx; ++i)
2147 ArgVec.push_back(cast<Constant>(Idxs[i]));
2148 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2149 return ExprConstants->getOrCreate(ReqTy, Key);
2152 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2154 // Get the result type of the getelementptr!
2156 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2157 assert(Ty && "GEP indices invalid!");
2158 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2159 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2162 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2164 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2169 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2170 assert(LHS->getType() == RHS->getType());
2171 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2172 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2174 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2175 return FC; // Fold a few common cases...
2177 // Look up the constant in the table first to ensure uniqueness
2178 std::vector<Constant*> ArgVec;
2179 ArgVec.push_back(LHS);
2180 ArgVec.push_back(RHS);
2181 // Get the key type with both the opcode and predicate
2182 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2183 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2187 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2188 assert(LHS->getType() == RHS->getType());
2189 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2191 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
2192 return FC; // Fold a few common cases...
2194 // Look up the constant in the table first to ensure uniqueness
2195 std::vector<Constant*> ArgVec;
2196 ArgVec.push_back(LHS);
2197 ArgVec.push_back(RHS);
2198 // Get the key type with both the opcode and predicate
2199 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2200 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2204 ConstantExpr::getVICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2205 assert(isa<VectorType>(LHS->getType()) && LHS->getType() == RHS->getType() &&
2206 "Tried to create vicmp operation on non-vector type!");
2207 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2208 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid VICmp Predicate");
2210 const VectorType *VTy = cast<VectorType>(LHS->getType());
2211 const Type *EltTy = VTy->getElementType();
2212 unsigned NumElts = VTy->getNumElements();
2214 // See if we can fold the element-wise comparison of the LHS and RHS.
2215 SmallVector<Constant *, 16> LHSElts, RHSElts;
2216 LHS->getVectorElements(LHSElts);
2217 RHS->getVectorElements(RHSElts);
2219 if (!LHSElts.empty() && !RHSElts.empty()) {
2220 SmallVector<Constant *, 16> Elts;
2221 for (unsigned i = 0; i != NumElts; ++i) {
2222 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2224 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2225 if (FCI->getZExtValue())
2226 Elts.push_back(ConstantInt::getAllOnesValue(EltTy));
2228 Elts.push_back(ConstantInt::get(EltTy, 0ULL));
2229 } else if (FC && isa<UndefValue>(FC)) {
2230 Elts.push_back(UndefValue::get(EltTy));
2235 if (Elts.size() == NumElts)
2236 return ConstantVector::get(&Elts[0], Elts.size());
2239 // Look up the constant in the table first to ensure uniqueness
2240 std::vector<Constant*> ArgVec;
2241 ArgVec.push_back(LHS);
2242 ArgVec.push_back(RHS);
2243 // Get the key type with both the opcode and predicate
2244 const ExprMapKeyType Key(Instruction::VICmp, ArgVec, pred);
2245 return ExprConstants->getOrCreate(LHS->getType(), Key);
2249 ConstantExpr::getVFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2250 assert(isa<VectorType>(LHS->getType()) &&
2251 "Tried to create vfcmp operation on non-vector type!");
2252 assert(LHS->getType() == RHS->getType());
2253 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid VFCmp Predicate");
2255 const VectorType *VTy = cast<VectorType>(LHS->getType());
2256 unsigned NumElts = VTy->getNumElements();
2257 const Type *EltTy = VTy->getElementType();
2258 const Type *REltTy = IntegerType::get(EltTy->getPrimitiveSizeInBits());
2259 const Type *ResultTy = VectorType::get(REltTy, NumElts);
2261 // See if we can fold the element-wise comparison of the LHS and RHS.
2262 SmallVector<Constant *, 16> LHSElts, RHSElts;
2263 LHS->getVectorElements(LHSElts);
2264 RHS->getVectorElements(RHSElts);
2266 if (!LHSElts.empty() && !RHSElts.empty()) {
2267 SmallVector<Constant *, 16> Elts;
2268 for (unsigned i = 0; i != NumElts; ++i) {
2269 Constant *FC = ConstantFoldCompareInstruction(pred, LHSElts[i],
2271 if (ConstantInt *FCI = dyn_cast_or_null<ConstantInt>(FC)) {
2272 if (FCI->getZExtValue())
2273 Elts.push_back(ConstantInt::getAllOnesValue(REltTy));
2275 Elts.push_back(ConstantInt::get(REltTy, 0ULL));
2276 } else if (FC && isa<UndefValue>(FC)) {
2277 Elts.push_back(UndefValue::get(REltTy));
2282 if (Elts.size() == NumElts)
2283 return ConstantVector::get(&Elts[0], Elts.size());
2286 // Look up the constant in the table first to ensure uniqueness
2287 std::vector<Constant*> ArgVec;
2288 ArgVec.push_back(LHS);
2289 ArgVec.push_back(RHS);
2290 // Get the key type with both the opcode and predicate
2291 const ExprMapKeyType Key(Instruction::VFCmp, ArgVec, pred);
2292 return ExprConstants->getOrCreate(ResultTy, Key);
2295 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2297 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, 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(Idx);
2302 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2303 return ExprConstants->getOrCreate(ReqTy, Key);
2306 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2307 assert(isa<VectorType>(Val->getType()) &&
2308 "Tried to create extractelement operation on non-vector type!");
2309 assert(Idx->getType() == Type::Int32Ty &&
2310 "Extractelement index must be i32 type!");
2311 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2315 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2316 Constant *Elt, Constant *Idx) {
2317 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2318 return FC; // Fold a few common cases...
2319 // Look up the constant in the table first to ensure uniqueness
2320 std::vector<Constant*> ArgVec(1, Val);
2321 ArgVec.push_back(Elt);
2322 ArgVec.push_back(Idx);
2323 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2324 return ExprConstants->getOrCreate(ReqTy, Key);
2327 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2329 assert(isa<VectorType>(Val->getType()) &&
2330 "Tried to create insertelement operation on non-vector type!");
2331 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2332 && "Insertelement types must match!");
2333 assert(Idx->getType() == Type::Int32Ty &&
2334 "Insertelement index must be i32 type!");
2335 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2338 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2339 Constant *V2, Constant *Mask) {
2340 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2341 return FC; // Fold a few common cases...
2342 // Look up the constant in the table first to ensure uniqueness
2343 std::vector<Constant*> ArgVec(1, V1);
2344 ArgVec.push_back(V2);
2345 ArgVec.push_back(Mask);
2346 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2347 return ExprConstants->getOrCreate(ReqTy, Key);
2350 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2352 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2353 "Invalid shuffle vector constant expr operands!");
2354 return getShuffleVectorTy(V1->getType(), V1, V2, Mask);
2357 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2359 const unsigned *Idxs, unsigned NumIdx) {
2360 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2361 Idxs+NumIdx) == Val->getType() &&
2362 "insertvalue indices invalid!");
2363 assert(Agg->getType() == ReqTy &&
2364 "insertvalue type invalid!");
2365 assert(Agg->getType()->isFirstClassType() &&
2366 "Non-first-class type for constant InsertValue expression");
2367 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
2368 assert(FC && "InsertValue constant expr couldn't be folded!");
2372 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2373 const unsigned *IdxList, unsigned NumIdx) {
2374 assert(Agg->getType()->isFirstClassType() &&
2375 "Tried to create insertelement operation on non-first-class type!");
2377 const Type *ReqTy = Agg->getType();
2380 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2382 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2383 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2386 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2387 const unsigned *Idxs, unsigned NumIdx) {
2388 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2389 Idxs+NumIdx) == ReqTy &&
2390 "extractvalue indices invalid!");
2391 assert(Agg->getType()->isFirstClassType() &&
2392 "Non-first-class type for constant extractvalue expression");
2393 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
2394 assert(FC && "ExtractValue constant expr couldn't be folded!");
2398 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2399 const unsigned *IdxList, unsigned NumIdx) {
2400 assert(Agg->getType()->isFirstClassType() &&
2401 "Tried to create extractelement operation on non-first-class type!");
2404 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2405 assert(ReqTy && "extractvalue indices invalid!");
2406 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2409 Constant *ConstantExpr::getZeroValueForNegationExpr(const Type *Ty) {
2410 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
2411 if (PTy->getElementType()->isFloatingPoint()) {
2412 std::vector<Constant*> zeros(PTy->getNumElements(),
2413 ConstantFP::getNegativeZero(PTy->getElementType()));
2414 return ConstantVector::get(PTy, zeros);
2417 if (Ty->isFloatingPoint())
2418 return ConstantFP::getNegativeZero(Ty);
2420 return Constant::getNullValue(Ty);
2423 // destroyConstant - Remove the constant from the constant table...
2425 void ConstantExpr::destroyConstant() {
2426 ExprConstants->remove(this);
2427 destroyConstantImpl();
2430 const char *ConstantExpr::getOpcodeName() const {
2431 return Instruction::getOpcodeName(getOpcode());
2434 //===----------------------------------------------------------------------===//
2435 // replaceUsesOfWithOnConstant implementations
2437 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2438 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2441 /// Note that we intentionally replace all uses of From with To here. Consider
2442 /// a large array that uses 'From' 1000 times. By handling this case all here,
2443 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2444 /// single invocation handles all 1000 uses. Handling them one at a time would
2445 /// work, but would be really slow because it would have to unique each updated
2447 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2449 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2450 Constant *ToC = cast<Constant>(To);
2452 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2453 Lookup.first.first = getType();
2454 Lookup.second = this;
2456 std::vector<Constant*> &Values = Lookup.first.second;
2457 Values.reserve(getNumOperands()); // Build replacement array.
2459 // Fill values with the modified operands of the constant array. Also,
2460 // compute whether this turns into an all-zeros array.
2461 bool isAllZeros = false;
2462 unsigned NumUpdated = 0;
2463 if (!ToC->isNullValue()) {
2464 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2465 Constant *Val = cast<Constant>(O->get());
2470 Values.push_back(Val);
2474 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2475 Constant *Val = cast<Constant>(O->get());
2480 Values.push_back(Val);
2481 if (isAllZeros) isAllZeros = Val->isNullValue();
2485 Constant *Replacement = 0;
2487 Replacement = ConstantAggregateZero::get(getType());
2489 // Check to see if we have this array type already.
2491 ArrayConstantsTy::MapTy::iterator I =
2492 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2495 Replacement = I->second;
2497 // Okay, the new shape doesn't exist in the system yet. Instead of
2498 // creating a new constant array, inserting it, replaceallusesof'ing the
2499 // old with the new, then deleting the old... just update the current one
2501 ArrayConstants->MoveConstantToNewSlot(this, I);
2503 // Update to the new value. Optimize for the case when we have a single
2504 // operand that we're changing, but handle bulk updates efficiently.
2505 if (NumUpdated == 1) {
2506 unsigned OperandToUpdate = U-OperandList;
2507 assert(getOperand(OperandToUpdate) == From &&
2508 "ReplaceAllUsesWith broken!");
2509 setOperand(OperandToUpdate, ToC);
2511 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2512 if (getOperand(i) == From)
2519 // Otherwise, I do need to replace this with an existing value.
2520 assert(Replacement != this && "I didn't contain From!");
2522 // Everyone using this now uses the replacement.
2523 uncheckedReplaceAllUsesWith(Replacement);
2525 // Delete the old constant!
2529 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2531 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2532 Constant *ToC = cast<Constant>(To);
2534 unsigned OperandToUpdate = U-OperandList;
2535 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2537 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2538 Lookup.first.first = getType();
2539 Lookup.second = this;
2540 std::vector<Constant*> &Values = Lookup.first.second;
2541 Values.reserve(getNumOperands()); // Build replacement struct.
2544 // Fill values with the modified operands of the constant struct. Also,
2545 // compute whether this turns into an all-zeros struct.
2546 bool isAllZeros = false;
2547 if (!ToC->isNullValue()) {
2548 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2549 Values.push_back(cast<Constant>(O->get()));
2552 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2553 Constant *Val = cast<Constant>(O->get());
2554 Values.push_back(Val);
2555 if (isAllZeros) isAllZeros = Val->isNullValue();
2558 Values[OperandToUpdate] = ToC;
2560 Constant *Replacement = 0;
2562 Replacement = ConstantAggregateZero::get(getType());
2564 // Check to see if we have this array type already.
2566 StructConstantsTy::MapTy::iterator I =
2567 StructConstants->InsertOrGetItem(Lookup, Exists);
2570 Replacement = I->second;
2572 // Okay, the new shape doesn't exist in the system yet. Instead of
2573 // creating a new constant struct, inserting it, replaceallusesof'ing the
2574 // old with the new, then deleting the old... just update the current one
2576 StructConstants->MoveConstantToNewSlot(this, I);
2578 // Update to the new value.
2579 setOperand(OperandToUpdate, ToC);
2584 assert(Replacement != this && "I didn't contain From!");
2586 // Everyone using this now uses the replacement.
2587 uncheckedReplaceAllUsesWith(Replacement);
2589 // Delete the old constant!
2593 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2595 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2597 std::vector<Constant*> Values;
2598 Values.reserve(getNumOperands()); // Build replacement array...
2599 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2600 Constant *Val = getOperand(i);
2601 if (Val == From) Val = cast<Constant>(To);
2602 Values.push_back(Val);
2605 Constant *Replacement = ConstantVector::get(getType(), Values);
2606 assert(Replacement != this && "I didn't contain From!");
2608 // Everyone using this now uses the replacement.
2609 uncheckedReplaceAllUsesWith(Replacement);
2611 // Delete the old constant!
2615 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2617 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2618 Constant *To = cast<Constant>(ToV);
2620 Constant *Replacement = 0;
2621 if (getOpcode() == Instruction::GetElementPtr) {
2622 SmallVector<Constant*, 8> Indices;
2623 Constant *Pointer = getOperand(0);
2624 Indices.reserve(getNumOperands()-1);
2625 if (Pointer == From) Pointer = To;
2627 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2628 Constant *Val = getOperand(i);
2629 if (Val == From) Val = To;
2630 Indices.push_back(Val);
2632 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2633 &Indices[0], Indices.size());
2634 } else if (getOpcode() == Instruction::ExtractValue) {
2635 Constant *Agg = getOperand(0);
2636 if (Agg == From) Agg = To;
2638 const SmallVector<unsigned, 4> &Indices = getIndices();
2639 Replacement = ConstantExpr::getExtractValue(Agg,
2640 &Indices[0], Indices.size());
2641 } else if (getOpcode() == Instruction::InsertValue) {
2642 Constant *Agg = getOperand(0);
2643 Constant *Val = getOperand(1);
2644 if (Agg == From) Agg = To;
2645 if (Val == From) Val = To;
2647 const SmallVector<unsigned, 4> &Indices = getIndices();
2648 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2649 &Indices[0], Indices.size());
2650 } else if (isCast()) {
2651 assert(getOperand(0) == From && "Cast only has one use!");
2652 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2653 } else if (getOpcode() == Instruction::Select) {
2654 Constant *C1 = getOperand(0);
2655 Constant *C2 = getOperand(1);
2656 Constant *C3 = getOperand(2);
2657 if (C1 == From) C1 = To;
2658 if (C2 == From) C2 = To;
2659 if (C3 == From) C3 = To;
2660 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2661 } else if (getOpcode() == Instruction::ExtractElement) {
2662 Constant *C1 = getOperand(0);
2663 Constant *C2 = getOperand(1);
2664 if (C1 == From) C1 = To;
2665 if (C2 == From) C2 = To;
2666 Replacement = ConstantExpr::getExtractElement(C1, C2);
2667 } else if (getOpcode() == Instruction::InsertElement) {
2668 Constant *C1 = getOperand(0);
2669 Constant *C2 = getOperand(1);
2670 Constant *C3 = getOperand(1);
2671 if (C1 == From) C1 = To;
2672 if (C2 == From) C2 = To;
2673 if (C3 == From) C3 = To;
2674 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2675 } else if (getOpcode() == Instruction::ShuffleVector) {
2676 Constant *C1 = getOperand(0);
2677 Constant *C2 = getOperand(1);
2678 Constant *C3 = getOperand(2);
2679 if (C1 == From) C1 = To;
2680 if (C2 == From) C2 = To;
2681 if (C3 == From) C3 = To;
2682 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2683 } else if (isCompare()) {
2684 Constant *C1 = getOperand(0);
2685 Constant *C2 = getOperand(1);
2686 if (C1 == From) C1 = To;
2687 if (C2 == From) C2 = To;
2688 if (getOpcode() == Instruction::ICmp)
2689 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2690 else if (getOpcode() == Instruction::FCmp)
2691 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2692 else if (getOpcode() == Instruction::VICmp)
2693 Replacement = ConstantExpr::getVICmp(getPredicate(), C1, C2);
2695 assert(getOpcode() == Instruction::VFCmp);
2696 Replacement = ConstantExpr::getVFCmp(getPredicate(), C1, C2);
2698 } else if (getNumOperands() == 2) {
2699 Constant *C1 = getOperand(0);
2700 Constant *C2 = getOperand(1);
2701 if (C1 == From) C1 = To;
2702 if (C2 == From) C2 = To;
2703 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2705 assert(0 && "Unknown ConstantExpr type!");
2709 assert(Replacement != this && "I didn't contain From!");
2711 // Everyone using this now uses the replacement.
2712 uncheckedReplaceAllUsesWith(Replacement);
2714 // Delete the old constant!