1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "ConstantFold.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/GlobalValue.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/MDNode.h"
20 #include "llvm/Module.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/System/Mutex.h"
30 #include "llvm/System/RWMutex.h"
31 #include "llvm/System/Threading.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // Becomes a no-op when multithreading is disabled.
43 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
45 void Constant::destroyConstantImpl() {
46 // When a Constant is destroyed, there may be lingering
47 // references to the constant by other constants in the constant pool. These
48 // constants are implicitly dependent on the module that is being deleted,
49 // but they don't know that. Because we only find out when the CPV is
50 // deleted, we must now notify all of our users (that should only be
51 // Constants) that they are, in fact, invalid now and should be deleted.
53 while (!use_empty()) {
54 Value *V = use_back();
55 #ifndef NDEBUG // Only in -g mode...
56 if (!isa<Constant>(V))
57 DOUT << "While deleting: " << *this
58 << "\n\nUse still stuck around after Def is destroyed: "
61 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
62 Constant *CV = cast<Constant>(V);
63 CV->destroyConstant();
65 // The constant should remove itself from our use list...
66 assert((use_empty() || use_back() != V) && "Constant not removed!");
69 // Value has no outstanding references it is safe to delete it now...
73 /// canTrap - Return true if evaluation of this constant could trap. This is
74 /// true for things like constant expressions that could divide by zero.
75 bool Constant::canTrap() const {
76 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
77 // The only thing that could possibly trap are constant exprs.
78 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
79 if (!CE) return false;
81 // ConstantExpr traps if any operands can trap.
82 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
83 if (getOperand(i)->canTrap())
86 // Otherwise, only specific operations can trap.
87 switch (CE->getOpcode()) {
90 case Instruction::UDiv:
91 case Instruction::SDiv:
92 case Instruction::FDiv:
93 case Instruction::URem:
94 case Instruction::SRem:
95 case Instruction::FRem:
96 // Div and rem can trap if the RHS is not known to be non-zero.
97 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
103 /// ContainsRelocations - Return true if the constant value contains relocations
104 /// which cannot be resolved at compile time. Kind argument is used to filter
105 /// only 'interesting' sorts of relocations.
106 bool Constant::ContainsRelocations(unsigned Kind) const {
107 if (const GlobalValue* GV = dyn_cast<GlobalValue>(this)) {
108 bool isLocal = GV->hasLocalLinkage();
109 if ((Kind & Reloc::Local) && isLocal) {
110 // Global has local linkage and 'local' kind of relocations are
115 if ((Kind & Reloc::Global) && !isLocal) {
116 // Global has non-local linkage and 'global' kind of relocations are
124 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
125 if (getOperand(i)->ContainsRelocations(Kind))
131 /// getVectorElements - This method, which is only valid on constant of vector
132 /// type, returns the elements of the vector in the specified smallvector.
133 /// This handles breaking down a vector undef into undef elements, etc. For
134 /// constant exprs and other cases we can't handle, we return an empty vector.
135 void Constant::getVectorElements(LLVMContext &Context,
136 SmallVectorImpl<Constant*> &Elts) const {
137 assert(isa<VectorType>(getType()) && "Not a vector constant!");
139 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
140 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
141 Elts.push_back(CV->getOperand(i));
145 const VectorType *VT = cast<VectorType>(getType());
146 if (isa<ConstantAggregateZero>(this)) {
147 Elts.assign(VT->getNumElements(),
148 Context.getNullValue(VT->getElementType()));
152 if (isa<UndefValue>(this)) {
153 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
157 // Unknown type, must be constant expr etc.
162 //===----------------------------------------------------------------------===//
164 //===----------------------------------------------------------------------===//
166 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
167 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
168 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
171 ConstantInt *ConstantInt::TheTrueVal = 0;
172 ConstantInt *ConstantInt::TheFalseVal = 0;
175 void CleanupTrueFalse(void *) {
176 ConstantInt::ResetTrueFalse();
180 static ManagedCleanup<llvm::CleanupTrueFalse> TrueFalseCleanup;
182 ConstantInt *ConstantInt::CreateTrueFalseVals(bool WhichOne) {
183 assert(TheTrueVal == 0 && TheFalseVal == 0);
184 TheTrueVal = get(Type::Int1Ty, 1);
185 TheFalseVal = get(Type::Int1Ty, 0);
187 // Ensure that llvm_shutdown nulls out TheTrueVal/TheFalseVal.
188 TrueFalseCleanup.Register();
190 return WhichOne ? TheTrueVal : TheFalseVal;
195 struct DenseMapAPIntKeyInfo {
199 KeyTy(const APInt& V, const Type* Ty) : val(V), type(Ty) {}
200 KeyTy(const KeyTy& that) : val(that.val), type(that.type) {}
201 bool operator==(const KeyTy& that) const {
202 return type == that.type && this->val == that.val;
204 bool operator!=(const KeyTy& that) const {
205 return !this->operator==(that);
208 static inline KeyTy getEmptyKey() { return KeyTy(APInt(1,0), 0); }
209 static inline KeyTy getTombstoneKey() { return KeyTy(APInt(1,1), 0); }
210 static unsigned getHashValue(const KeyTy &Key) {
211 return DenseMapInfo<void*>::getHashValue(Key.type) ^
212 Key.val.getHashValue();
214 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
217 static bool isPod() { return false; }
222 typedef DenseMap<DenseMapAPIntKeyInfo::KeyTy, ConstantInt*,
223 DenseMapAPIntKeyInfo> IntMapTy;
224 static ManagedStatic<IntMapTy> IntConstants;
226 ConstantInt *ConstantInt::get(const IntegerType *Ty,
227 uint64_t V, bool isSigned) {
228 return get(APInt(Ty->getBitWidth(), V, isSigned));
231 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
232 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
234 // For vectors, broadcast the value.
235 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
237 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
242 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
243 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
244 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
245 // compare APInt's of different widths, which would violate an APInt class
246 // invariant which generates an assertion.
247 ConstantInt *ConstantInt::get(const APInt& V) {
248 // Get the corresponding integer type for the bit width of the value.
249 const IntegerType *ITy = IntegerType::get(V.getBitWidth());
250 // get an existing value or the insertion position
251 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
253 ConstantsLock->reader_acquire();
254 ConstantInt *&Slot = (*IntConstants)[Key];
255 ConstantsLock->reader_release();
258 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
259 ConstantInt *&NewSlot = (*IntConstants)[Key];
261 NewSlot = new ConstantInt(ITy, V);
270 Constant *ConstantInt::get(const Type *Ty, const APInt &V) {
271 ConstantInt *C = ConstantInt::get(V);
272 assert(C->getType() == Ty->getScalarType() &&
273 "ConstantInt type doesn't match the type implied by its value!");
275 // For vectors, broadcast the value.
276 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
278 ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
283 //===----------------------------------------------------------------------===//
285 //===----------------------------------------------------------------------===//
287 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
288 if (Ty == Type::FloatTy)
289 return &APFloat::IEEEsingle;
290 if (Ty == Type::DoubleTy)
291 return &APFloat::IEEEdouble;
292 if (Ty == Type::X86_FP80Ty)
293 return &APFloat::x87DoubleExtended;
294 else if (Ty == Type::FP128Ty)
295 return &APFloat::IEEEquad;
297 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
298 return &APFloat::PPCDoubleDouble;
301 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
302 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
303 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
307 bool ConstantFP::isNullValue() const {
308 return Val.isZero() && !Val.isNegative();
311 bool ConstantFP::isExactlyValue(const APFloat& V) const {
312 return Val.bitwiseIsEqual(V);
316 struct DenseMapAPFloatKeyInfo {
319 KeyTy(const APFloat& V) : val(V){}
320 KeyTy(const KeyTy& that) : val(that.val) {}
321 bool operator==(const KeyTy& that) const {
322 return this->val.bitwiseIsEqual(that.val);
324 bool operator!=(const KeyTy& that) const {
325 return !this->operator==(that);
328 static inline KeyTy getEmptyKey() {
329 return KeyTy(APFloat(APFloat::Bogus,1));
331 static inline KeyTy getTombstoneKey() {
332 return KeyTy(APFloat(APFloat::Bogus,2));
334 static unsigned getHashValue(const KeyTy &Key) {
335 return Key.val.getHashValue();
337 static bool isEqual(const KeyTy &LHS, const KeyTy &RHS) {
340 static bool isPod() { return false; }
344 //---- ConstantFP::get() implementation...
346 typedef DenseMap<DenseMapAPFloatKeyInfo::KeyTy, ConstantFP*,
347 DenseMapAPFloatKeyInfo> FPMapTy;
349 static ManagedStatic<FPMapTy> FPConstants;
351 ConstantFP *ConstantFP::get(const APFloat &V) {
352 DenseMapAPFloatKeyInfo::KeyTy Key(V);
354 ConstantsLock->reader_acquire();
355 ConstantFP *&Slot = (*FPConstants)[Key];
356 ConstantsLock->reader_release();
359 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
360 ConstantFP *&NewSlot = (*FPConstants)[Key];
363 if (&V.getSemantics() == &APFloat::IEEEsingle)
365 else if (&V.getSemantics() == &APFloat::IEEEdouble)
367 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
368 Ty = Type::X86_FP80Ty;
369 else if (&V.getSemantics() == &APFloat::IEEEquad)
372 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
373 "Unknown FP format");
374 Ty = Type::PPC_FP128Ty;
376 NewSlot = new ConstantFP(Ty, V);
385 //===----------------------------------------------------------------------===//
386 // ConstantXXX Classes
387 //===----------------------------------------------------------------------===//
390 ConstantArray::ConstantArray(const ArrayType *T,
391 const std::vector<Constant*> &V)
392 : Constant(T, ConstantArrayVal,
393 OperandTraits<ConstantArray>::op_end(this) - V.size(),
395 assert(V.size() == T->getNumElements() &&
396 "Invalid initializer vector for constant array");
397 Use *OL = OperandList;
398 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
401 assert((C->getType() == T->getElementType() ||
403 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
404 "Initializer for array element doesn't match array element type!");
410 ConstantStruct::ConstantStruct(const StructType *T,
411 const std::vector<Constant*> &V)
412 : Constant(T, ConstantStructVal,
413 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
415 assert(V.size() == T->getNumElements() &&
416 "Invalid initializer vector for constant structure");
417 Use *OL = OperandList;
418 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
421 assert((C->getType() == T->getElementType(I-V.begin()) ||
422 ((T->getElementType(I-V.begin())->isAbstract() ||
423 C->getType()->isAbstract()) &&
424 T->getElementType(I-V.begin())->getTypeID() ==
425 C->getType()->getTypeID())) &&
426 "Initializer for struct element doesn't match struct element type!");
432 ConstantVector::ConstantVector(const VectorType *T,
433 const std::vector<Constant*> &V)
434 : Constant(T, ConstantVectorVal,
435 OperandTraits<ConstantVector>::op_end(this) - V.size(),
437 Use *OL = OperandList;
438 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
441 assert((C->getType() == T->getElementType() ||
443 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
444 "Initializer for vector element doesn't match vector element type!");
451 // We declare several classes private to this file, so use an anonymous
455 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
456 /// behind the scenes to implement unary constant exprs.
457 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
458 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
460 // allocate space for exactly one operand
461 void *operator new(size_t s) {
462 return User::operator new(s, 1);
464 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
465 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
468 /// Transparently provide more efficient getOperand methods.
469 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
472 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
473 /// behind the scenes to implement binary constant exprs.
474 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
475 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
477 // allocate space for exactly two operands
478 void *operator new(size_t s) {
479 return User::operator new(s, 2);
481 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
482 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
486 /// Transparently provide more efficient getOperand methods.
487 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
490 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
491 /// behind the scenes to implement select constant exprs.
492 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
493 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
495 // allocate space for exactly three operands
496 void *operator new(size_t s) {
497 return User::operator new(s, 3);
499 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
500 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
505 /// Transparently provide more efficient getOperand methods.
506 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
509 /// ExtractElementConstantExpr - This class is private to
510 /// Constants.cpp, and is used behind the scenes to implement
511 /// extractelement constant exprs.
512 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
513 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
515 // allocate space for exactly two operands
516 void *operator new(size_t s) {
517 return User::operator new(s, 2);
519 ExtractElementConstantExpr(Constant *C1, Constant *C2)
520 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
521 Instruction::ExtractElement, &Op<0>(), 2) {
525 /// Transparently provide more efficient getOperand methods.
526 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
529 /// InsertElementConstantExpr - This class is private to
530 /// Constants.cpp, and is used behind the scenes to implement
531 /// insertelement constant exprs.
532 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
533 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
535 // allocate space for exactly three operands
536 void *operator new(size_t s) {
537 return User::operator new(s, 3);
539 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
540 : ConstantExpr(C1->getType(), Instruction::InsertElement,
546 /// Transparently provide more efficient getOperand methods.
547 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
550 /// ShuffleVectorConstantExpr - This class is private to
551 /// Constants.cpp, and is used behind the scenes to implement
552 /// shufflevector constant exprs.
553 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
554 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
556 // allocate space for exactly three operands
557 void *operator new(size_t s) {
558 return User::operator new(s, 3);
560 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
561 : ConstantExpr(VectorType::get(
562 cast<VectorType>(C1->getType())->getElementType(),
563 cast<VectorType>(C3->getType())->getNumElements()),
564 Instruction::ShuffleVector,
570 /// Transparently provide more efficient getOperand methods.
571 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
574 /// ExtractValueConstantExpr - This class is private to
575 /// Constants.cpp, and is used behind the scenes to implement
576 /// extractvalue constant exprs.
577 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
578 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
580 // allocate space for exactly one operand
581 void *operator new(size_t s) {
582 return User::operator new(s, 1);
584 ExtractValueConstantExpr(Constant *Agg,
585 const SmallVector<unsigned, 4> &IdxList,
587 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
592 /// Indices - These identify which value to extract.
593 const SmallVector<unsigned, 4> Indices;
595 /// Transparently provide more efficient getOperand methods.
596 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
599 /// InsertValueConstantExpr - This class is private to
600 /// Constants.cpp, and is used behind the scenes to implement
601 /// insertvalue constant exprs.
602 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
603 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
605 // allocate space for exactly one operand
606 void *operator new(size_t s) {
607 return User::operator new(s, 2);
609 InsertValueConstantExpr(Constant *Agg, Constant *Val,
610 const SmallVector<unsigned, 4> &IdxList,
612 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
618 /// Indices - These identify the position for the insertion.
619 const SmallVector<unsigned, 4> Indices;
621 /// Transparently provide more efficient getOperand methods.
622 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
626 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
627 /// used behind the scenes to implement getelementpr constant exprs.
628 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
629 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
632 static GetElementPtrConstantExpr *Create(Constant *C,
633 const std::vector<Constant*>&IdxList,
634 const Type *DestTy) {
635 return new(IdxList.size() + 1)
636 GetElementPtrConstantExpr(C, IdxList, DestTy);
638 /// Transparently provide more efficient getOperand methods.
639 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
642 // CompareConstantExpr - This class is private to Constants.cpp, and is used
643 // behind the scenes to implement ICmp and FCmp constant expressions. This is
644 // needed in order to store the predicate value for these instructions.
645 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
646 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
647 // allocate space for exactly two operands
648 void *operator new(size_t s) {
649 return User::operator new(s, 2);
651 unsigned short predicate;
652 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
653 unsigned short pred, Constant* LHS, Constant* RHS)
654 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
658 /// Transparently provide more efficient getOperand methods.
659 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
662 } // end anonymous namespace
665 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
667 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
670 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
672 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
675 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
677 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
680 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
682 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
685 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
687 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
690 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
692 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
695 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
697 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
700 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
702 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
705 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
708 GetElementPtrConstantExpr::GetElementPtrConstantExpr
710 const std::vector<Constant*> &IdxList,
712 : ConstantExpr(DestTy, Instruction::GetElementPtr,
713 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
714 - (IdxList.size()+1),
717 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
718 OperandList[i+1] = IdxList[i];
721 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
725 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
727 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
730 } // End llvm namespace
733 // Utility function for determining if a ConstantExpr is a CastOp or not. This
734 // can't be inline because we don't want to #include Instruction.h into
736 bool ConstantExpr::isCast() const {
737 return Instruction::isCast(getOpcode());
740 bool ConstantExpr::isCompare() const {
741 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
744 bool ConstantExpr::hasIndices() const {
745 return getOpcode() == Instruction::ExtractValue ||
746 getOpcode() == Instruction::InsertValue;
749 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
750 if (const ExtractValueConstantExpr *EVCE =
751 dyn_cast<ExtractValueConstantExpr>(this))
752 return EVCE->Indices;
754 return cast<InsertValueConstantExpr>(this)->Indices;
757 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2) {
758 return get(Instruction::Add, C1, C2);
760 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
761 return get(Instruction::FAdd, C1, C2);
763 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2) {
764 return get(Instruction::Sub, C1, C2);
766 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
767 return get(Instruction::FSub, C1, C2);
769 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2) {
770 return get(Instruction::Mul, C1, C2);
772 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
773 return get(Instruction::FMul, 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 return ((const CompareConstantExpr*)this)->predicate;
807 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2) {
808 return get(Instruction::Shl, C1, C2);
810 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2) {
811 return get(Instruction::LShr, C1, C2);
813 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2) {
814 return get(Instruction::AShr, C1, C2);
817 /// getWithOperandReplaced - Return a constant expression identical to this
818 /// one, but with the specified operand set to the specified value.
820 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
821 assert(OpNo < getNumOperands() && "Operand num is out of range!");
822 assert(Op->getType() == getOperand(OpNo)->getType() &&
823 "Replacing operand with value of different type!");
824 if (getOperand(OpNo) == Op)
825 return const_cast<ConstantExpr*>(this);
827 Constant *Op0, *Op1, *Op2;
828 switch (getOpcode()) {
829 case Instruction::Trunc:
830 case Instruction::ZExt:
831 case Instruction::SExt:
832 case Instruction::FPTrunc:
833 case Instruction::FPExt:
834 case Instruction::UIToFP:
835 case Instruction::SIToFP:
836 case Instruction::FPToUI:
837 case Instruction::FPToSI:
838 case Instruction::PtrToInt:
839 case Instruction::IntToPtr:
840 case Instruction::BitCast:
841 return ConstantExpr::getCast(getOpcode(), Op, getType());
842 case Instruction::Select:
843 Op0 = (OpNo == 0) ? Op : getOperand(0);
844 Op1 = (OpNo == 1) ? Op : getOperand(1);
845 Op2 = (OpNo == 2) ? Op : getOperand(2);
846 return ConstantExpr::getSelect(Op0, Op1, Op2);
847 case Instruction::InsertElement:
848 Op0 = (OpNo == 0) ? Op : getOperand(0);
849 Op1 = (OpNo == 1) ? Op : getOperand(1);
850 Op2 = (OpNo == 2) ? Op : getOperand(2);
851 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
852 case Instruction::ExtractElement:
853 Op0 = (OpNo == 0) ? Op : getOperand(0);
854 Op1 = (OpNo == 1) ? Op : getOperand(1);
855 return ConstantExpr::getExtractElement(Op0, Op1);
856 case Instruction::ShuffleVector:
857 Op0 = (OpNo == 0) ? Op : getOperand(0);
858 Op1 = (OpNo == 1) ? Op : getOperand(1);
859 Op2 = (OpNo == 2) ? Op : getOperand(2);
860 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
861 case Instruction::GetElementPtr: {
862 SmallVector<Constant*, 8> Ops;
863 Ops.resize(getNumOperands()-1);
864 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
865 Ops[i-1] = getOperand(i);
867 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
869 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
872 assert(getNumOperands() == 2 && "Must be binary operator?");
873 Op0 = (OpNo == 0) ? Op : getOperand(0);
874 Op1 = (OpNo == 1) ? Op : getOperand(1);
875 return ConstantExpr::get(getOpcode(), Op0, Op1);
879 /// getWithOperands - This returns the current constant expression with the
880 /// operands replaced with the specified values. The specified operands must
881 /// match count and type with the existing ones.
882 Constant *ConstantExpr::
883 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
884 assert(NumOps == getNumOperands() && "Operand count mismatch!");
885 bool AnyChange = false;
886 for (unsigned i = 0; i != NumOps; ++i) {
887 assert(Ops[i]->getType() == getOperand(i)->getType() &&
888 "Operand type mismatch!");
889 AnyChange |= Ops[i] != getOperand(i);
891 if (!AnyChange) // No operands changed, return self.
892 return const_cast<ConstantExpr*>(this);
894 switch (getOpcode()) {
895 case Instruction::Trunc:
896 case Instruction::ZExt:
897 case Instruction::SExt:
898 case Instruction::FPTrunc:
899 case Instruction::FPExt:
900 case Instruction::UIToFP:
901 case Instruction::SIToFP:
902 case Instruction::FPToUI:
903 case Instruction::FPToSI:
904 case Instruction::PtrToInt:
905 case Instruction::IntToPtr:
906 case Instruction::BitCast:
907 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
908 case Instruction::Select:
909 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
910 case Instruction::InsertElement:
911 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
912 case Instruction::ExtractElement:
913 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
914 case Instruction::ShuffleVector:
915 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
916 case Instruction::GetElementPtr:
917 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
918 case Instruction::ICmp:
919 case Instruction::FCmp:
920 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
922 assert(getNumOperands() == 2 && "Must be binary operator?");
923 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
928 //===----------------------------------------------------------------------===//
929 // isValueValidForType implementations
931 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
932 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
933 if (Ty == Type::Int1Ty)
934 return Val == 0 || Val == 1;
936 return true; // always true, has to fit in largest type
937 uint64_t Max = (1ll << NumBits) - 1;
941 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
942 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
943 if (Ty == Type::Int1Ty)
944 return Val == 0 || Val == 1 || Val == -1;
946 return true; // always true, has to fit in largest type
947 int64_t Min = -(1ll << (NumBits-1));
948 int64_t Max = (1ll << (NumBits-1)) - 1;
949 return (Val >= Min && Val <= Max);
952 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
953 // convert modifies in place, so make a copy.
954 APFloat Val2 = APFloat(Val);
956 switch (Ty->getTypeID()) {
958 return false; // These can't be represented as floating point!
960 // FIXME rounding mode needs to be more flexible
961 case Type::FloatTyID: {
962 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
964 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
967 case Type::DoubleTyID: {
968 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
969 &Val2.getSemantics() == &APFloat::IEEEdouble)
971 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
974 case Type::X86_FP80TyID:
975 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
976 &Val2.getSemantics() == &APFloat::IEEEdouble ||
977 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
978 case Type::FP128TyID:
979 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
980 &Val2.getSemantics() == &APFloat::IEEEdouble ||
981 &Val2.getSemantics() == &APFloat::IEEEquad;
982 case Type::PPC_FP128TyID:
983 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
984 &Val2.getSemantics() == &APFloat::IEEEdouble ||
985 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
989 //===----------------------------------------------------------------------===//
990 // Factory Function Implementation
993 // The number of operands for each ConstantCreator::create method is
994 // determined by the ConstantTraits template.
995 // ConstantCreator - A class that is used to create constants by
996 // ValueMap*. This class should be partially specialized if there is
997 // something strange that needs to be done to interface to the ctor for the
1001 template<class ValType>
1002 struct ConstantTraits;
1004 template<typename T, typename Alloc>
1005 struct VISIBILITY_HIDDEN ConstantTraits< std::vector<T, Alloc> > {
1006 static unsigned uses(const std::vector<T, Alloc>& v) {
1011 template<class ConstantClass, class TypeClass, class ValType>
1012 struct VISIBILITY_HIDDEN ConstantCreator {
1013 static ConstantClass *create(const TypeClass *Ty, const ValType &V) {
1014 return new(ConstantTraits<ValType>::uses(V)) ConstantClass(Ty, V);
1018 template<class ConstantClass, class TypeClass>
1019 struct VISIBILITY_HIDDEN ConvertConstantType {
1020 static void convert(ConstantClass *OldC, const TypeClass *NewTy) {
1021 LLVM_UNREACHABLE("This type cannot be converted!");
1025 template<class ValType, class TypeClass, class ConstantClass,
1026 bool HasLargeKey = false /*true for arrays and structs*/ >
1027 class VISIBILITY_HIDDEN ValueMap : public AbstractTypeUser {
1029 typedef std::pair<const Type*, ValType> MapKey;
1030 typedef std::map<MapKey, Constant *> MapTy;
1031 typedef std::map<Constant*, typename MapTy::iterator> InverseMapTy;
1032 typedef std::map<const Type*, typename MapTy::iterator> AbstractTypeMapTy;
1034 /// Map - This is the main map from the element descriptor to the Constants.
1035 /// This is the primary way we avoid creating two of the same shape
1039 /// InverseMap - If "HasLargeKey" is true, this contains an inverse mapping
1040 /// from the constants to their element in Map. This is important for
1041 /// removal of constants from the array, which would otherwise have to scan
1042 /// through the map with very large keys.
1043 InverseMapTy InverseMap;
1045 /// AbstractTypeMap - Map for abstract type constants.
1047 AbstractTypeMapTy AbstractTypeMap;
1049 /// ValueMapLock - Mutex for this map.
1050 sys::SmartMutex<true> ValueMapLock;
1053 // NOTE: This function is not locked. It is the caller's responsibility
1054 // to enforce proper synchronization.
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 /// NOTE: This function is not locked. It is the caller's responsibility
1063 // to enforce proper synchronization.
1064 typename MapTy::iterator InsertOrGetItem(std::pair<MapKey, Constant *>
1067 std::pair<typename MapTy::iterator, bool> IP = Map.insert(InsertVal);
1068 Exists = !IP.second;
1073 typename MapTy::iterator FindExistingElement(ConstantClass *CP) {
1075 typename InverseMapTy::iterator IMI = InverseMap.find(CP);
1076 assert(IMI != InverseMap.end() && IMI->second != Map.end() &&
1077 IMI->second->second == CP &&
1078 "InverseMap corrupt!");
1082 typename MapTy::iterator I =
1083 Map.find(MapKey(static_cast<const TypeClass*>(CP->getRawType()),
1085 if (I == Map.end() || I->second != CP) {
1086 // FIXME: This should not use a linear scan. If this gets to be a
1087 // performance problem, someone should look at this.
1088 for (I = Map.begin(); I != Map.end() && I->second != CP; ++I)
1094 ConstantClass* Create(const TypeClass *Ty, const ValType &V,
1095 typename MapTy::iterator I) {
1096 ConstantClass* Result =
1097 ConstantCreator<ConstantClass,TypeClass,ValType>::create(Ty, V);
1099 assert(Result->getType() == Ty && "Type specified is not correct!");
1100 I = Map.insert(I, std::make_pair(MapKey(Ty, V), Result));
1102 if (HasLargeKey) // Remember the reverse mapping if needed.
1103 InverseMap.insert(std::make_pair(Result, I));
1105 // If the type of the constant is abstract, make sure that an entry
1106 // exists for it in the AbstractTypeMap.
1107 if (Ty->isAbstract()) {
1108 typename AbstractTypeMapTy::iterator TI =
1109 AbstractTypeMap.find(Ty);
1111 if (TI == AbstractTypeMap.end()) {
1112 // Add ourselves to the ATU list of the type.
1113 cast<DerivedType>(Ty)->addAbstractTypeUser(this);
1115 AbstractTypeMap.insert(TI, std::make_pair(Ty, I));
1123 /// getOrCreate - Return the specified constant from the map, creating it if
1125 ConstantClass *getOrCreate(const TypeClass *Ty, const ValType &V) {
1126 sys::SmartScopedLock<true> Lock(ValueMapLock);
1127 MapKey Lookup(Ty, V);
1128 ConstantClass* Result = 0;
1130 typename MapTy::iterator I = Map.find(Lookup);
1131 // Is it in the map?
1133 Result = static_cast<ConstantClass *>(I->second);
1136 // If no preexisting value, create one now...
1137 Result = Create(Ty, V, I);
1143 void remove(ConstantClass *CP) {
1144 sys::SmartScopedLock<true> Lock(ValueMapLock);
1145 typename MapTy::iterator I = FindExistingElement(CP);
1146 assert(I != Map.end() && "Constant not found in constant table!");
1147 assert(I->second == CP && "Didn't find correct element?");
1149 if (HasLargeKey) // Remember the reverse mapping if needed.
1150 InverseMap.erase(CP);
1152 // Now that we found the entry, make sure this isn't the entry that
1153 // the AbstractTypeMap points to.
1154 const TypeClass *Ty = static_cast<const TypeClass *>(I->first.first);
1155 if (Ty->isAbstract()) {
1156 assert(AbstractTypeMap.count(Ty) &&
1157 "Abstract type not in AbstractTypeMap?");
1158 typename MapTy::iterator &ATMEntryIt = AbstractTypeMap[Ty];
1159 if (ATMEntryIt == I) {
1160 // Yes, we are removing the representative entry for this type.
1161 // See if there are any other entries of the same type.
1162 typename MapTy::iterator TmpIt = ATMEntryIt;
1164 // First check the entry before this one...
1165 if (TmpIt != Map.begin()) {
1167 if (TmpIt->first.first != Ty) // Not the same type, move back...
1171 // If we didn't find the same type, try to move forward...
1172 if (TmpIt == ATMEntryIt) {
1174 if (TmpIt == Map.end() || TmpIt->first.first != Ty)
1175 --TmpIt; // No entry afterwards with the same type
1178 // If there is another entry in the map of the same abstract type,
1179 // update the AbstractTypeMap entry now.
1180 if (TmpIt != ATMEntryIt) {
1183 // Otherwise, we are removing the last instance of this type
1184 // from the table. Remove from the ATM, and from user list.
1185 cast<DerivedType>(Ty)->removeAbstractTypeUser(this);
1186 AbstractTypeMap.erase(Ty);
1195 /// MoveConstantToNewSlot - If we are about to change C to be the element
1196 /// specified by I, update our internal data structures to reflect this
1198 /// NOTE: This function is not locked. It is the responsibility of the
1199 /// caller to enforce proper synchronization if using this method.
1200 void MoveConstantToNewSlot(ConstantClass *C, typename MapTy::iterator I) {
1201 // First, remove the old location of the specified constant in the map.
1202 typename MapTy::iterator OldI = FindExistingElement(C);
1203 assert(OldI != Map.end() && "Constant not found in constant table!");
1204 assert(OldI->second == C && "Didn't find correct element?");
1206 // If this constant is the representative element for its abstract type,
1207 // update the AbstractTypeMap so that the representative element is I.
1208 if (C->getType()->isAbstract()) {
1209 typename AbstractTypeMapTy::iterator ATI =
1210 AbstractTypeMap.find(C->getType());
1211 assert(ATI != AbstractTypeMap.end() &&
1212 "Abstract type not in AbstractTypeMap?");
1213 if (ATI->second == OldI)
1217 // Remove the old entry from the map.
1220 // Update the inverse map so that we know that this constant is now
1221 // located at descriptor I.
1223 assert(I->second == C && "Bad inversemap entry!");
1228 void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
1229 sys::SmartScopedLock<true> Lock(ValueMapLock);
1230 typename AbstractTypeMapTy::iterator I =
1231 AbstractTypeMap.find(cast<Type>(OldTy));
1233 assert(I != AbstractTypeMap.end() &&
1234 "Abstract type not in AbstractTypeMap?");
1236 // Convert a constant at a time until the last one is gone. The last one
1237 // leaving will remove() itself, causing the AbstractTypeMapEntry to be
1238 // eliminated eventually.
1240 ConvertConstantType<ConstantClass,
1241 TypeClass>::convert(
1242 static_cast<ConstantClass *>(I->second->second),
1243 cast<TypeClass>(NewTy));
1245 I = AbstractTypeMap.find(cast<Type>(OldTy));
1246 } while (I != AbstractTypeMap.end());
1249 // If the type became concrete without being refined to any other existing
1250 // type, we just remove ourselves from the ATU list.
1251 void typeBecameConcrete(const DerivedType *AbsTy) {
1252 AbsTy->removeAbstractTypeUser(this);
1256 DOUT << "Constant.cpp: ValueMap\n";
1263 //---- ConstantAggregateZero::get() implementation...
1266 // ConstantAggregateZero does not take extra "value" argument...
1267 template<class ValType>
1268 struct ConstantCreator<ConstantAggregateZero, Type, ValType> {
1269 static ConstantAggregateZero *create(const Type *Ty, const ValType &V){
1270 return new ConstantAggregateZero(Ty);
1275 struct ConvertConstantType<ConstantAggregateZero, Type> {
1276 static void convert(ConstantAggregateZero *OldC, const Type *NewTy) {
1277 // Make everyone now use a constant of the new type...
1278 Constant *New = ConstantAggregateZero::get(NewTy);
1279 assert(New != OldC && "Didn't replace constant??");
1280 OldC->uncheckedReplaceAllUsesWith(New);
1281 OldC->destroyConstant(); // This constant is now dead, destroy it.
1286 static ManagedStatic<ValueMap<char, Type,
1287 ConstantAggregateZero> > AggZeroConstants;
1289 static char getValType(ConstantAggregateZero *CPZ) { return 0; }
1291 ConstantAggregateZero *ConstantAggregateZero::get(const Type *Ty) {
1292 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
1293 "Cannot create an aggregate zero of non-aggregate type!");
1295 // Implicitly locked.
1296 return AggZeroConstants->getOrCreate(Ty, 0);
1299 /// destroyConstant - Remove the constant from the constant table...
1301 void ConstantAggregateZero::destroyConstant() {
1302 // Implicitly locked.
1303 AggZeroConstants->remove(this);
1304 destroyConstantImpl();
1307 //---- ConstantArray::get() implementation...
1311 struct ConvertConstantType<ConstantArray, ArrayType> {
1312 static void convert(ConstantArray *OldC, const ArrayType *NewTy) {
1313 // Make everyone now use a constant of the new type...
1314 std::vector<Constant*> C;
1315 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1316 C.push_back(cast<Constant>(OldC->getOperand(i)));
1317 Constant *New = ConstantArray::get(NewTy, C);
1318 assert(New != OldC && "Didn't replace constant??");
1319 OldC->uncheckedReplaceAllUsesWith(New);
1320 OldC->destroyConstant(); // This constant is now dead, destroy it.
1325 static std::vector<Constant*> getValType(ConstantArray *CA) {
1326 std::vector<Constant*> Elements;
1327 Elements.reserve(CA->getNumOperands());
1328 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1329 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1333 typedef ValueMap<std::vector<Constant*>, ArrayType,
1334 ConstantArray, true /*largekey*/> ArrayConstantsTy;
1335 static ManagedStatic<ArrayConstantsTy> ArrayConstants;
1337 Constant *ConstantArray::get(const ArrayType *Ty,
1338 const std::vector<Constant*> &V) {
1339 // If this is an all-zero array, return a ConstantAggregateZero object
1342 if (!C->isNullValue()) {
1343 // Implicitly locked.
1344 return ArrayConstants->getOrCreate(Ty, V);
1346 for (unsigned i = 1, e = V.size(); i != e; ++i)
1348 // Implicitly locked.
1349 return ArrayConstants->getOrCreate(Ty, V);
1353 return ConstantAggregateZero::get(Ty);
1356 /// destroyConstant - Remove the constant from the constant table...
1358 void ConstantArray::destroyConstant() {
1359 // Implicitly locked.
1360 ArrayConstants->remove(this);
1361 destroyConstantImpl();
1364 /// ConstantArray::get(const string&) - Return an array that is initialized to
1365 /// contain the specified string. If length is zero then a null terminator is
1366 /// added to the specified string so that it may be used in a natural way.
1367 /// Otherwise, the length parameter specifies how much of the string to use
1368 /// and it won't be null terminated.
1370 Constant *ConstantArray::get(const std::string &Str, bool AddNull) {
1371 std::vector<Constant*> ElementVals;
1372 for (unsigned i = 0; i < Str.length(); ++i)
1373 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
1375 // Add a null terminator to the string...
1377 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
1380 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
1381 return ConstantArray::get(ATy, ElementVals);
1384 /// isString - This method returns true if the array is an array of i8, and
1385 /// if the elements of the array are all ConstantInt's.
1386 bool ConstantArray::isString() const {
1387 // Check the element type for i8...
1388 if (getType()->getElementType() != Type::Int8Ty)
1390 // Check the elements to make sure they are all integers, not constant
1392 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1393 if (!isa<ConstantInt>(getOperand(i)))
1398 /// isCString - This method returns true if the array is a string (see
1399 /// isString) and it ends in a null byte \\0 and does not contains any other
1400 /// null bytes except its terminator.
1401 bool ConstantArray::isCString() const {
1402 // Check the element type for i8...
1403 if (getType()->getElementType() != Type::Int8Ty)
1406 // Last element must be a null.
1407 if (!getOperand(getNumOperands()-1)->isNullValue())
1409 // Other elements must be non-null integers.
1410 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1411 if (!isa<ConstantInt>(getOperand(i)))
1413 if (getOperand(i)->isNullValue())
1420 /// getAsString - If the sub-element type of this array is i8
1421 /// then this method converts the array to an std::string and returns it.
1422 /// Otherwise, it asserts out.
1424 std::string ConstantArray::getAsString() const {
1425 assert(isString() && "Not a string!");
1427 Result.reserve(getNumOperands());
1428 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1429 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1434 //---- ConstantStruct::get() implementation...
1439 struct ConvertConstantType<ConstantStruct, StructType> {
1440 static void convert(ConstantStruct *OldC, const StructType *NewTy) {
1441 // Make everyone now use a constant of the new type...
1442 std::vector<Constant*> C;
1443 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1444 C.push_back(cast<Constant>(OldC->getOperand(i)));
1445 Constant *New = ConstantStruct::get(NewTy, C);
1446 assert(New != OldC && "Didn't replace constant??");
1448 OldC->uncheckedReplaceAllUsesWith(New);
1449 OldC->destroyConstant(); // This constant is now dead, destroy it.
1454 typedef ValueMap<std::vector<Constant*>, StructType,
1455 ConstantStruct, true /*largekey*/> StructConstantsTy;
1456 static ManagedStatic<StructConstantsTy> StructConstants;
1458 static std::vector<Constant*> getValType(ConstantStruct *CS) {
1459 std::vector<Constant*> Elements;
1460 Elements.reserve(CS->getNumOperands());
1461 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1462 Elements.push_back(cast<Constant>(CS->getOperand(i)));
1466 Constant *ConstantStruct::get(const StructType *Ty,
1467 const std::vector<Constant*> &V) {
1468 // Create a ConstantAggregateZero value if all elements are zeros...
1469 for (unsigned i = 0, e = V.size(); i != e; ++i)
1470 if (!V[i]->isNullValue())
1471 // Implicitly locked.
1472 return StructConstants->getOrCreate(Ty, V);
1474 return ConstantAggregateZero::get(Ty);
1477 Constant *ConstantStruct::get(const std::vector<Constant*> &V, bool packed) {
1478 std::vector<const Type*> StructEls;
1479 StructEls.reserve(V.size());
1480 for (unsigned i = 0, e = V.size(); i != e; ++i)
1481 StructEls.push_back(V[i]->getType());
1482 return get(StructType::get(StructEls, packed), V);
1485 // destroyConstant - Remove the constant from the constant table...
1487 void ConstantStruct::destroyConstant() {
1488 // Implicitly locked.
1489 StructConstants->remove(this);
1490 destroyConstantImpl();
1493 //---- ConstantVector::get() implementation...
1497 struct ConvertConstantType<ConstantVector, VectorType> {
1498 static void convert(ConstantVector *OldC, const VectorType *NewTy) {
1499 // Make everyone now use a constant of the new type...
1500 std::vector<Constant*> C;
1501 for (unsigned i = 0, e = OldC->getNumOperands(); i != e; ++i)
1502 C.push_back(cast<Constant>(OldC->getOperand(i)));
1503 Constant *New = ConstantVector::get(NewTy, C);
1504 assert(New != OldC && "Didn't replace constant??");
1505 OldC->uncheckedReplaceAllUsesWith(New);
1506 OldC->destroyConstant(); // This constant is now dead, destroy it.
1511 static std::vector<Constant*> getValType(ConstantVector *CP) {
1512 std::vector<Constant*> Elements;
1513 Elements.reserve(CP->getNumOperands());
1514 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
1515 Elements.push_back(CP->getOperand(i));
1519 static ManagedStatic<ValueMap<std::vector<Constant*>, VectorType,
1520 ConstantVector> > VectorConstants;
1522 Constant *ConstantVector::get(const VectorType *Ty,
1523 const std::vector<Constant*> &V) {
1524 assert(!V.empty() && "Vectors can't be empty");
1525 // If this is an all-undef or alll-zero vector, return a
1526 // ConstantAggregateZero or UndefValue.
1528 bool isZero = C->isNullValue();
1529 bool isUndef = isa<UndefValue>(C);
1531 if (isZero || isUndef) {
1532 for (unsigned i = 1, e = V.size(); i != e; ++i)
1534 isZero = isUndef = false;
1540 return ConstantAggregateZero::get(Ty);
1542 return UndefValue::get(Ty);
1544 // Implicitly locked.
1545 return VectorConstants->getOrCreate(Ty, V);
1548 Constant *ConstantVector::get(const std::vector<Constant*> &V) {
1549 assert(!V.empty() && "Cannot infer type if V is empty");
1550 return get(VectorType::get(V.front()->getType(),V.size()), V);
1553 // destroyConstant - Remove the constant from the constant table...
1555 void ConstantVector::destroyConstant() {
1556 // Implicitly locked.
1557 VectorConstants->remove(this);
1558 destroyConstantImpl();
1561 /// This function will return true iff every element in this vector constant
1562 /// is set to all ones.
1563 /// @returns true iff this constant's emements are all set to all ones.
1564 /// @brief Determine if the value is all ones.
1565 bool ConstantVector::isAllOnesValue() const {
1566 // Check out first element.
1567 const Constant *Elt = getOperand(0);
1568 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1569 if (!CI || !CI->isAllOnesValue()) return false;
1570 // Then make sure all remaining elements point to the same value.
1571 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1572 if (getOperand(I) != Elt) return false;
1577 /// getSplatValue - If this is a splat constant, where all of the
1578 /// elements have the same value, return that value. Otherwise return null.
1579 Constant *ConstantVector::getSplatValue() {
1580 // Check out first element.
1581 Constant *Elt = getOperand(0);
1582 // Then make sure all remaining elements point to the same value.
1583 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1584 if (getOperand(I) != Elt) return 0;
1588 //---- ConstantPointerNull::get() implementation...
1592 // ConstantPointerNull does not take extra "value" argument...
1593 template<class ValType>
1594 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1595 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1596 return new ConstantPointerNull(Ty);
1601 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1602 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1603 // Make everyone now use a constant of the new type...
1604 Constant *New = ConstantPointerNull::get(NewTy);
1605 assert(New != OldC && "Didn't replace constant??");
1606 OldC->uncheckedReplaceAllUsesWith(New);
1607 OldC->destroyConstant(); // This constant is now dead, destroy it.
1612 static ManagedStatic<ValueMap<char, PointerType,
1613 ConstantPointerNull> > NullPtrConstants;
1615 static char getValType(ConstantPointerNull *) {
1620 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1621 // Implicitly locked.
1622 return NullPtrConstants->getOrCreate(Ty, 0);
1625 // destroyConstant - Remove the constant from the constant table...
1627 void ConstantPointerNull::destroyConstant() {
1628 // Implicitly locked.
1629 NullPtrConstants->remove(this);
1630 destroyConstantImpl();
1634 //---- UndefValue::get() implementation...
1638 // UndefValue does not take extra "value" argument...
1639 template<class ValType>
1640 struct ConstantCreator<UndefValue, Type, ValType> {
1641 static UndefValue *create(const Type *Ty, const ValType &V) {
1642 return new UndefValue(Ty);
1647 struct ConvertConstantType<UndefValue, Type> {
1648 static void convert(UndefValue *OldC, const Type *NewTy) {
1649 // Make everyone now use a constant of the new type.
1650 Constant *New = UndefValue::get(NewTy);
1651 assert(New != OldC && "Didn't replace constant??");
1652 OldC->uncheckedReplaceAllUsesWith(New);
1653 OldC->destroyConstant(); // This constant is now dead, destroy it.
1658 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1660 static char getValType(UndefValue *) {
1665 UndefValue *UndefValue::get(const Type *Ty) {
1666 // Implicitly locked.
1667 return UndefValueConstants->getOrCreate(Ty, 0);
1670 // destroyConstant - Remove the constant from the constant table.
1672 void UndefValue::destroyConstant() {
1673 // Implicitly locked.
1674 UndefValueConstants->remove(this);
1675 destroyConstantImpl();
1678 //---- MDString::get() implementation
1681 MDString::MDString(const char *begin, const char *end)
1682 : Constant(Type::MetadataTy, MDStringVal, 0, 0),
1683 StrBegin(begin), StrEnd(end) {}
1685 static ManagedStatic<StringMap<MDString*> > MDStringCache;
1687 MDString *MDString::get(const char *StrBegin, const char *StrEnd) {
1688 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1689 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1691 MDString *&S = Entry.getValue();
1692 if (!S) S = new MDString(Entry.getKeyData(),
1693 Entry.getKeyData() + Entry.getKeyLength());
1698 MDString *MDString::get(const std::string &Str) {
1699 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1700 StringMapEntry<MDString *> &Entry = MDStringCache->GetOrCreateValue(
1701 Str.data(), Str.data() + Str.size());
1702 MDString *&S = Entry.getValue();
1703 if (!S) S = new MDString(Entry.getKeyData(),
1704 Entry.getKeyData() + Entry.getKeyLength());
1709 void MDString::destroyConstant() {
1710 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1711 MDStringCache->erase(MDStringCache->find(StrBegin, StrEnd));
1712 destroyConstantImpl();
1715 //---- MDNode::get() implementation
1718 static ManagedStatic<FoldingSet<MDNode> > MDNodeSet;
1720 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1721 : Constant(Type::MetadataTy, MDNodeVal, 0, 0) {
1722 for (unsigned i = 0; i != NumVals; ++i)
1723 Node.push_back(ElementVH(Vals[i], this));
1726 void MDNode::Profile(FoldingSetNodeID &ID) const {
1727 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1731 MDNode *MDNode::get(Value*const* Vals, unsigned NumVals) {
1732 FoldingSetNodeID ID;
1733 for (unsigned i = 0; i != NumVals; ++i)
1734 ID.AddPointer(Vals[i]);
1736 ConstantsLock->reader_acquire();
1738 MDNode *N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1739 ConstantsLock->reader_release();
1742 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1743 N = MDNodeSet->FindNodeOrInsertPos(ID, InsertPoint);
1745 // InsertPoint will have been set by the FindNodeOrInsertPos call.
1746 N = new(0) MDNode(Vals, NumVals);
1747 MDNodeSet->InsertNode(N, InsertPoint);
1753 void MDNode::destroyConstant() {
1754 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
1755 MDNodeSet->RemoveNode(this);
1757 destroyConstantImpl();
1760 //---- ConstantExpr::get() implementations...
1765 struct ExprMapKeyType {
1766 typedef SmallVector<unsigned, 4> IndexList;
1768 ExprMapKeyType(unsigned opc,
1769 const std::vector<Constant*> &ops,
1770 unsigned short pred = 0,
1771 const IndexList &inds = IndexList())
1772 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1775 std::vector<Constant*> operands;
1777 bool operator==(const ExprMapKeyType& that) const {
1778 return this->opcode == that.opcode &&
1779 this->predicate == that.predicate &&
1780 this->operands == that.operands &&
1781 this->indices == that.indices;
1783 bool operator<(const ExprMapKeyType & that) const {
1784 return this->opcode < that.opcode ||
1785 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1786 (this->opcode == that.opcode && this->predicate == that.predicate &&
1787 this->operands < that.operands) ||
1788 (this->opcode == that.opcode && this->predicate == that.predicate &&
1789 this->operands == that.operands && this->indices < that.indices);
1792 bool operator!=(const ExprMapKeyType& that) const {
1793 return !(*this == that);
1801 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1802 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1803 unsigned short pred = 0) {
1804 if (Instruction::isCast(V.opcode))
1805 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1806 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1807 V.opcode < Instruction::BinaryOpsEnd))
1808 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1809 if (V.opcode == Instruction::Select)
1810 return new SelectConstantExpr(V.operands[0], V.operands[1],
1812 if (V.opcode == Instruction::ExtractElement)
1813 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1814 if (V.opcode == Instruction::InsertElement)
1815 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1817 if (V.opcode == Instruction::ShuffleVector)
1818 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1820 if (V.opcode == Instruction::InsertValue)
1821 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1823 if (V.opcode == Instruction::ExtractValue)
1824 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1825 if (V.opcode == Instruction::GetElementPtr) {
1826 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1827 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1830 // The compare instructions are weird. We have to encode the predicate
1831 // value and it is combined with the instruction opcode by multiplying
1832 // the opcode by one hundred. We must decode this to get the predicate.
1833 if (V.opcode == Instruction::ICmp)
1834 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1835 V.operands[0], V.operands[1]);
1836 if (V.opcode == Instruction::FCmp)
1837 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1838 V.operands[0], V.operands[1]);
1839 LLVM_UNREACHABLE("Invalid ConstantExpr!");
1845 struct ConvertConstantType<ConstantExpr, Type> {
1846 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1848 switch (OldC->getOpcode()) {
1849 case Instruction::Trunc:
1850 case Instruction::ZExt:
1851 case Instruction::SExt:
1852 case Instruction::FPTrunc:
1853 case Instruction::FPExt:
1854 case Instruction::UIToFP:
1855 case Instruction::SIToFP:
1856 case Instruction::FPToUI:
1857 case Instruction::FPToSI:
1858 case Instruction::PtrToInt:
1859 case Instruction::IntToPtr:
1860 case Instruction::BitCast:
1861 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1864 case Instruction::Select:
1865 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1866 OldC->getOperand(1),
1867 OldC->getOperand(2));
1870 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1871 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1872 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1873 OldC->getOperand(1));
1875 case Instruction::GetElementPtr:
1876 // Make everyone now use a constant of the new type...
1877 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1878 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1879 &Idx[0], Idx.size());
1883 assert(New != OldC && "Didn't replace constant??");
1884 OldC->uncheckedReplaceAllUsesWith(New);
1885 OldC->destroyConstant(); // This constant is now dead, destroy it.
1888 } // end namespace llvm
1891 static ExprMapKeyType getValType(ConstantExpr *CE) {
1892 std::vector<Constant*> Operands;
1893 Operands.reserve(CE->getNumOperands());
1894 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1895 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1896 return ExprMapKeyType(CE->getOpcode(), Operands,
1897 CE->isCompare() ? CE->getPredicate() : 0,
1899 CE->getIndices() : SmallVector<unsigned, 4>());
1902 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1903 ConstantExpr> > ExprConstants;
1905 /// This is a utility function to handle folding of casts and lookup of the
1906 /// cast in the ExprConstants map. It is used by the various get* methods below.
1907 static inline Constant *getFoldedCast(
1908 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1909 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1910 // Fold a few common cases
1912 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1915 // Look up the constant in the table first to ensure uniqueness
1916 std::vector<Constant*> argVec(1, C);
1917 ExprMapKeyType Key(opc, argVec);
1919 // Implicitly locked.
1920 return ExprConstants->getOrCreate(Ty, Key);
1923 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1924 Instruction::CastOps opc = Instruction::CastOps(oc);
1925 assert(Instruction::isCast(opc) && "opcode out of range");
1926 assert(C && Ty && "Null arguments to getCast");
1927 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1931 LLVM_UNREACHABLE("Invalid cast opcode");
1933 case Instruction::Trunc: return getTrunc(C, Ty);
1934 case Instruction::ZExt: return getZExt(C, Ty);
1935 case Instruction::SExt: return getSExt(C, Ty);
1936 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1937 case Instruction::FPExt: return getFPExtend(C, Ty);
1938 case Instruction::UIToFP: return getUIToFP(C, Ty);
1939 case Instruction::SIToFP: return getSIToFP(C, Ty);
1940 case Instruction::FPToUI: return getFPToUI(C, Ty);
1941 case Instruction::FPToSI: return getFPToSI(C, Ty);
1942 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1943 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1944 case Instruction::BitCast: return getBitCast(C, Ty);
1949 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1950 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1951 return getCast(Instruction::BitCast, C, Ty);
1952 return getCast(Instruction::ZExt, C, Ty);
1955 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1956 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1957 return getCast(Instruction::BitCast, C, Ty);
1958 return getCast(Instruction::SExt, C, Ty);
1961 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1962 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1963 return getCast(Instruction::BitCast, C, Ty);
1964 return getCast(Instruction::Trunc, C, Ty);
1967 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1968 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1969 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1971 if (Ty->isInteger())
1972 return getCast(Instruction::PtrToInt, S, Ty);
1973 return getCast(Instruction::BitCast, S, Ty);
1976 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1978 assert(C->getType()->isIntOrIntVector() &&
1979 Ty->isIntOrIntVector() && "Invalid cast");
1980 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1981 unsigned DstBits = Ty->getScalarSizeInBits();
1982 Instruction::CastOps opcode =
1983 (SrcBits == DstBits ? Instruction::BitCast :
1984 (SrcBits > DstBits ? Instruction::Trunc :
1985 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1986 return getCast(opcode, C, Ty);
1989 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1990 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1992 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1993 unsigned DstBits = Ty->getScalarSizeInBits();
1994 if (SrcBits == DstBits)
1995 return C; // Avoid a useless cast
1996 Instruction::CastOps opcode =
1997 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1998 return getCast(opcode, C, Ty);
2001 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
2003 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2004 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2006 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2007 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
2008 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
2009 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2010 "SrcTy must be larger than DestTy for Trunc!");
2012 return getFoldedCast(Instruction::Trunc, C, Ty);
2015 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
2017 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2018 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2020 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2021 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
2022 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
2023 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2024 "SrcTy must be smaller than DestTy for SExt!");
2026 return getFoldedCast(Instruction::SExt, C, Ty);
2029 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
2031 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2032 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2034 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2035 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
2036 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
2037 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2038 "SrcTy must be smaller than DestTy for ZExt!");
2040 return getFoldedCast(Instruction::ZExt, C, Ty);
2043 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
2045 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2046 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2048 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2049 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2050 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2051 "This is an illegal floating point truncation!");
2052 return getFoldedCast(Instruction::FPTrunc, C, Ty);
2055 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
2057 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2058 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2060 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2061 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2062 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
2063 "This is an illegal floating point extension!");
2064 return getFoldedCast(Instruction::FPExt, C, Ty);
2067 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
2069 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2070 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2072 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2073 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2074 "This is an illegal uint to floating point cast!");
2075 return getFoldedCast(Instruction::UIToFP, C, Ty);
2078 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
2080 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2081 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2083 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2084 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
2085 "This is an illegal sint to floating point cast!");
2086 return getFoldedCast(Instruction::SIToFP, C, Ty);
2089 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
2091 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2092 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2094 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2095 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2096 "This is an illegal floating point to uint cast!");
2097 return getFoldedCast(Instruction::FPToUI, C, Ty);
2100 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
2102 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
2103 bool toVec = Ty->getTypeID() == Type::VectorTyID;
2105 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2106 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
2107 "This is an illegal floating point to sint cast!");
2108 return getFoldedCast(Instruction::FPToSI, C, Ty);
2111 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
2112 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
2113 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
2114 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
2117 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
2118 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
2119 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
2120 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
2123 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
2124 // BitCast implies a no-op cast of type only. No bits change. However, you
2125 // can't cast pointers to anything but pointers.
2127 const Type *SrcTy = C->getType();
2128 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
2129 "BitCast cannot cast pointer to non-pointer and vice versa");
2131 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
2132 // or nonptr->ptr). For all the other types, the cast is okay if source and
2133 // destination bit widths are identical.
2134 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2135 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2137 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
2139 // It is common to ask for a bitcast of a value to its own type, handle this
2141 if (C->getType() == DstTy) return C;
2143 return getFoldedCast(Instruction::BitCast, C, DstTy);
2146 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
2147 Constant *C1, Constant *C2) {
2148 // Check the operands for consistency first
2149 assert(Opcode >= Instruction::BinaryOpsBegin &&
2150 Opcode < Instruction::BinaryOpsEnd &&
2151 "Invalid opcode in binary constant expression");
2152 assert(C1->getType() == C2->getType() &&
2153 "Operand types in binary constant expression should match");
2155 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
2156 if (Constant *FC = ConstantFoldBinaryInstruction(
2157 getGlobalContext(), Opcode, C1, C2))
2158 return FC; // Fold a few common cases...
2160 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
2161 ExprMapKeyType Key(Opcode, argVec);
2163 // Implicitly locked.
2164 return ExprConstants->getOrCreate(ReqTy, Key);
2167 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
2168 Constant *C1, Constant *C2) {
2169 switch (predicate) {
2170 default: LLVM_UNREACHABLE("Invalid CmpInst predicate");
2171 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
2172 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
2173 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
2174 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
2175 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
2176 case CmpInst::FCMP_TRUE:
2177 return getFCmp(predicate, C1, C2);
2179 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
2180 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
2181 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
2182 case CmpInst::ICMP_SLE:
2183 return getICmp(predicate, C1, C2);
2187 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
2188 // API compatibility: Adjust integer opcodes to floating-point opcodes.
2189 if (C1->getType()->isFPOrFPVector()) {
2190 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
2191 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
2192 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
2196 case Instruction::Add:
2197 case Instruction::Sub:
2198 case Instruction::Mul:
2199 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2200 assert(C1->getType()->isIntOrIntVector() &&
2201 "Tried to create an integer operation on a non-integer type!");
2203 case Instruction::FAdd:
2204 case Instruction::FSub:
2205 case Instruction::FMul:
2206 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2207 assert(C1->getType()->isFPOrFPVector() &&
2208 "Tried to create a floating-point operation on a "
2209 "non-floating-point type!");
2211 case Instruction::UDiv:
2212 case Instruction::SDiv:
2213 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2214 assert(C1->getType()->isIntOrIntVector() &&
2215 "Tried to create an arithmetic operation on a non-arithmetic type!");
2217 case Instruction::FDiv:
2218 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2219 assert(C1->getType()->isFPOrFPVector() &&
2220 "Tried to create an arithmetic operation on a non-arithmetic type!");
2222 case Instruction::URem:
2223 case Instruction::SRem:
2224 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2225 assert(C1->getType()->isIntOrIntVector() &&
2226 "Tried to create an arithmetic operation on a non-arithmetic type!");
2228 case Instruction::FRem:
2229 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2230 assert(C1->getType()->isFPOrFPVector() &&
2231 "Tried to create an arithmetic operation on a non-arithmetic type!");
2233 case Instruction::And:
2234 case Instruction::Or:
2235 case Instruction::Xor:
2236 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2237 assert(C1->getType()->isIntOrIntVector() &&
2238 "Tried to create a logical operation on a non-integral type!");
2240 case Instruction::Shl:
2241 case Instruction::LShr:
2242 case Instruction::AShr:
2243 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2244 assert(C1->getType()->isIntOrIntVector() &&
2245 "Tried to create a shift operation on a non-integer type!");
2252 return getTy(C1->getType(), Opcode, C1, C2);
2255 Constant *ConstantExpr::getCompare(unsigned short pred,
2256 Constant *C1, Constant *C2) {
2257 assert(C1->getType() == C2->getType() && "Op types should be identical!");
2258 return getCompareTy(pred, C1, C2);
2261 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
2262 Constant *V1, Constant *V2) {
2263 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
2265 if (ReqTy == V1->getType())
2266 if (Constant *SC = ConstantFoldSelectInstruction(
2267 getGlobalContext(), C, V1, V2))
2268 return SC; // Fold common cases
2270 std::vector<Constant*> argVec(3, C);
2273 ExprMapKeyType Key(Instruction::Select, argVec);
2275 // Implicitly locked.
2276 return ExprConstants->getOrCreate(ReqTy, Key);
2279 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
2282 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
2284 cast<PointerType>(ReqTy)->getElementType() &&
2285 "GEP indices invalid!");
2287 if (Constant *FC = ConstantFoldGetElementPtr(
2288 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
2289 return FC; // Fold a few common cases...
2291 assert(isa<PointerType>(C->getType()) &&
2292 "Non-pointer type for constant GetElementPtr expression");
2293 // Look up the constant in the table first to ensure uniqueness
2294 std::vector<Constant*> ArgVec;
2295 ArgVec.reserve(NumIdx+1);
2296 ArgVec.push_back(C);
2297 for (unsigned i = 0; i != NumIdx; ++i)
2298 ArgVec.push_back(cast<Constant>(Idxs[i]));
2299 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
2301 // Implicitly locked.
2302 return ExprConstants->getOrCreate(ReqTy, Key);
2305 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
2307 // Get the result type of the getelementptr!
2309 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
2310 assert(Ty && "GEP indices invalid!");
2311 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
2312 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
2315 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
2317 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
2322 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2323 assert(LHS->getType() == RHS->getType());
2324 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
2325 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
2327 if (Constant *FC = ConstantFoldCompareInstruction(
2328 getGlobalContext(),pred, LHS, RHS))
2329 return FC; // Fold a few common cases...
2331 // Look up the constant in the table first to ensure uniqueness
2332 std::vector<Constant*> ArgVec;
2333 ArgVec.push_back(LHS);
2334 ArgVec.push_back(RHS);
2335 // Get the key type with both the opcode and predicate
2336 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
2338 // Implicitly locked.
2339 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2343 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
2344 assert(LHS->getType() == RHS->getType());
2345 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
2347 if (Constant *FC = ConstantFoldCompareInstruction(
2348 getGlobalContext(), pred, LHS, RHS))
2349 return FC; // Fold a few common cases...
2351 // Look up the constant in the table first to ensure uniqueness
2352 std::vector<Constant*> ArgVec;
2353 ArgVec.push_back(LHS);
2354 ArgVec.push_back(RHS);
2355 // Get the key type with both the opcode and predicate
2356 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
2358 // Implicitly locked.
2359 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
2362 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
2364 if (Constant *FC = ConstantFoldExtractElementInstruction(
2365 getGlobalContext(), Val, Idx))
2366 return FC; // Fold a few common cases...
2367 // Look up the constant in the table first to ensure uniqueness
2368 std::vector<Constant*> ArgVec(1, Val);
2369 ArgVec.push_back(Idx);
2370 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
2372 // Implicitly locked.
2373 return ExprConstants->getOrCreate(ReqTy, Key);
2376 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
2377 assert(isa<VectorType>(Val->getType()) &&
2378 "Tried to create extractelement operation on non-vector type!");
2379 assert(Idx->getType() == Type::Int32Ty &&
2380 "Extractelement index must be i32 type!");
2381 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
2385 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
2386 Constant *Elt, Constant *Idx) {
2387 if (Constant *FC = ConstantFoldInsertElementInstruction(
2388 getGlobalContext(), Val, Elt, Idx))
2389 return FC; // Fold a few common cases...
2390 // Look up the constant in the table first to ensure uniqueness
2391 std::vector<Constant*> ArgVec(1, Val);
2392 ArgVec.push_back(Elt);
2393 ArgVec.push_back(Idx);
2394 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
2396 // Implicitly locked.
2397 return ExprConstants->getOrCreate(ReqTy, Key);
2400 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2402 assert(isa<VectorType>(Val->getType()) &&
2403 "Tried to create insertelement operation on non-vector type!");
2404 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
2405 && "Insertelement types must match!");
2406 assert(Idx->getType() == Type::Int32Ty &&
2407 "Insertelement index must be i32 type!");
2408 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
2411 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
2412 Constant *V2, Constant *Mask) {
2413 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
2414 getGlobalContext(), V1, V2, Mask))
2415 return FC; // Fold a few common cases...
2416 // Look up the constant in the table first to ensure uniqueness
2417 std::vector<Constant*> ArgVec(1, V1);
2418 ArgVec.push_back(V2);
2419 ArgVec.push_back(Mask);
2420 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
2422 // Implicitly locked.
2423 return ExprConstants->getOrCreate(ReqTy, Key);
2426 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2428 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2429 "Invalid shuffle vector constant expr operands!");
2431 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
2432 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
2433 const Type *ShufTy = VectorType::get(EltTy, NElts);
2434 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
2437 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
2439 const unsigned *Idxs, unsigned NumIdx) {
2440 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2441 Idxs+NumIdx) == Val->getType() &&
2442 "insertvalue indices invalid!");
2443 assert(Agg->getType() == ReqTy &&
2444 "insertvalue type invalid!");
2445 assert(Agg->getType()->isFirstClassType() &&
2446 "Non-first-class type for constant InsertValue expression");
2447 Constant *FC = ConstantFoldInsertValueInstruction(
2448 getGlobalContext(), Agg, Val, Idxs, NumIdx);
2449 assert(FC && "InsertValue constant expr couldn't be folded!");
2453 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2454 const unsigned *IdxList, unsigned NumIdx) {
2455 assert(Agg->getType()->isFirstClassType() &&
2456 "Tried to create insertelement operation on non-first-class type!");
2458 const Type *ReqTy = Agg->getType();
2461 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2463 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
2464 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
2467 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
2468 const unsigned *Idxs, unsigned NumIdx) {
2469 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
2470 Idxs+NumIdx) == ReqTy &&
2471 "extractvalue indices invalid!");
2472 assert(Agg->getType()->isFirstClassType() &&
2473 "Non-first-class type for constant extractvalue expression");
2474 Constant *FC = ConstantFoldExtractValueInstruction(
2475 getGlobalContext(), Agg, Idxs, NumIdx);
2476 assert(FC && "ExtractValue constant expr couldn't be folded!");
2480 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2481 const unsigned *IdxList, unsigned NumIdx) {
2482 assert(Agg->getType()->isFirstClassType() &&
2483 "Tried to create extractelement operation on non-first-class type!");
2486 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
2487 assert(ReqTy && "extractvalue indices invalid!");
2488 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
2491 // destroyConstant - Remove the constant from the constant table...
2493 void ConstantExpr::destroyConstant() {
2494 // Implicitly locked.
2495 ExprConstants->remove(this);
2496 destroyConstantImpl();
2499 const char *ConstantExpr::getOpcodeName() const {
2500 return Instruction::getOpcodeName(getOpcode());
2503 //===----------------------------------------------------------------------===//
2504 // replaceUsesOfWithOnConstant implementations
2506 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2507 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2510 /// Note that we intentionally replace all uses of From with To here. Consider
2511 /// a large array that uses 'From' 1000 times. By handling this case all here,
2512 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2513 /// single invocation handles all 1000 uses. Handling them one at a time would
2514 /// work, but would be really slow because it would have to unique each updated
2516 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2518 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2519 Constant *ToC = cast<Constant>(To);
2521 std::pair<ArrayConstantsTy::MapKey, Constant*> Lookup;
2522 Lookup.first.first = getType();
2523 Lookup.second = this;
2525 std::vector<Constant*> &Values = Lookup.first.second;
2526 Values.reserve(getNumOperands()); // Build replacement array.
2528 // Fill values with the modified operands of the constant array. Also,
2529 // compute whether this turns into an all-zeros array.
2530 bool isAllZeros = false;
2531 unsigned NumUpdated = 0;
2532 if (!ToC->isNullValue()) {
2533 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2534 Constant *Val = cast<Constant>(O->get());
2539 Values.push_back(Val);
2543 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2544 Constant *Val = cast<Constant>(O->get());
2549 Values.push_back(Val);
2550 if (isAllZeros) isAllZeros = Val->isNullValue();
2554 Constant *Replacement = 0;
2556 Replacement = ConstantAggregateZero::get(getType());
2558 // Check to see if we have this array type already.
2559 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2561 ArrayConstantsTy::MapTy::iterator I =
2562 ArrayConstants->InsertOrGetItem(Lookup, Exists);
2565 Replacement = I->second;
2567 // Okay, the new shape doesn't exist in the system yet. Instead of
2568 // creating a new constant array, inserting it, replaceallusesof'ing the
2569 // old with the new, then deleting the old... just update the current one
2571 ArrayConstants->MoveConstantToNewSlot(this, I);
2573 // Update to the new value. Optimize for the case when we have a single
2574 // operand that we're changing, but handle bulk updates efficiently.
2575 if (NumUpdated == 1) {
2576 unsigned OperandToUpdate = U-OperandList;
2577 assert(getOperand(OperandToUpdate) == From &&
2578 "ReplaceAllUsesWith broken!");
2579 setOperand(OperandToUpdate, ToC);
2581 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2582 if (getOperand(i) == From)
2589 // Otherwise, I do need to replace this with an existing value.
2590 assert(Replacement != this && "I didn't contain From!");
2592 // Everyone using this now uses the replacement.
2593 uncheckedReplaceAllUsesWith(Replacement);
2595 // Delete the old constant!
2599 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2601 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2602 Constant *ToC = cast<Constant>(To);
2604 unsigned OperandToUpdate = U-OperandList;
2605 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2607 std::pair<StructConstantsTy::MapKey, Constant*> Lookup;
2608 Lookup.first.first = getType();
2609 Lookup.second = this;
2610 std::vector<Constant*> &Values = Lookup.first.second;
2611 Values.reserve(getNumOperands()); // Build replacement struct.
2614 // Fill values with the modified operands of the constant struct. Also,
2615 // compute whether this turns into an all-zeros struct.
2616 bool isAllZeros = false;
2617 if (!ToC->isNullValue()) {
2618 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O)
2619 Values.push_back(cast<Constant>(O->get()));
2622 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2623 Constant *Val = cast<Constant>(O->get());
2624 Values.push_back(Val);
2625 if (isAllZeros) isAllZeros = Val->isNullValue();
2628 Values[OperandToUpdate] = ToC;
2630 Constant *Replacement = 0;
2632 Replacement = ConstantAggregateZero::get(getType());
2634 // Check to see if we have this array type already.
2635 sys::SmartScopedWriter<true> Writer(*ConstantsLock);
2637 StructConstantsTy::MapTy::iterator I =
2638 StructConstants->InsertOrGetItem(Lookup, Exists);
2641 Replacement = I->second;
2643 // Okay, the new shape doesn't exist in the system yet. Instead of
2644 // creating a new constant struct, inserting it, replaceallusesof'ing the
2645 // old with the new, then deleting the old... just update the current one
2647 StructConstants->MoveConstantToNewSlot(this, I);
2649 // Update to the new value.
2650 setOperand(OperandToUpdate, ToC);
2655 assert(Replacement != this && "I didn't contain From!");
2657 // Everyone using this now uses the replacement.
2658 uncheckedReplaceAllUsesWith(Replacement);
2660 // Delete the old constant!
2664 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2666 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2668 std::vector<Constant*> Values;
2669 Values.reserve(getNumOperands()); // Build replacement array...
2670 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2671 Constant *Val = getOperand(i);
2672 if (Val == From) Val = cast<Constant>(To);
2673 Values.push_back(Val);
2676 Constant *Replacement = ConstantVector::get(getType(), Values);
2677 assert(Replacement != this && "I didn't contain From!");
2679 // Everyone using this now uses the replacement.
2680 uncheckedReplaceAllUsesWith(Replacement);
2682 // Delete the old constant!
2686 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2688 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2689 Constant *To = cast<Constant>(ToV);
2691 Constant *Replacement = 0;
2692 if (getOpcode() == Instruction::GetElementPtr) {
2693 SmallVector<Constant*, 8> Indices;
2694 Constant *Pointer = getOperand(0);
2695 Indices.reserve(getNumOperands()-1);
2696 if (Pointer == From) Pointer = To;
2698 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2699 Constant *Val = getOperand(i);
2700 if (Val == From) Val = To;
2701 Indices.push_back(Val);
2703 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2704 &Indices[0], Indices.size());
2705 } else if (getOpcode() == Instruction::ExtractValue) {
2706 Constant *Agg = getOperand(0);
2707 if (Agg == From) Agg = To;
2709 const SmallVector<unsigned, 4> &Indices = getIndices();
2710 Replacement = ConstantExpr::getExtractValue(Agg,
2711 &Indices[0], Indices.size());
2712 } else if (getOpcode() == Instruction::InsertValue) {
2713 Constant *Agg = getOperand(0);
2714 Constant *Val = getOperand(1);
2715 if (Agg == From) Agg = To;
2716 if (Val == From) Val = To;
2718 const SmallVector<unsigned, 4> &Indices = getIndices();
2719 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2720 &Indices[0], Indices.size());
2721 } else if (isCast()) {
2722 assert(getOperand(0) == From && "Cast only has one use!");
2723 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2724 } else if (getOpcode() == Instruction::Select) {
2725 Constant *C1 = getOperand(0);
2726 Constant *C2 = getOperand(1);
2727 Constant *C3 = getOperand(2);
2728 if (C1 == From) C1 = To;
2729 if (C2 == From) C2 = To;
2730 if (C3 == From) C3 = To;
2731 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2732 } else if (getOpcode() == Instruction::ExtractElement) {
2733 Constant *C1 = getOperand(0);
2734 Constant *C2 = getOperand(1);
2735 if (C1 == From) C1 = To;
2736 if (C2 == From) C2 = To;
2737 Replacement = ConstantExpr::getExtractElement(C1, C2);
2738 } else if (getOpcode() == Instruction::InsertElement) {
2739 Constant *C1 = getOperand(0);
2740 Constant *C2 = getOperand(1);
2741 Constant *C3 = getOperand(1);
2742 if (C1 == From) C1 = To;
2743 if (C2 == From) C2 = To;
2744 if (C3 == From) C3 = To;
2745 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2746 } else if (getOpcode() == Instruction::ShuffleVector) {
2747 Constant *C1 = getOperand(0);
2748 Constant *C2 = getOperand(1);
2749 Constant *C3 = getOperand(2);
2750 if (C1 == From) C1 = To;
2751 if (C2 == From) C2 = To;
2752 if (C3 == From) C3 = To;
2753 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2754 } else if (isCompare()) {
2755 Constant *C1 = getOperand(0);
2756 Constant *C2 = getOperand(1);
2757 if (C1 == From) C1 = To;
2758 if (C2 == From) C2 = To;
2759 if (getOpcode() == Instruction::ICmp)
2760 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2762 assert(getOpcode() == Instruction::FCmp);
2763 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2765 } else if (getNumOperands() == 2) {
2766 Constant *C1 = getOperand(0);
2767 Constant *C2 = getOperand(1);
2768 if (C1 == From) C1 = To;
2769 if (C2 == From) C2 = To;
2770 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2772 LLVM_UNREACHABLE("Unknown ConstantExpr type!");
2776 assert(Replacement != this && "I didn't contain From!");
2778 // Everyone using this now uses the replacement.
2779 uncheckedReplaceAllUsesWith(Replacement);
2781 // Delete the old constant!
2785 void MDNode::replaceElement(Value *From, Value *To) {
2786 SmallVector<Value*, 4> Values;
2787 Values.reserve(getNumElements()); // Build replacement array...
2788 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2789 Value *Val = getElement(i);
2790 if (Val == From) Val = To;
2791 Values.push_back(Val);
2794 MDNode *Replacement = MDNode::get(&Values[0], Values.size());
2795 assert(Replacement != this && "I didn't contain From!");
2797 uncheckedReplaceAllUsesWith(Replacement);