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 "LLVMContextImpl.h"
15 #include "llvm/Constants.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/MDNode.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ADT/FoldingSet.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/System/Mutex.h"
32 #include "llvm/System/RWMutex.h"
33 #include "llvm/System/Threading.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallVector.h"
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 // Becomes a no-op when multithreading is disabled.
45 ManagedStatic<sys::SmartRWMutex<true> > ConstantsLock;
47 void Constant::destroyConstantImpl() {
48 // When a Constant is destroyed, there may be lingering
49 // references to the constant by other constants in the constant pool. These
50 // constants are implicitly dependent on the module that is being deleted,
51 // but they don't know that. Because we only find out when the CPV is
52 // deleted, we must now notify all of our users (that should only be
53 // Constants) that they are, in fact, invalid now and should be deleted.
55 while (!use_empty()) {
56 Value *V = use_back();
57 #ifndef NDEBUG // Only in -g mode...
58 if (!isa<Constant>(V))
59 DOUT << "While deleting: " << *this
60 << "\n\nUse still stuck around after Def is destroyed: "
63 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
64 Constant *CV = cast<Constant>(V);
65 CV->destroyConstant();
67 // The constant should remove itself from our use list...
68 assert((use_empty() || use_back() != V) && "Constant not removed!");
71 // Value has no outstanding references it is safe to delete it now...
75 /// canTrap - Return true if evaluation of this constant could trap. This is
76 /// true for things like constant expressions that could divide by zero.
77 bool Constant::canTrap() const {
78 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
79 // The only thing that could possibly trap are constant exprs.
80 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
81 if (!CE) return false;
83 // ConstantExpr traps if any operands can trap.
84 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
85 if (getOperand(i)->canTrap())
88 // Otherwise, only specific operations can trap.
89 switch (CE->getOpcode()) {
92 case Instruction::UDiv:
93 case Instruction::SDiv:
94 case Instruction::FDiv:
95 case Instruction::URem:
96 case Instruction::SRem:
97 case Instruction::FRem:
98 // Div and rem can trap if the RHS is not known to be non-zero.
99 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
106 /// getRelocationInfo - This method classifies the entry according to
107 /// whether or not it may generate a relocation entry. This must be
108 /// conservative, so if it might codegen to a relocatable entry, it should say
109 /// so. The return values are:
111 /// NoRelocation: This constant pool entry is guaranteed to never have a
112 /// relocation applied to it (because it holds a simple constant like
114 /// LocalRelocation: This entry has relocations, but the entries are
115 /// guaranteed to be resolvable by the static linker, so the dynamic
116 /// linker will never see them.
117 /// GlobalRelocations: This entry may have arbitrary relocations.
119 /// FIXME: This really should not be in VMCore.
120 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
121 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
122 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
123 return LocalRelocation; // Local to this file/library.
124 return GlobalRelocations; // Global reference.
127 PossibleRelocationsTy Result = NoRelocation;
128 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
129 Result = std::max(Result, getOperand(i)->getRelocationInfo());
135 /// getVectorElements - This method, which is only valid on constant of vector
136 /// type, returns the elements of the vector in the specified smallvector.
137 /// This handles breaking down a vector undef into undef elements, etc. For
138 /// constant exprs and other cases we can't handle, we return an empty vector.
139 void Constant::getVectorElements(LLVMContext &Context,
140 SmallVectorImpl<Constant*> &Elts) const {
141 assert(isa<VectorType>(getType()) && "Not a vector constant!");
143 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
144 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
145 Elts.push_back(CV->getOperand(i));
149 const VectorType *VT = cast<VectorType>(getType());
150 if (isa<ConstantAggregateZero>(this)) {
151 Elts.assign(VT->getNumElements(),
152 Context.getNullValue(VT->getElementType()));
156 if (isa<UndefValue>(this)) {
157 Elts.assign(VT->getNumElements(), Context.getUndef(VT->getElementType()));
161 // Unknown type, must be constant expr etc.
166 //===----------------------------------------------------------------------===//
168 //===----------------------------------------------------------------------===//
170 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
171 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
172 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
175 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
176 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
177 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
178 // compare APInt's of different widths, which would violate an APInt class
179 // invariant which generates an assertion.
180 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
181 // Get the corresponding integer type for the bit width of the value.
182 const IntegerType *ITy = Context.getIntegerType(V.getBitWidth());
183 // get an existing value or the insertion position
184 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
186 Context.pImpl->ConstantsLock.reader_acquire();
187 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
188 Context.pImpl->ConstantsLock.reader_release();
191 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
192 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
194 NewSlot = new ConstantInt(ITy, V);
203 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
204 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
207 // For vectors, broadcast the value.
208 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
209 return Ty->getContext().getConstantVector(
210 std::vector<Constant *>(VTy->getNumElements(), C));
215 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
217 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
220 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
221 return get(Ty, V, true);
224 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
225 return get(Ty, V, true);
228 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
229 ConstantInt *C = get(Ty->getContext(), V);
230 assert(C->getType() == Ty->getScalarType() &&
231 "ConstantInt type doesn't match the type implied by its value!");
233 // For vectors, broadcast the value.
234 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
235 return Ty->getContext().getConstantVector(
236 std::vector<Constant *>(VTy->getNumElements(), C));
241 //===----------------------------------------------------------------------===//
243 //===----------------------------------------------------------------------===//
246 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
247 if (Ty == Type::FloatTy)
248 return &APFloat::IEEEsingle;
249 if (Ty == Type::DoubleTy)
250 return &APFloat::IEEEdouble;
251 if (Ty == Type::X86_FP80Ty)
252 return &APFloat::x87DoubleExtended;
253 else if (Ty == Type::FP128Ty)
254 return &APFloat::IEEEquad;
256 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
257 return &APFloat::PPCDoubleDouble;
261 /// get() - This returns a constant fp for the specified value in the
262 /// specified type. This should only be used for simple constant values like
263 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
264 Constant* ConstantFP::get(const Type* Ty, double V) {
265 LLVMContext &Context = Ty->getContext();
269 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
270 APFloat::rmNearestTiesToEven, &ignored);
271 Constant *C = get(Context, FV);
273 // For vectors, broadcast the value.
274 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
275 return Context.getConstantVector(
276 std::vector<Constant *>(VTy->getNumElements(), C));
281 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
282 LLVMContext &Context = Ty->getContext();
283 APFloat apf = cast <ConstantFP>(Context.getNullValue(Ty))->getValueAPF();
285 return get(Context, apf);
289 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
290 LLVMContext &Context = Ty->getContext();
291 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
292 if (PTy->getElementType()->isFloatingPoint()) {
293 std::vector<Constant*> zeros(PTy->getNumElements(),
294 getNegativeZero(PTy->getElementType()));
295 return Context.getConstantVector(PTy, zeros);
298 if (Ty->isFloatingPoint())
299 return getNegativeZero(Ty);
301 return Context.getNullValue(Ty);
305 // ConstantFP accessors.
306 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
307 DenseMapAPFloatKeyInfo::KeyTy Key(V);
309 LLVMContextImpl* pImpl = Context.pImpl;
311 pImpl->ConstantsLock.reader_acquire();
312 ConstantFP *&Slot = pImpl->FPConstants[Key];
313 pImpl->ConstantsLock.reader_release();
316 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
317 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
320 if (&V.getSemantics() == &APFloat::IEEEsingle)
322 else if (&V.getSemantics() == &APFloat::IEEEdouble)
324 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
325 Ty = Type::X86_FP80Ty;
326 else if (&V.getSemantics() == &APFloat::IEEEquad)
329 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
330 "Unknown FP format");
331 Ty = Type::PPC_FP128Ty;
333 NewSlot = new ConstantFP(Ty, V);
342 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
343 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
344 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
348 bool ConstantFP::isNullValue() const {
349 return Val.isZero() && !Val.isNegative();
352 bool ConstantFP::isExactlyValue(const APFloat& V) const {
353 return Val.bitwiseIsEqual(V);
356 //===----------------------------------------------------------------------===//
357 // ConstantXXX Classes
358 //===----------------------------------------------------------------------===//
361 ConstantArray::ConstantArray(const ArrayType *T,
362 const std::vector<Constant*> &V)
363 : Constant(T, ConstantArrayVal,
364 OperandTraits<ConstantArray>::op_end(this) - V.size(),
366 assert(V.size() == T->getNumElements() &&
367 "Invalid initializer vector for constant array");
368 Use *OL = OperandList;
369 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
372 assert((C->getType() == T->getElementType() ||
374 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
375 "Initializer for array element doesn't match array element type!");
381 ConstantStruct::ConstantStruct(const StructType *T,
382 const std::vector<Constant*> &V)
383 : Constant(T, ConstantStructVal,
384 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
386 assert(V.size() == T->getNumElements() &&
387 "Invalid initializer vector for constant structure");
388 Use *OL = OperandList;
389 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
392 assert((C->getType() == T->getElementType(I-V.begin()) ||
393 ((T->getElementType(I-V.begin())->isAbstract() ||
394 C->getType()->isAbstract()) &&
395 T->getElementType(I-V.begin())->getTypeID() ==
396 C->getType()->getTypeID())) &&
397 "Initializer for struct element doesn't match struct element type!");
403 ConstantVector::ConstantVector(const VectorType *T,
404 const std::vector<Constant*> &V)
405 : Constant(T, ConstantVectorVal,
406 OperandTraits<ConstantVector>::op_end(this) - V.size(),
408 Use *OL = OperandList;
409 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
412 assert((C->getType() == T->getElementType() ||
414 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
415 "Initializer for vector element doesn't match vector element type!");
422 // We declare several classes private to this file, so use an anonymous
426 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
427 /// behind the scenes to implement unary constant exprs.
428 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
429 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
431 // allocate space for exactly one operand
432 void *operator new(size_t s) {
433 return User::operator new(s, 1);
435 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
436 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
439 /// Transparently provide more efficient getOperand methods.
440 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
443 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
444 /// behind the scenes to implement binary constant exprs.
445 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
446 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
448 // allocate space for exactly two operands
449 void *operator new(size_t s) {
450 return User::operator new(s, 2);
452 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
453 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
457 /// Transparently provide more efficient getOperand methods.
458 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
461 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
462 /// behind the scenes to implement select constant exprs.
463 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
464 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
466 // allocate space for exactly three operands
467 void *operator new(size_t s) {
468 return User::operator new(s, 3);
470 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
471 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
476 /// Transparently provide more efficient getOperand methods.
477 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
480 /// ExtractElementConstantExpr - This class is private to
481 /// Constants.cpp, and is used behind the scenes to implement
482 /// extractelement constant exprs.
483 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
484 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
486 // allocate space for exactly two operands
487 void *operator new(size_t s) {
488 return User::operator new(s, 2);
490 ExtractElementConstantExpr(Constant *C1, Constant *C2)
491 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
492 Instruction::ExtractElement, &Op<0>(), 2) {
496 /// Transparently provide more efficient getOperand methods.
497 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
500 /// InsertElementConstantExpr - This class is private to
501 /// Constants.cpp, and is used behind the scenes to implement
502 /// insertelement constant exprs.
503 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
504 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
506 // allocate space for exactly three operands
507 void *operator new(size_t s) {
508 return User::operator new(s, 3);
510 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
511 : ConstantExpr(C1->getType(), Instruction::InsertElement,
517 /// Transparently provide more efficient getOperand methods.
518 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
521 /// ShuffleVectorConstantExpr - This class is private to
522 /// Constants.cpp, and is used behind the scenes to implement
523 /// shufflevector constant exprs.
524 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
525 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
527 // allocate space for exactly three operands
528 void *operator new(size_t s) {
529 return User::operator new(s, 3);
531 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
532 : ConstantExpr(VectorType::get(
533 cast<VectorType>(C1->getType())->getElementType(),
534 cast<VectorType>(C3->getType())->getNumElements()),
535 Instruction::ShuffleVector,
541 /// Transparently provide more efficient getOperand methods.
542 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
545 /// ExtractValueConstantExpr - This class is private to
546 /// Constants.cpp, and is used behind the scenes to implement
547 /// extractvalue constant exprs.
548 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
549 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
551 // allocate space for exactly one operand
552 void *operator new(size_t s) {
553 return User::operator new(s, 1);
555 ExtractValueConstantExpr(Constant *Agg,
556 const SmallVector<unsigned, 4> &IdxList,
558 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
563 /// Indices - These identify which value to extract.
564 const SmallVector<unsigned, 4> Indices;
566 /// Transparently provide more efficient getOperand methods.
567 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
570 /// InsertValueConstantExpr - This class is private to
571 /// Constants.cpp, and is used behind the scenes to implement
572 /// insertvalue constant exprs.
573 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
574 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
576 // allocate space for exactly one operand
577 void *operator new(size_t s) {
578 return User::operator new(s, 2);
580 InsertValueConstantExpr(Constant *Agg, Constant *Val,
581 const SmallVector<unsigned, 4> &IdxList,
583 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
589 /// Indices - These identify the position for the insertion.
590 const SmallVector<unsigned, 4> Indices;
592 /// Transparently provide more efficient getOperand methods.
593 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
597 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
598 /// used behind the scenes to implement getelementpr constant exprs.
599 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
600 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
603 static GetElementPtrConstantExpr *Create(Constant *C,
604 const std::vector<Constant*>&IdxList,
605 const Type *DestTy) {
607 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
609 /// Transparently provide more efficient getOperand methods.
610 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
613 // CompareConstantExpr - This class is private to Constants.cpp, and is used
614 // behind the scenes to implement ICmp and FCmp constant expressions. This is
615 // needed in order to store the predicate value for these instructions.
616 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
617 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
618 // allocate space for exactly two operands
619 void *operator new(size_t s) {
620 return User::operator new(s, 2);
622 unsigned short predicate;
623 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
624 unsigned short pred, Constant* LHS, Constant* RHS)
625 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
629 /// Transparently provide more efficient getOperand methods.
630 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
633 } // end anonymous namespace
636 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
638 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
641 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
643 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
646 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
648 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
651 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
653 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
656 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
658 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
661 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
663 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
666 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
668 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
671 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
673 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
676 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
679 GetElementPtrConstantExpr::GetElementPtrConstantExpr
681 const std::vector<Constant*> &IdxList,
683 : ConstantExpr(DestTy, Instruction::GetElementPtr,
684 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
685 - (IdxList.size()+1),
688 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
689 OperandList[i+1] = IdxList[i];
692 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
696 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
698 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
701 } // End llvm namespace
704 // Utility function for determining if a ConstantExpr is a CastOp or not. This
705 // can't be inline because we don't want to #include Instruction.h into
707 bool ConstantExpr::isCast() const {
708 return Instruction::isCast(getOpcode());
711 bool ConstantExpr::isCompare() const {
712 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
715 bool ConstantExpr::hasIndices() const {
716 return getOpcode() == Instruction::ExtractValue ||
717 getOpcode() == Instruction::InsertValue;
720 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
721 if (const ExtractValueConstantExpr *EVCE =
722 dyn_cast<ExtractValueConstantExpr>(this))
723 return EVCE->Indices;
725 return cast<InsertValueConstantExpr>(this)->Indices;
728 unsigned ConstantExpr::getPredicate() const {
729 assert(getOpcode() == Instruction::FCmp ||
730 getOpcode() == Instruction::ICmp);
731 return ((const CompareConstantExpr*)this)->predicate;
734 /// getWithOperandReplaced - Return a constant expression identical to this
735 /// one, but with the specified operand set to the specified value.
737 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
738 assert(OpNo < getNumOperands() && "Operand num is out of range!");
739 assert(Op->getType() == getOperand(OpNo)->getType() &&
740 "Replacing operand with value of different type!");
741 if (getOperand(OpNo) == Op)
742 return const_cast<ConstantExpr*>(this);
744 Constant *Op0, *Op1, *Op2;
745 switch (getOpcode()) {
746 case Instruction::Trunc:
747 case Instruction::ZExt:
748 case Instruction::SExt:
749 case Instruction::FPTrunc:
750 case Instruction::FPExt:
751 case Instruction::UIToFP:
752 case Instruction::SIToFP:
753 case Instruction::FPToUI:
754 case Instruction::FPToSI:
755 case Instruction::PtrToInt:
756 case Instruction::IntToPtr:
757 case Instruction::BitCast:
758 return ConstantExpr::getCast(getOpcode(), Op, getType());
759 case Instruction::Select:
760 Op0 = (OpNo == 0) ? Op : getOperand(0);
761 Op1 = (OpNo == 1) ? Op : getOperand(1);
762 Op2 = (OpNo == 2) ? Op : getOperand(2);
763 return ConstantExpr::getSelect(Op0, Op1, Op2);
764 case Instruction::InsertElement:
765 Op0 = (OpNo == 0) ? Op : getOperand(0);
766 Op1 = (OpNo == 1) ? Op : getOperand(1);
767 Op2 = (OpNo == 2) ? Op : getOperand(2);
768 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
769 case Instruction::ExtractElement:
770 Op0 = (OpNo == 0) ? Op : getOperand(0);
771 Op1 = (OpNo == 1) ? Op : getOperand(1);
772 return ConstantExpr::getExtractElement(Op0, Op1);
773 case Instruction::ShuffleVector:
774 Op0 = (OpNo == 0) ? Op : getOperand(0);
775 Op1 = (OpNo == 1) ? Op : getOperand(1);
776 Op2 = (OpNo == 2) ? Op : getOperand(2);
777 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
778 case Instruction::GetElementPtr: {
779 SmallVector<Constant*, 8> Ops;
780 Ops.resize(getNumOperands()-1);
781 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
782 Ops[i-1] = getOperand(i);
784 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
786 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
789 assert(getNumOperands() == 2 && "Must be binary operator?");
790 Op0 = (OpNo == 0) ? Op : getOperand(0);
791 Op1 = (OpNo == 1) ? Op : getOperand(1);
792 return ConstantExpr::get(getOpcode(), Op0, Op1);
796 /// getWithOperands - This returns the current constant expression with the
797 /// operands replaced with the specified values. The specified operands must
798 /// match count and type with the existing ones.
799 Constant *ConstantExpr::
800 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
801 assert(NumOps == getNumOperands() && "Operand count mismatch!");
802 bool AnyChange = false;
803 for (unsigned i = 0; i != NumOps; ++i) {
804 assert(Ops[i]->getType() == getOperand(i)->getType() &&
805 "Operand type mismatch!");
806 AnyChange |= Ops[i] != getOperand(i);
808 if (!AnyChange) // No operands changed, return self.
809 return const_cast<ConstantExpr*>(this);
811 switch (getOpcode()) {
812 case Instruction::Trunc:
813 case Instruction::ZExt:
814 case Instruction::SExt:
815 case Instruction::FPTrunc:
816 case Instruction::FPExt:
817 case Instruction::UIToFP:
818 case Instruction::SIToFP:
819 case Instruction::FPToUI:
820 case Instruction::FPToSI:
821 case Instruction::PtrToInt:
822 case Instruction::IntToPtr:
823 case Instruction::BitCast:
824 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
825 case Instruction::Select:
826 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
827 case Instruction::InsertElement:
828 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
829 case Instruction::ExtractElement:
830 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
831 case Instruction::ShuffleVector:
832 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
833 case Instruction::GetElementPtr:
834 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
835 case Instruction::ICmp:
836 case Instruction::FCmp:
837 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
839 assert(getNumOperands() == 2 && "Must be binary operator?");
840 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
845 //===----------------------------------------------------------------------===//
846 // isValueValidForType implementations
848 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
849 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
850 if (Ty == Type::Int1Ty)
851 return Val == 0 || Val == 1;
853 return true; // always true, has to fit in largest type
854 uint64_t Max = (1ll << NumBits) - 1;
858 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
859 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
860 if (Ty == Type::Int1Ty)
861 return Val == 0 || Val == 1 || Val == -1;
863 return true; // always true, has to fit in largest type
864 int64_t Min = -(1ll << (NumBits-1));
865 int64_t Max = (1ll << (NumBits-1)) - 1;
866 return (Val >= Min && Val <= Max);
869 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
870 // convert modifies in place, so make a copy.
871 APFloat Val2 = APFloat(Val);
873 switch (Ty->getTypeID()) {
875 return false; // These can't be represented as floating point!
877 // FIXME rounding mode needs to be more flexible
878 case Type::FloatTyID: {
879 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
881 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
884 case Type::DoubleTyID: {
885 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
886 &Val2.getSemantics() == &APFloat::IEEEdouble)
888 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
891 case Type::X86_FP80TyID:
892 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
893 &Val2.getSemantics() == &APFloat::IEEEdouble ||
894 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
895 case Type::FP128TyID:
896 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
897 &Val2.getSemantics() == &APFloat::IEEEdouble ||
898 &Val2.getSemantics() == &APFloat::IEEEquad;
899 case Type::PPC_FP128TyID:
900 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
901 &Val2.getSemantics() == &APFloat::IEEEdouble ||
902 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
906 //===----------------------------------------------------------------------===//
907 // Factory Function Implementation
909 /// destroyConstant - Remove the constant from the constant table...
911 void ConstantAggregateZero::destroyConstant() {
912 // Implicitly locked.
913 getType()->getContext().erase(this);
914 destroyConstantImpl();
917 /// destroyConstant - Remove the constant from the constant table...
919 void ConstantArray::destroyConstant() {
920 // Implicitly locked.
921 getType()->getContext().erase(this);
922 destroyConstantImpl();
925 /// isString - This method returns true if the array is an array of i8, and
926 /// if the elements of the array are all ConstantInt's.
927 bool ConstantArray::isString() const {
928 // Check the element type for i8...
929 if (getType()->getElementType() != Type::Int8Ty)
931 // Check the elements to make sure they are all integers, not constant
933 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
934 if (!isa<ConstantInt>(getOperand(i)))
939 /// isCString - This method returns true if the array is a string (see
940 /// isString) and it ends in a null byte \\0 and does not contains any other
941 /// null bytes except its terminator.
942 bool ConstantArray::isCString() const {
943 // Check the element type for i8...
944 if (getType()->getElementType() != Type::Int8Ty)
947 // Last element must be a null.
948 if (!getOperand(getNumOperands()-1)->isNullValue())
950 // Other elements must be non-null integers.
951 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
952 if (!isa<ConstantInt>(getOperand(i)))
954 if (getOperand(i)->isNullValue())
961 /// getAsString - If the sub-element type of this array is i8
962 /// then this method converts the array to an std::string and returns it.
963 /// Otherwise, it asserts out.
965 std::string ConstantArray::getAsString() const {
966 assert(isString() && "Not a string!");
968 Result.reserve(getNumOperands());
969 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
970 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
975 //---- ConstantStruct::get() implementation...
982 // destroyConstant - Remove the constant from the constant table...
984 void ConstantStruct::destroyConstant() {
985 // Implicitly locked.
986 getType()->getContext().erase(this);
987 destroyConstantImpl();
990 // destroyConstant - Remove the constant from the constant table...
992 void ConstantVector::destroyConstant() {
993 // Implicitly locked.
994 getType()->getContext().erase(this);
995 destroyConstantImpl();
998 /// This function will return true iff every element in this vector constant
999 /// is set to all ones.
1000 /// @returns true iff this constant's emements are all set to all ones.
1001 /// @brief Determine if the value is all ones.
1002 bool ConstantVector::isAllOnesValue() const {
1003 // Check out first element.
1004 const Constant *Elt = getOperand(0);
1005 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1006 if (!CI || !CI->isAllOnesValue()) return false;
1007 // Then make sure all remaining elements point to the same value.
1008 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1009 if (getOperand(I) != Elt) return false;
1014 /// getSplatValue - If this is a splat constant, where all of the
1015 /// elements have the same value, return that value. Otherwise return null.
1016 Constant *ConstantVector::getSplatValue() {
1017 // Check out first element.
1018 Constant *Elt = getOperand(0);
1019 // Then make sure all remaining elements point to the same value.
1020 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1021 if (getOperand(I) != Elt) return 0;
1025 //---- ConstantPointerNull::get() implementation...
1029 // ConstantPointerNull does not take extra "value" argument...
1030 template<class ValType>
1031 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1032 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1033 return new ConstantPointerNull(Ty);
1038 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1039 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1040 // Make everyone now use a constant of the new type...
1041 Constant *New = ConstantPointerNull::get(NewTy);
1042 assert(New != OldC && "Didn't replace constant??");
1043 OldC->uncheckedReplaceAllUsesWith(New);
1044 OldC->destroyConstant(); // This constant is now dead, destroy it.
1049 static ManagedStatic<ValueMap<char, PointerType,
1050 ConstantPointerNull> > NullPtrConstants;
1052 static char getValType(ConstantPointerNull *) {
1057 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1058 // Implicitly locked.
1059 return NullPtrConstants->getOrCreate(Ty, 0);
1062 // destroyConstant - Remove the constant from the constant table...
1064 void ConstantPointerNull::destroyConstant() {
1065 // Implicitly locked.
1066 NullPtrConstants->remove(this);
1067 destroyConstantImpl();
1071 //---- UndefValue::get() implementation...
1075 // UndefValue does not take extra "value" argument...
1076 template<class ValType>
1077 struct ConstantCreator<UndefValue, Type, ValType> {
1078 static UndefValue *create(const Type *Ty, const ValType &V) {
1079 return new UndefValue(Ty);
1084 struct ConvertConstantType<UndefValue, Type> {
1085 static void convert(UndefValue *OldC, const Type *NewTy) {
1086 // Make everyone now use a constant of the new type.
1087 Constant *New = UndefValue::get(NewTy);
1088 assert(New != OldC && "Didn't replace constant??");
1089 OldC->uncheckedReplaceAllUsesWith(New);
1090 OldC->destroyConstant(); // This constant is now dead, destroy it.
1095 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1097 static char getValType(UndefValue *) {
1102 UndefValue *UndefValue::get(const Type *Ty) {
1103 // Implicitly locked.
1104 return UndefValueConstants->getOrCreate(Ty, 0);
1107 // destroyConstant - Remove the constant from the constant table.
1109 void UndefValue::destroyConstant() {
1110 // Implicitly locked.
1111 UndefValueConstants->remove(this);
1112 destroyConstantImpl();
1115 //---- MDNode::get() implementation
1118 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1119 : MetadataBase(Type::MetadataTy, Value::MDNodeVal) {
1120 for (unsigned i = 0; i != NumVals; ++i)
1121 Node.push_back(WeakVH(Vals[i]));
1124 void MDNode::Profile(FoldingSetNodeID &ID) const {
1125 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1129 //---- ConstantExpr::get() implementations...
1134 struct ExprMapKeyType {
1135 typedef SmallVector<unsigned, 4> IndexList;
1137 ExprMapKeyType(unsigned opc,
1138 const std::vector<Constant*> &ops,
1139 unsigned short pred = 0,
1140 const IndexList &inds = IndexList())
1141 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1144 std::vector<Constant*> operands;
1146 bool operator==(const ExprMapKeyType& that) const {
1147 return this->opcode == that.opcode &&
1148 this->predicate == that.predicate &&
1149 this->operands == that.operands &&
1150 this->indices == that.indices;
1152 bool operator<(const ExprMapKeyType & that) const {
1153 return this->opcode < that.opcode ||
1154 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1155 (this->opcode == that.opcode && this->predicate == that.predicate &&
1156 this->operands < that.operands) ||
1157 (this->opcode == that.opcode && this->predicate == that.predicate &&
1158 this->operands == that.operands && this->indices < that.indices);
1161 bool operator!=(const ExprMapKeyType& that) const {
1162 return !(*this == that);
1170 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1171 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1172 unsigned short pred = 0) {
1173 if (Instruction::isCast(V.opcode))
1174 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1175 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1176 V.opcode < Instruction::BinaryOpsEnd))
1177 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1178 if (V.opcode == Instruction::Select)
1179 return new SelectConstantExpr(V.operands[0], V.operands[1],
1181 if (V.opcode == Instruction::ExtractElement)
1182 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1183 if (V.opcode == Instruction::InsertElement)
1184 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1186 if (V.opcode == Instruction::ShuffleVector)
1187 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1189 if (V.opcode == Instruction::InsertValue)
1190 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1192 if (V.opcode == Instruction::ExtractValue)
1193 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1194 if (V.opcode == Instruction::GetElementPtr) {
1195 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1196 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1199 // The compare instructions are weird. We have to encode the predicate
1200 // value and it is combined with the instruction opcode by multiplying
1201 // the opcode by one hundred. We must decode this to get the predicate.
1202 if (V.opcode == Instruction::ICmp)
1203 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1204 V.operands[0], V.operands[1]);
1205 if (V.opcode == Instruction::FCmp)
1206 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1207 V.operands[0], V.operands[1]);
1208 llvm_unreachable("Invalid ConstantExpr!");
1214 struct ConvertConstantType<ConstantExpr, Type> {
1215 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1217 switch (OldC->getOpcode()) {
1218 case Instruction::Trunc:
1219 case Instruction::ZExt:
1220 case Instruction::SExt:
1221 case Instruction::FPTrunc:
1222 case Instruction::FPExt:
1223 case Instruction::UIToFP:
1224 case Instruction::SIToFP:
1225 case Instruction::FPToUI:
1226 case Instruction::FPToSI:
1227 case Instruction::PtrToInt:
1228 case Instruction::IntToPtr:
1229 case Instruction::BitCast:
1230 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1233 case Instruction::Select:
1234 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1235 OldC->getOperand(1),
1236 OldC->getOperand(2));
1239 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1240 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1241 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1242 OldC->getOperand(1));
1244 case Instruction::GetElementPtr:
1245 // Make everyone now use a constant of the new type...
1246 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1247 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1248 &Idx[0], Idx.size());
1252 assert(New != OldC && "Didn't replace constant??");
1253 OldC->uncheckedReplaceAllUsesWith(New);
1254 OldC->destroyConstant(); // This constant is now dead, destroy it.
1257 } // end namespace llvm
1260 static ExprMapKeyType getValType(ConstantExpr *CE) {
1261 std::vector<Constant*> Operands;
1262 Operands.reserve(CE->getNumOperands());
1263 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1264 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1265 return ExprMapKeyType(CE->getOpcode(), Operands,
1266 CE->isCompare() ? CE->getPredicate() : 0,
1268 CE->getIndices() : SmallVector<unsigned, 4>());
1271 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1272 ConstantExpr> > ExprConstants;
1274 /// This is a utility function to handle folding of casts and lookup of the
1275 /// cast in the ExprConstants map. It is used by the various get* methods below.
1276 static inline Constant *getFoldedCast(
1277 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1278 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1279 // Fold a few common cases
1281 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1284 // Look up the constant in the table first to ensure uniqueness
1285 std::vector<Constant*> argVec(1, C);
1286 ExprMapKeyType Key(opc, argVec);
1288 // Implicitly locked.
1289 return ExprConstants->getOrCreate(Ty, Key);
1292 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1293 Instruction::CastOps opc = Instruction::CastOps(oc);
1294 assert(Instruction::isCast(opc) && "opcode out of range");
1295 assert(C && Ty && "Null arguments to getCast");
1296 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1300 llvm_unreachable("Invalid cast opcode");
1302 case Instruction::Trunc: return getTrunc(C, Ty);
1303 case Instruction::ZExt: return getZExt(C, Ty);
1304 case Instruction::SExt: return getSExt(C, Ty);
1305 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1306 case Instruction::FPExt: return getFPExtend(C, Ty);
1307 case Instruction::UIToFP: return getUIToFP(C, Ty);
1308 case Instruction::SIToFP: return getSIToFP(C, Ty);
1309 case Instruction::FPToUI: return getFPToUI(C, Ty);
1310 case Instruction::FPToSI: return getFPToSI(C, Ty);
1311 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1312 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1313 case Instruction::BitCast: return getBitCast(C, Ty);
1318 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1319 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1320 return getCast(Instruction::BitCast, C, Ty);
1321 return getCast(Instruction::ZExt, C, Ty);
1324 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1325 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1326 return getCast(Instruction::BitCast, C, Ty);
1327 return getCast(Instruction::SExt, C, Ty);
1330 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1331 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1332 return getCast(Instruction::BitCast, C, Ty);
1333 return getCast(Instruction::Trunc, C, Ty);
1336 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1337 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1338 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1340 if (Ty->isInteger())
1341 return getCast(Instruction::PtrToInt, S, Ty);
1342 return getCast(Instruction::BitCast, S, Ty);
1345 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1347 assert(C->getType()->isIntOrIntVector() &&
1348 Ty->isIntOrIntVector() && "Invalid cast");
1349 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1350 unsigned DstBits = Ty->getScalarSizeInBits();
1351 Instruction::CastOps opcode =
1352 (SrcBits == DstBits ? Instruction::BitCast :
1353 (SrcBits > DstBits ? Instruction::Trunc :
1354 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1355 return getCast(opcode, C, Ty);
1358 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1359 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1361 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1362 unsigned DstBits = Ty->getScalarSizeInBits();
1363 if (SrcBits == DstBits)
1364 return C; // Avoid a useless cast
1365 Instruction::CastOps opcode =
1366 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1367 return getCast(opcode, C, Ty);
1370 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1372 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1373 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1375 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1376 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1377 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1378 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1379 "SrcTy must be larger than DestTy for Trunc!");
1381 return getFoldedCast(Instruction::Trunc, C, Ty);
1384 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1386 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1387 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1389 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1390 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1391 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1392 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1393 "SrcTy must be smaller than DestTy for SExt!");
1395 return getFoldedCast(Instruction::SExt, C, Ty);
1398 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1400 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1401 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1403 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1404 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1405 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1406 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1407 "SrcTy must be smaller than DestTy for ZExt!");
1409 return getFoldedCast(Instruction::ZExt, C, Ty);
1412 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1414 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1415 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1417 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1418 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1419 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1420 "This is an illegal floating point truncation!");
1421 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1424 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1426 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1427 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1429 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1430 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1431 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1432 "This is an illegal floating point extension!");
1433 return getFoldedCast(Instruction::FPExt, C, Ty);
1436 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1438 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1439 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1441 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1442 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1443 "This is an illegal uint to floating point cast!");
1444 return getFoldedCast(Instruction::UIToFP, C, Ty);
1447 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1449 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1450 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1452 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1453 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1454 "This is an illegal sint to floating point cast!");
1455 return getFoldedCast(Instruction::SIToFP, C, Ty);
1458 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1460 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1461 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1463 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1464 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1465 "This is an illegal floating point to uint cast!");
1466 return getFoldedCast(Instruction::FPToUI, C, Ty);
1469 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1471 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1472 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1474 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1475 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1476 "This is an illegal floating point to sint cast!");
1477 return getFoldedCast(Instruction::FPToSI, C, Ty);
1480 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1481 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1482 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1483 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1486 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1487 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1488 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1489 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1492 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1493 // BitCast implies a no-op cast of type only. No bits change. However, you
1494 // can't cast pointers to anything but pointers.
1496 const Type *SrcTy = C->getType();
1497 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1498 "BitCast cannot cast pointer to non-pointer and vice versa");
1500 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1501 // or nonptr->ptr). For all the other types, the cast is okay if source and
1502 // destination bit widths are identical.
1503 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1504 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1506 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1508 // It is common to ask for a bitcast of a value to its own type, handle this
1510 if (C->getType() == DstTy) return C;
1512 return getFoldedCast(Instruction::BitCast, C, DstTy);
1515 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1516 Constant *C1, Constant *C2) {
1517 // Check the operands for consistency first
1518 assert(Opcode >= Instruction::BinaryOpsBegin &&
1519 Opcode < Instruction::BinaryOpsEnd &&
1520 "Invalid opcode in binary constant expression");
1521 assert(C1->getType() == C2->getType() &&
1522 "Operand types in binary constant expression should match");
1524 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1525 if (Constant *FC = ConstantFoldBinaryInstruction(
1526 getGlobalContext(), Opcode, C1, C2))
1527 return FC; // Fold a few common cases...
1529 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1530 ExprMapKeyType Key(Opcode, argVec);
1532 // Implicitly locked.
1533 return ExprConstants->getOrCreate(ReqTy, Key);
1536 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1537 Constant *C1, Constant *C2) {
1538 switch (predicate) {
1539 default: llvm_unreachable("Invalid CmpInst predicate");
1540 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1541 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1542 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1543 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1544 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1545 case CmpInst::FCMP_TRUE:
1546 return getFCmp(predicate, C1, C2);
1548 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1549 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1550 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1551 case CmpInst::ICMP_SLE:
1552 return getICmp(predicate, C1, C2);
1556 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1557 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1558 if (C1->getType()->isFPOrFPVector()) {
1559 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1560 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1561 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1565 case Instruction::Add:
1566 case Instruction::Sub:
1567 case Instruction::Mul:
1568 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1569 assert(C1->getType()->isIntOrIntVector() &&
1570 "Tried to create an integer operation on a non-integer type!");
1572 case Instruction::FAdd:
1573 case Instruction::FSub:
1574 case Instruction::FMul:
1575 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1576 assert(C1->getType()->isFPOrFPVector() &&
1577 "Tried to create a floating-point operation on a "
1578 "non-floating-point type!");
1580 case Instruction::UDiv:
1581 case Instruction::SDiv:
1582 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1583 assert(C1->getType()->isIntOrIntVector() &&
1584 "Tried to create an arithmetic operation on a non-arithmetic type!");
1586 case Instruction::FDiv:
1587 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1588 assert(C1->getType()->isFPOrFPVector() &&
1589 "Tried to create an arithmetic operation on a non-arithmetic type!");
1591 case Instruction::URem:
1592 case Instruction::SRem:
1593 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1594 assert(C1->getType()->isIntOrIntVector() &&
1595 "Tried to create an arithmetic operation on a non-arithmetic type!");
1597 case Instruction::FRem:
1598 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1599 assert(C1->getType()->isFPOrFPVector() &&
1600 "Tried to create an arithmetic operation on a non-arithmetic type!");
1602 case Instruction::And:
1603 case Instruction::Or:
1604 case Instruction::Xor:
1605 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1606 assert(C1->getType()->isIntOrIntVector() &&
1607 "Tried to create a logical operation on a non-integral type!");
1609 case Instruction::Shl:
1610 case Instruction::LShr:
1611 case Instruction::AShr:
1612 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1613 assert(C1->getType()->isIntOrIntVector() &&
1614 "Tried to create a shift operation on a non-integer type!");
1621 return getTy(C1->getType(), Opcode, C1, C2);
1624 Constant *ConstantExpr::getCompare(unsigned short pred,
1625 Constant *C1, Constant *C2) {
1626 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1627 return getCompareTy(pred, C1, C2);
1630 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1631 Constant *V1, Constant *V2) {
1632 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1634 if (ReqTy == V1->getType())
1635 if (Constant *SC = ConstantFoldSelectInstruction(
1636 getGlobalContext(), C, V1, V2))
1637 return SC; // Fold common cases
1639 std::vector<Constant*> argVec(3, C);
1642 ExprMapKeyType Key(Instruction::Select, argVec);
1644 // Implicitly locked.
1645 return ExprConstants->getOrCreate(ReqTy, Key);
1648 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1651 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1653 cast<PointerType>(ReqTy)->getElementType() &&
1654 "GEP indices invalid!");
1656 if (Constant *FC = ConstantFoldGetElementPtr(
1657 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1658 return FC; // Fold a few common cases...
1660 assert(isa<PointerType>(C->getType()) &&
1661 "Non-pointer type for constant GetElementPtr expression");
1662 // Look up the constant in the table first to ensure uniqueness
1663 std::vector<Constant*> ArgVec;
1664 ArgVec.reserve(NumIdx+1);
1665 ArgVec.push_back(C);
1666 for (unsigned i = 0; i != NumIdx; ++i)
1667 ArgVec.push_back(cast<Constant>(Idxs[i]));
1668 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1670 // Implicitly locked.
1671 return ExprConstants->getOrCreate(ReqTy, Key);
1674 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1676 // Get the result type of the getelementptr!
1678 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1679 assert(Ty && "GEP indices invalid!");
1680 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1681 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1684 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1686 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1691 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1692 assert(LHS->getType() == RHS->getType());
1693 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1694 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1696 if (Constant *FC = ConstantFoldCompareInstruction(
1697 getGlobalContext(),pred, LHS, RHS))
1698 return FC; // Fold a few common cases...
1700 // Look up the constant in the table first to ensure uniqueness
1701 std::vector<Constant*> ArgVec;
1702 ArgVec.push_back(LHS);
1703 ArgVec.push_back(RHS);
1704 // Get the key type with both the opcode and predicate
1705 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1707 // Implicitly locked.
1708 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1712 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1713 assert(LHS->getType() == RHS->getType());
1714 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1716 if (Constant *FC = ConstantFoldCompareInstruction(
1717 getGlobalContext(), pred, LHS, RHS))
1718 return FC; // Fold a few common cases...
1720 // Look up the constant in the table first to ensure uniqueness
1721 std::vector<Constant*> ArgVec;
1722 ArgVec.push_back(LHS);
1723 ArgVec.push_back(RHS);
1724 // Get the key type with both the opcode and predicate
1725 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1727 // Implicitly locked.
1728 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1731 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1733 if (Constant *FC = ConstantFoldExtractElementInstruction(
1734 getGlobalContext(), Val, Idx))
1735 return FC; // Fold a few common cases...
1736 // Look up the constant in the table first to ensure uniqueness
1737 std::vector<Constant*> ArgVec(1, Val);
1738 ArgVec.push_back(Idx);
1739 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1741 // Implicitly locked.
1742 return ExprConstants->getOrCreate(ReqTy, Key);
1745 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1746 assert(isa<VectorType>(Val->getType()) &&
1747 "Tried to create extractelement operation on non-vector type!");
1748 assert(Idx->getType() == Type::Int32Ty &&
1749 "Extractelement index must be i32 type!");
1750 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1754 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1755 Constant *Elt, Constant *Idx) {
1756 if (Constant *FC = ConstantFoldInsertElementInstruction(
1757 getGlobalContext(), Val, Elt, Idx))
1758 return FC; // Fold a few common cases...
1759 // Look up the constant in the table first to ensure uniqueness
1760 std::vector<Constant*> ArgVec(1, Val);
1761 ArgVec.push_back(Elt);
1762 ArgVec.push_back(Idx);
1763 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1765 // Implicitly locked.
1766 return ExprConstants->getOrCreate(ReqTy, Key);
1769 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1771 assert(isa<VectorType>(Val->getType()) &&
1772 "Tried to create insertelement operation on non-vector type!");
1773 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1774 && "Insertelement types must match!");
1775 assert(Idx->getType() == Type::Int32Ty &&
1776 "Insertelement index must be i32 type!");
1777 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1780 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1781 Constant *V2, Constant *Mask) {
1782 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1783 getGlobalContext(), V1, V2, Mask))
1784 return FC; // Fold a few common cases...
1785 // Look up the constant in the table first to ensure uniqueness
1786 std::vector<Constant*> ArgVec(1, V1);
1787 ArgVec.push_back(V2);
1788 ArgVec.push_back(Mask);
1789 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1791 // Implicitly locked.
1792 return ExprConstants->getOrCreate(ReqTy, Key);
1795 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1797 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1798 "Invalid shuffle vector constant expr operands!");
1800 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1801 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1802 const Type *ShufTy = VectorType::get(EltTy, NElts);
1803 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1806 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1808 const unsigned *Idxs, unsigned NumIdx) {
1809 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1810 Idxs+NumIdx) == Val->getType() &&
1811 "insertvalue indices invalid!");
1812 assert(Agg->getType() == ReqTy &&
1813 "insertvalue type invalid!");
1814 assert(Agg->getType()->isFirstClassType() &&
1815 "Non-first-class type for constant InsertValue expression");
1816 Constant *FC = ConstantFoldInsertValueInstruction(
1817 getGlobalContext(), Agg, Val, Idxs, NumIdx);
1818 assert(FC && "InsertValue constant expr couldn't be folded!");
1822 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1823 const unsigned *IdxList, unsigned NumIdx) {
1824 assert(Agg->getType()->isFirstClassType() &&
1825 "Tried to create insertelement operation on non-first-class type!");
1827 const Type *ReqTy = Agg->getType();
1830 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1832 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1833 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1836 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1837 const unsigned *Idxs, unsigned NumIdx) {
1838 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1839 Idxs+NumIdx) == ReqTy &&
1840 "extractvalue indices invalid!");
1841 assert(Agg->getType()->isFirstClassType() &&
1842 "Non-first-class type for constant extractvalue expression");
1843 Constant *FC = ConstantFoldExtractValueInstruction(
1844 getGlobalContext(), Agg, Idxs, NumIdx);
1845 assert(FC && "ExtractValue constant expr couldn't be folded!");
1849 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1850 const unsigned *IdxList, unsigned NumIdx) {
1851 assert(Agg->getType()->isFirstClassType() &&
1852 "Tried to create extractelement operation on non-first-class type!");
1855 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1856 assert(ReqTy && "extractvalue indices invalid!");
1857 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1860 // destroyConstant - Remove the constant from the constant table...
1862 void ConstantExpr::destroyConstant() {
1863 // Implicitly locked.
1864 ExprConstants->remove(this);
1865 destroyConstantImpl();
1868 const char *ConstantExpr::getOpcodeName() const {
1869 return Instruction::getOpcodeName(getOpcode());
1872 //===----------------------------------------------------------------------===//
1873 // replaceUsesOfWithOnConstant implementations
1875 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1876 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1879 /// Note that we intentionally replace all uses of From with To here. Consider
1880 /// a large array that uses 'From' 1000 times. By handling this case all here,
1881 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1882 /// single invocation handles all 1000 uses. Handling them one at a time would
1883 /// work, but would be really slow because it would have to unique each updated
1885 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1887 Constant *Replacement =
1888 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
1890 if (!Replacement) return;
1892 // Otherwise, I do need to replace this with an existing value.
1893 assert(Replacement != this && "I didn't contain From!");
1895 // Everyone using this now uses the replacement.
1896 uncheckedReplaceAllUsesWith(Replacement);
1898 // Delete the old constant!
1902 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1904 Constant* Replacement =
1905 getType()->getContext().replaceUsesOfWithOnConstant(this, From, To, U);
1906 if (!Replacement) return;
1908 // Everyone using this now uses the replacement.
1909 uncheckedReplaceAllUsesWith(Replacement);
1911 // Delete the old constant!
1915 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
1917 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1919 std::vector<Constant*> Values;
1920 Values.reserve(getNumOperands()); // Build replacement array...
1921 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1922 Constant *Val = getOperand(i);
1923 if (Val == From) Val = cast<Constant>(To);
1924 Values.push_back(Val);
1927 Constant *Replacement =
1928 getType()->getContext().getConstantVector(getType(), Values);
1929 assert(Replacement != this && "I didn't contain From!");
1931 // Everyone using this now uses the replacement.
1932 uncheckedReplaceAllUsesWith(Replacement);
1934 // Delete the old constant!
1938 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
1940 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
1941 Constant *To = cast<Constant>(ToV);
1943 Constant *Replacement = 0;
1944 if (getOpcode() == Instruction::GetElementPtr) {
1945 SmallVector<Constant*, 8> Indices;
1946 Constant *Pointer = getOperand(0);
1947 Indices.reserve(getNumOperands()-1);
1948 if (Pointer == From) Pointer = To;
1950 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1951 Constant *Val = getOperand(i);
1952 if (Val == From) Val = To;
1953 Indices.push_back(Val);
1955 Replacement = ConstantExpr::getGetElementPtr(Pointer,
1956 &Indices[0], Indices.size());
1957 } else if (getOpcode() == Instruction::ExtractValue) {
1958 Constant *Agg = getOperand(0);
1959 if (Agg == From) Agg = To;
1961 const SmallVector<unsigned, 4> &Indices = getIndices();
1962 Replacement = ConstantExpr::getExtractValue(Agg,
1963 &Indices[0], Indices.size());
1964 } else if (getOpcode() == Instruction::InsertValue) {
1965 Constant *Agg = getOperand(0);
1966 Constant *Val = getOperand(1);
1967 if (Agg == From) Agg = To;
1968 if (Val == From) Val = To;
1970 const SmallVector<unsigned, 4> &Indices = getIndices();
1971 Replacement = ConstantExpr::getInsertValue(Agg, Val,
1972 &Indices[0], Indices.size());
1973 } else if (isCast()) {
1974 assert(getOperand(0) == From && "Cast only has one use!");
1975 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
1976 } else if (getOpcode() == Instruction::Select) {
1977 Constant *C1 = getOperand(0);
1978 Constant *C2 = getOperand(1);
1979 Constant *C3 = getOperand(2);
1980 if (C1 == From) C1 = To;
1981 if (C2 == From) C2 = To;
1982 if (C3 == From) C3 = To;
1983 Replacement = ConstantExpr::getSelect(C1, C2, C3);
1984 } else if (getOpcode() == Instruction::ExtractElement) {
1985 Constant *C1 = getOperand(0);
1986 Constant *C2 = getOperand(1);
1987 if (C1 == From) C1 = To;
1988 if (C2 == From) C2 = To;
1989 Replacement = ConstantExpr::getExtractElement(C1, C2);
1990 } else if (getOpcode() == Instruction::InsertElement) {
1991 Constant *C1 = getOperand(0);
1992 Constant *C2 = getOperand(1);
1993 Constant *C3 = getOperand(1);
1994 if (C1 == From) C1 = To;
1995 if (C2 == From) C2 = To;
1996 if (C3 == From) C3 = To;
1997 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
1998 } else if (getOpcode() == Instruction::ShuffleVector) {
1999 Constant *C1 = getOperand(0);
2000 Constant *C2 = getOperand(1);
2001 Constant *C3 = getOperand(2);
2002 if (C1 == From) C1 = To;
2003 if (C2 == From) C2 = To;
2004 if (C3 == From) C3 = To;
2005 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2006 } else if (isCompare()) {
2007 Constant *C1 = getOperand(0);
2008 Constant *C2 = getOperand(1);
2009 if (C1 == From) C1 = To;
2010 if (C2 == From) C2 = To;
2011 if (getOpcode() == Instruction::ICmp)
2012 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2014 assert(getOpcode() == Instruction::FCmp);
2015 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2017 } else if (getNumOperands() == 2) {
2018 Constant *C1 = getOperand(0);
2019 Constant *C2 = getOperand(1);
2020 if (C1 == From) C1 = To;
2021 if (C2 == From) C2 = To;
2022 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2024 llvm_unreachable("Unknown ConstantExpr type!");
2028 assert(Replacement != this && "I didn't contain From!");
2030 // Everyone using this now uses the replacement.
2031 uncheckedReplaceAllUsesWith(Replacement);
2033 // Delete the old constant!
2037 void MDNode::replaceElement(Value *From, Value *To) {
2038 SmallVector<Value*, 4> Values;
2039 Values.reserve(getNumElements()); // Build replacement array...
2040 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2041 Value *Val = getElement(i);
2042 if (Val == From) Val = To;
2043 Values.push_back(Val);
2046 MDNode *Replacement =
2047 getType()->getContext().getMDNode(&Values[0], Values.size());
2048 assert(Replacement != this && "I didn't contain From!");
2050 uncheckedReplaceAllUsesWith(Replacement);