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 //===----------------------------------------------------------------------===//
245 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
246 if (Ty == Type::FloatTy)
247 return &APFloat::IEEEsingle;
248 if (Ty == Type::DoubleTy)
249 return &APFloat::IEEEdouble;
250 if (Ty == Type::X86_FP80Ty)
251 return &APFloat::x87DoubleExtended;
252 else if (Ty == Type::FP128Ty)
253 return &APFloat::IEEEquad;
255 assert(Ty == Type::PPC_FP128Ty && "Unknown FP format");
256 return &APFloat::PPCDoubleDouble;
259 /// get() - This returns a constant fp for the specified value in the
260 /// specified type. This should only be used for simple constant values like
261 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
262 Constant* ConstantFP::get(const Type* Ty, double V) {
263 LLVMContext &Context = Ty->getContext();
267 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
268 APFloat::rmNearestTiesToEven, &ignored);
269 Constant *C = get(Context, FV);
271 // For vectors, broadcast the value.
272 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
273 return Context.getConstantVector(
274 std::vector<Constant *>(VTy->getNumElements(), C));
279 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
280 LLVMContext &Context = Ty->getContext();
281 APFloat apf = cast <ConstantFP>(Context.getNullValue(Ty))->getValueAPF();
283 return get(Context, apf);
287 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
288 LLVMContext &Context = Ty->getContext();
289 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
290 if (PTy->getElementType()->isFloatingPoint()) {
291 std::vector<Constant*> zeros(PTy->getNumElements(),
292 getNegativeZero(PTy->getElementType()));
293 return Context.getConstantVector(PTy, zeros);
296 if (Ty->isFloatingPoint())
297 return getNegativeZero(Ty);
299 return Context.getNullValue(Ty);
303 // ConstantFP accessors.
304 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
305 DenseMapAPFloatKeyInfo::KeyTy Key(V);
307 LLVMContextImpl* pImpl = Context.pImpl;
309 pImpl->ConstantsLock.reader_acquire();
310 ConstantFP *&Slot = pImpl->FPConstants[Key];
311 pImpl->ConstantsLock.reader_release();
314 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
315 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
318 if (&V.getSemantics() == &APFloat::IEEEsingle)
320 else if (&V.getSemantics() == &APFloat::IEEEdouble)
322 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
323 Ty = Type::X86_FP80Ty;
324 else if (&V.getSemantics() == &APFloat::IEEEquad)
327 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
328 "Unknown FP format");
329 Ty = Type::PPC_FP128Ty;
331 NewSlot = new ConstantFP(Ty, V);
340 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
341 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
342 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
346 bool ConstantFP::isNullValue() const {
347 return Val.isZero() && !Val.isNegative();
350 bool ConstantFP::isExactlyValue(const APFloat& V) const {
351 return Val.bitwiseIsEqual(V);
354 //===----------------------------------------------------------------------===//
355 // ConstantXXX Classes
356 //===----------------------------------------------------------------------===//
359 ConstantArray::ConstantArray(const ArrayType *T,
360 const std::vector<Constant*> &V)
361 : Constant(T, ConstantArrayVal,
362 OperandTraits<ConstantArray>::op_end(this) - V.size(),
364 assert(V.size() == T->getNumElements() &&
365 "Invalid initializer vector for constant array");
366 Use *OL = OperandList;
367 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
370 assert((C->getType() == T->getElementType() ||
372 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
373 "Initializer for array element doesn't match array element type!");
378 Constant *ConstantArray::get(const ArrayType *Ty,
379 const std::vector<Constant*> &V) {
380 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
381 // If this is an all-zero array, return a ConstantAggregateZero object
384 if (!C->isNullValue()) {
385 // Implicitly locked.
386 return pImpl->ArrayConstants.getOrCreate(Ty, V);
388 for (unsigned i = 1, e = V.size(); i != e; ++i)
390 // Implicitly locked.
391 return pImpl->ArrayConstants.getOrCreate(Ty, V);
395 return Ty->getContext().getConstantAggregateZero(Ty);
399 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
401 // FIXME: make this the primary ctor method.
402 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
405 /// ConstantArray::get(const string&) - Return an array that is initialized to
406 /// contain the specified string. If length is zero then a null terminator is
407 /// added to the specified string so that it may be used in a natural way.
408 /// Otherwise, the length parameter specifies how much of the string to use
409 /// and it won't be null terminated.
411 Constant* ConstantArray::get(const StringRef &Str, bool AddNull) {
412 std::vector<Constant*> ElementVals;
413 for (unsigned i = 0; i < Str.size(); ++i)
414 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, Str[i]));
416 // Add a null terminator to the string...
418 ElementVals.push_back(ConstantInt::get(Type::Int8Ty, 0));
421 ArrayType *ATy = ArrayType::get(Type::Int8Ty, ElementVals.size());
422 return get(ATy, ElementVals);
427 ConstantStruct::ConstantStruct(const StructType *T,
428 const std::vector<Constant*> &V)
429 : Constant(T, ConstantStructVal,
430 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
432 assert(V.size() == T->getNumElements() &&
433 "Invalid initializer vector for constant structure");
434 Use *OL = OperandList;
435 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
438 assert((C->getType() == T->getElementType(I-V.begin()) ||
439 ((T->getElementType(I-V.begin())->isAbstract() ||
440 C->getType()->isAbstract()) &&
441 T->getElementType(I-V.begin())->getTypeID() ==
442 C->getType()->getTypeID())) &&
443 "Initializer for struct element doesn't match struct element type!");
448 // ConstantStruct accessors.
449 Constant* ConstantStruct::get(const StructType* T,
450 const std::vector<Constant*>& V) {
451 LLVMContextImpl* pImpl = T->getContext().pImpl;
453 // Create a ConstantAggregateZero value if all elements are zeros...
454 for (unsigned i = 0, e = V.size(); i != e; ++i)
455 if (!V[i]->isNullValue())
456 // Implicitly locked.
457 return pImpl->StructConstants.getOrCreate(T, V);
459 return T->getContext().getConstantAggregateZero(T);
462 Constant* ConstantStruct::get(const std::vector<Constant*>& V, bool packed) {
463 std::vector<const Type*> StructEls;
464 StructEls.reserve(V.size());
465 for (unsigned i = 0, e = V.size(); i != e; ++i)
466 StructEls.push_back(V[i]->getType());
467 return get(StructType::get(StructEls, packed), V);
470 Constant* ConstantStruct::get(Constant* const *Vals, unsigned NumVals,
472 // FIXME: make this the primary ctor method.
473 return get(std::vector<Constant*>(Vals, Vals+NumVals), Packed);
476 ConstantVector::ConstantVector(const VectorType *T,
477 const std::vector<Constant*> &V)
478 : Constant(T, ConstantVectorVal,
479 OperandTraits<ConstantVector>::op_end(this) - V.size(),
481 Use *OL = OperandList;
482 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
485 assert((C->getType() == T->getElementType() ||
487 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
488 "Initializer for vector element doesn't match vector element type!");
495 // We declare several classes private to this file, so use an anonymous
499 /// UnaryConstantExpr - This class is private to Constants.cpp, and is used
500 /// behind the scenes to implement unary constant exprs.
501 class VISIBILITY_HIDDEN UnaryConstantExpr : public ConstantExpr {
502 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
504 // allocate space for exactly one operand
505 void *operator new(size_t s) {
506 return User::operator new(s, 1);
508 UnaryConstantExpr(unsigned Opcode, Constant *C, const Type *Ty)
509 : ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
512 /// Transparently provide more efficient getOperand methods.
513 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
516 /// BinaryConstantExpr - This class is private to Constants.cpp, and is used
517 /// behind the scenes to implement binary constant exprs.
518 class VISIBILITY_HIDDEN BinaryConstantExpr : public ConstantExpr {
519 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
521 // allocate space for exactly two operands
522 void *operator new(size_t s) {
523 return User::operator new(s, 2);
525 BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2)
526 : ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
530 /// Transparently provide more efficient getOperand methods.
531 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
534 /// SelectConstantExpr - This class is private to Constants.cpp, and is used
535 /// behind the scenes to implement select constant exprs.
536 class VISIBILITY_HIDDEN SelectConstantExpr : public ConstantExpr {
537 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
539 // allocate space for exactly three operands
540 void *operator new(size_t s) {
541 return User::operator new(s, 3);
543 SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
544 : ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
549 /// Transparently provide more efficient getOperand methods.
550 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
553 /// ExtractElementConstantExpr - This class is private to
554 /// Constants.cpp, and is used behind the scenes to implement
555 /// extractelement constant exprs.
556 class VISIBILITY_HIDDEN ExtractElementConstantExpr : public ConstantExpr {
557 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
559 // allocate space for exactly two operands
560 void *operator new(size_t s) {
561 return User::operator new(s, 2);
563 ExtractElementConstantExpr(Constant *C1, Constant *C2)
564 : ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
565 Instruction::ExtractElement, &Op<0>(), 2) {
569 /// Transparently provide more efficient getOperand methods.
570 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
573 /// InsertElementConstantExpr - This class is private to
574 /// Constants.cpp, and is used behind the scenes to implement
575 /// insertelement constant exprs.
576 class VISIBILITY_HIDDEN InsertElementConstantExpr : public ConstantExpr {
577 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
579 // allocate space for exactly three operands
580 void *operator new(size_t s) {
581 return User::operator new(s, 3);
583 InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
584 : ConstantExpr(C1->getType(), Instruction::InsertElement,
590 /// Transparently provide more efficient getOperand methods.
591 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
594 /// ShuffleVectorConstantExpr - This class is private to
595 /// Constants.cpp, and is used behind the scenes to implement
596 /// shufflevector constant exprs.
597 class VISIBILITY_HIDDEN ShuffleVectorConstantExpr : public ConstantExpr {
598 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
600 // allocate space for exactly three operands
601 void *operator new(size_t s) {
602 return User::operator new(s, 3);
604 ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
605 : ConstantExpr(VectorType::get(
606 cast<VectorType>(C1->getType())->getElementType(),
607 cast<VectorType>(C3->getType())->getNumElements()),
608 Instruction::ShuffleVector,
614 /// Transparently provide more efficient getOperand methods.
615 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
618 /// ExtractValueConstantExpr - This class is private to
619 /// Constants.cpp, and is used behind the scenes to implement
620 /// extractvalue constant exprs.
621 class VISIBILITY_HIDDEN ExtractValueConstantExpr : public ConstantExpr {
622 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
624 // allocate space for exactly one operand
625 void *operator new(size_t s) {
626 return User::operator new(s, 1);
628 ExtractValueConstantExpr(Constant *Agg,
629 const SmallVector<unsigned, 4> &IdxList,
631 : ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
636 /// Indices - These identify which value to extract.
637 const SmallVector<unsigned, 4> Indices;
639 /// Transparently provide more efficient getOperand methods.
640 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
643 /// InsertValueConstantExpr - This class is private to
644 /// Constants.cpp, and is used behind the scenes to implement
645 /// insertvalue constant exprs.
646 class VISIBILITY_HIDDEN InsertValueConstantExpr : public ConstantExpr {
647 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
649 // allocate space for exactly one operand
650 void *operator new(size_t s) {
651 return User::operator new(s, 2);
653 InsertValueConstantExpr(Constant *Agg, Constant *Val,
654 const SmallVector<unsigned, 4> &IdxList,
656 : ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
662 /// Indices - These identify the position for the insertion.
663 const SmallVector<unsigned, 4> Indices;
665 /// Transparently provide more efficient getOperand methods.
666 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
670 /// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
671 /// used behind the scenes to implement getelementpr constant exprs.
672 class VISIBILITY_HIDDEN GetElementPtrConstantExpr : public ConstantExpr {
673 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
676 static GetElementPtrConstantExpr *Create(Constant *C,
677 const std::vector<Constant*>&IdxList,
678 const Type *DestTy) {
680 new(IdxList.size() + 1) GetElementPtrConstantExpr(C, IdxList, DestTy);
682 /// Transparently provide more efficient getOperand methods.
683 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
686 // CompareConstantExpr - This class is private to Constants.cpp, and is used
687 // behind the scenes to implement ICmp and FCmp constant expressions. This is
688 // needed in order to store the predicate value for these instructions.
689 struct VISIBILITY_HIDDEN CompareConstantExpr : public ConstantExpr {
690 void *operator new(size_t, unsigned); // DO NOT IMPLEMENT
691 // allocate space for exactly two operands
692 void *operator new(size_t s) {
693 return User::operator new(s, 2);
695 unsigned short predicate;
696 CompareConstantExpr(const Type *ty, Instruction::OtherOps opc,
697 unsigned short pred, Constant* LHS, Constant* RHS)
698 : ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
702 /// Transparently provide more efficient getOperand methods.
703 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
706 } // end anonymous namespace
709 struct OperandTraits<UnaryConstantExpr> : FixedNumOperandTraits<1> {
711 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
714 struct OperandTraits<BinaryConstantExpr> : FixedNumOperandTraits<2> {
716 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
719 struct OperandTraits<SelectConstantExpr> : FixedNumOperandTraits<3> {
721 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
724 struct OperandTraits<ExtractElementConstantExpr> : FixedNumOperandTraits<2> {
726 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
729 struct OperandTraits<InsertElementConstantExpr> : FixedNumOperandTraits<3> {
731 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
734 struct OperandTraits<ShuffleVectorConstantExpr> : FixedNumOperandTraits<3> {
736 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
739 struct OperandTraits<ExtractValueConstantExpr> : FixedNumOperandTraits<1> {
741 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
744 struct OperandTraits<InsertValueConstantExpr> : FixedNumOperandTraits<2> {
746 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
749 struct OperandTraits<GetElementPtrConstantExpr> : VariadicOperandTraits<1> {
752 GetElementPtrConstantExpr::GetElementPtrConstantExpr
754 const std::vector<Constant*> &IdxList,
756 : ConstantExpr(DestTy, Instruction::GetElementPtr,
757 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
758 - (IdxList.size()+1),
761 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
762 OperandList[i+1] = IdxList[i];
765 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
769 struct OperandTraits<CompareConstantExpr> : FixedNumOperandTraits<2> {
771 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
774 } // End llvm namespace
777 // Utility function for determining if a ConstantExpr is a CastOp or not. This
778 // can't be inline because we don't want to #include Instruction.h into
780 bool ConstantExpr::isCast() const {
781 return Instruction::isCast(getOpcode());
784 bool ConstantExpr::isCompare() const {
785 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
788 bool ConstantExpr::hasIndices() const {
789 return getOpcode() == Instruction::ExtractValue ||
790 getOpcode() == Instruction::InsertValue;
793 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
794 if (const ExtractValueConstantExpr *EVCE =
795 dyn_cast<ExtractValueConstantExpr>(this))
796 return EVCE->Indices;
798 return cast<InsertValueConstantExpr>(this)->Indices;
801 unsigned ConstantExpr::getPredicate() const {
802 assert(getOpcode() == Instruction::FCmp ||
803 getOpcode() == Instruction::ICmp);
804 return ((const CompareConstantExpr*)this)->predicate;
807 /// getWithOperandReplaced - Return a constant expression identical to this
808 /// one, but with the specified operand set to the specified value.
810 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
811 assert(OpNo < getNumOperands() && "Operand num is out of range!");
812 assert(Op->getType() == getOperand(OpNo)->getType() &&
813 "Replacing operand with value of different type!");
814 if (getOperand(OpNo) == Op)
815 return const_cast<ConstantExpr*>(this);
817 Constant *Op0, *Op1, *Op2;
818 switch (getOpcode()) {
819 case Instruction::Trunc:
820 case Instruction::ZExt:
821 case Instruction::SExt:
822 case Instruction::FPTrunc:
823 case Instruction::FPExt:
824 case Instruction::UIToFP:
825 case Instruction::SIToFP:
826 case Instruction::FPToUI:
827 case Instruction::FPToSI:
828 case Instruction::PtrToInt:
829 case Instruction::IntToPtr:
830 case Instruction::BitCast:
831 return ConstantExpr::getCast(getOpcode(), Op, getType());
832 case Instruction::Select:
833 Op0 = (OpNo == 0) ? Op : getOperand(0);
834 Op1 = (OpNo == 1) ? Op : getOperand(1);
835 Op2 = (OpNo == 2) ? Op : getOperand(2);
836 return ConstantExpr::getSelect(Op0, Op1, Op2);
837 case Instruction::InsertElement:
838 Op0 = (OpNo == 0) ? Op : getOperand(0);
839 Op1 = (OpNo == 1) ? Op : getOperand(1);
840 Op2 = (OpNo == 2) ? Op : getOperand(2);
841 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
842 case Instruction::ExtractElement:
843 Op0 = (OpNo == 0) ? Op : getOperand(0);
844 Op1 = (OpNo == 1) ? Op : getOperand(1);
845 return ConstantExpr::getExtractElement(Op0, Op1);
846 case Instruction::ShuffleVector:
847 Op0 = (OpNo == 0) ? Op : getOperand(0);
848 Op1 = (OpNo == 1) ? Op : getOperand(1);
849 Op2 = (OpNo == 2) ? Op : getOperand(2);
850 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
851 case Instruction::GetElementPtr: {
852 SmallVector<Constant*, 8> Ops;
853 Ops.resize(getNumOperands()-1);
854 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
855 Ops[i-1] = getOperand(i);
857 return ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
859 return ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
862 assert(getNumOperands() == 2 && "Must be binary operator?");
863 Op0 = (OpNo == 0) ? Op : getOperand(0);
864 Op1 = (OpNo == 1) ? Op : getOperand(1);
865 return ConstantExpr::get(getOpcode(), Op0, Op1);
869 /// getWithOperands - This returns the current constant expression with the
870 /// operands replaced with the specified values. The specified operands must
871 /// match count and type with the existing ones.
872 Constant *ConstantExpr::
873 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
874 assert(NumOps == getNumOperands() && "Operand count mismatch!");
875 bool AnyChange = false;
876 for (unsigned i = 0; i != NumOps; ++i) {
877 assert(Ops[i]->getType() == getOperand(i)->getType() &&
878 "Operand type mismatch!");
879 AnyChange |= Ops[i] != getOperand(i);
881 if (!AnyChange) // No operands changed, return self.
882 return const_cast<ConstantExpr*>(this);
884 switch (getOpcode()) {
885 case Instruction::Trunc:
886 case Instruction::ZExt:
887 case Instruction::SExt:
888 case Instruction::FPTrunc:
889 case Instruction::FPExt:
890 case Instruction::UIToFP:
891 case Instruction::SIToFP:
892 case Instruction::FPToUI:
893 case Instruction::FPToSI:
894 case Instruction::PtrToInt:
895 case Instruction::IntToPtr:
896 case Instruction::BitCast:
897 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
898 case Instruction::Select:
899 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
900 case Instruction::InsertElement:
901 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
902 case Instruction::ExtractElement:
903 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
904 case Instruction::ShuffleVector:
905 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
906 case Instruction::GetElementPtr:
907 return ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
908 case Instruction::ICmp:
909 case Instruction::FCmp:
910 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
912 assert(getNumOperands() == 2 && "Must be binary operator?");
913 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1]);
918 //===----------------------------------------------------------------------===//
919 // isValueValidForType implementations
921 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
922 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
923 if (Ty == Type::Int1Ty)
924 return Val == 0 || Val == 1;
926 return true; // always true, has to fit in largest type
927 uint64_t Max = (1ll << NumBits) - 1;
931 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
932 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
933 if (Ty == Type::Int1Ty)
934 return Val == 0 || Val == 1 || Val == -1;
936 return true; // always true, has to fit in largest type
937 int64_t Min = -(1ll << (NumBits-1));
938 int64_t Max = (1ll << (NumBits-1)) - 1;
939 return (Val >= Min && Val <= Max);
942 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
943 // convert modifies in place, so make a copy.
944 APFloat Val2 = APFloat(Val);
946 switch (Ty->getTypeID()) {
948 return false; // These can't be represented as floating point!
950 // FIXME rounding mode needs to be more flexible
951 case Type::FloatTyID: {
952 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
954 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
957 case Type::DoubleTyID: {
958 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
959 &Val2.getSemantics() == &APFloat::IEEEdouble)
961 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
964 case Type::X86_FP80TyID:
965 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
966 &Val2.getSemantics() == &APFloat::IEEEdouble ||
967 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
968 case Type::FP128TyID:
969 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
970 &Val2.getSemantics() == &APFloat::IEEEdouble ||
971 &Val2.getSemantics() == &APFloat::IEEEquad;
972 case Type::PPC_FP128TyID:
973 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
974 &Val2.getSemantics() == &APFloat::IEEEdouble ||
975 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
979 //===----------------------------------------------------------------------===//
980 // Factory Function Implementation
982 /// destroyConstant - Remove the constant from the constant table...
984 void ConstantAggregateZero::destroyConstant() {
985 // Implicitly locked.
986 getType()->getContext().erase(this);
987 destroyConstantImpl();
990 /// destroyConstant - Remove the constant from the constant table...
992 void ConstantArray::destroyConstant() {
993 // Implicitly locked.
994 getType()->getContext().pImpl->ArrayConstants.remove(this);
995 destroyConstantImpl();
998 /// isString - This method returns true if the array is an array of i8, and
999 /// if the elements of the array are all ConstantInt's.
1000 bool ConstantArray::isString() const {
1001 // Check the element type for i8...
1002 if (getType()->getElementType() != Type::Int8Ty)
1004 // Check the elements to make sure they are all integers, not constant
1006 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1007 if (!isa<ConstantInt>(getOperand(i)))
1012 /// isCString - This method returns true if the array is a string (see
1013 /// isString) and it ends in a null byte \\0 and does not contains any other
1014 /// null bytes except its terminator.
1015 bool ConstantArray::isCString() const {
1016 // Check the element type for i8...
1017 if (getType()->getElementType() != Type::Int8Ty)
1020 // Last element must be a null.
1021 if (!getOperand(getNumOperands()-1)->isNullValue())
1023 // Other elements must be non-null integers.
1024 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1025 if (!isa<ConstantInt>(getOperand(i)))
1027 if (getOperand(i)->isNullValue())
1034 /// getAsString - If the sub-element type of this array is i8
1035 /// then this method converts the array to an std::string and returns it.
1036 /// Otherwise, it asserts out.
1038 std::string ConstantArray::getAsString() const {
1039 assert(isString() && "Not a string!");
1041 Result.reserve(getNumOperands());
1042 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1043 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1048 //---- ConstantStruct::get() implementation...
1055 // destroyConstant - Remove the constant from the constant table...
1057 void ConstantStruct::destroyConstant() {
1058 // Implicitly locked.
1059 getType()->getContext().pImpl->StructConstants.remove(this);
1060 destroyConstantImpl();
1063 // destroyConstant - Remove the constant from the constant table...
1065 void ConstantVector::destroyConstant() {
1066 // Implicitly locked.
1067 getType()->getContext().erase(this);
1068 destroyConstantImpl();
1071 /// This function will return true iff every element in this vector constant
1072 /// is set to all ones.
1073 /// @returns true iff this constant's emements are all set to all ones.
1074 /// @brief Determine if the value is all ones.
1075 bool ConstantVector::isAllOnesValue() const {
1076 // Check out first element.
1077 const Constant *Elt = getOperand(0);
1078 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1079 if (!CI || !CI->isAllOnesValue()) return false;
1080 // Then make sure all remaining elements point to the same value.
1081 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1082 if (getOperand(I) != Elt) return false;
1087 /// getSplatValue - If this is a splat constant, where all of the
1088 /// elements have the same value, return that value. Otherwise return null.
1089 Constant *ConstantVector::getSplatValue() {
1090 // Check out first element.
1091 Constant *Elt = getOperand(0);
1092 // Then make sure all remaining elements point to the same value.
1093 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1094 if (getOperand(I) != Elt) return 0;
1098 //---- ConstantPointerNull::get() implementation...
1102 // ConstantPointerNull does not take extra "value" argument...
1103 template<class ValType>
1104 struct ConstantCreator<ConstantPointerNull, PointerType, ValType> {
1105 static ConstantPointerNull *create(const PointerType *Ty, const ValType &V){
1106 return new ConstantPointerNull(Ty);
1111 struct ConvertConstantType<ConstantPointerNull, PointerType> {
1112 static void convert(ConstantPointerNull *OldC, const PointerType *NewTy) {
1113 // Make everyone now use a constant of the new type...
1114 Constant *New = ConstantPointerNull::get(NewTy);
1115 assert(New != OldC && "Didn't replace constant??");
1116 OldC->uncheckedReplaceAllUsesWith(New);
1117 OldC->destroyConstant(); // This constant is now dead, destroy it.
1122 static ManagedStatic<ValueMap<char, PointerType,
1123 ConstantPointerNull> > NullPtrConstants;
1125 static char getValType(ConstantPointerNull *) {
1130 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1131 // Implicitly locked.
1132 return NullPtrConstants->getOrCreate(Ty, 0);
1135 // destroyConstant - Remove the constant from the constant table...
1137 void ConstantPointerNull::destroyConstant() {
1138 // Implicitly locked.
1139 NullPtrConstants->remove(this);
1140 destroyConstantImpl();
1144 //---- UndefValue::get() implementation...
1148 // UndefValue does not take extra "value" argument...
1149 template<class ValType>
1150 struct ConstantCreator<UndefValue, Type, ValType> {
1151 static UndefValue *create(const Type *Ty, const ValType &V) {
1152 return new UndefValue(Ty);
1157 struct ConvertConstantType<UndefValue, Type> {
1158 static void convert(UndefValue *OldC, const Type *NewTy) {
1159 // Make everyone now use a constant of the new type.
1160 Constant *New = UndefValue::get(NewTy);
1161 assert(New != OldC && "Didn't replace constant??");
1162 OldC->uncheckedReplaceAllUsesWith(New);
1163 OldC->destroyConstant(); // This constant is now dead, destroy it.
1168 static ManagedStatic<ValueMap<char, Type, UndefValue> > UndefValueConstants;
1170 static char getValType(UndefValue *) {
1175 UndefValue *UndefValue::get(const Type *Ty) {
1176 // Implicitly locked.
1177 return UndefValueConstants->getOrCreate(Ty, 0);
1180 // destroyConstant - Remove the constant from the constant table.
1182 void UndefValue::destroyConstant() {
1183 // Implicitly locked.
1184 UndefValueConstants->remove(this);
1185 destroyConstantImpl();
1188 //---- MDNode::get() implementation
1191 MDNode::MDNode(Value*const* Vals, unsigned NumVals)
1192 : MetadataBase(Type::MetadataTy, Value::MDNodeVal) {
1193 for (unsigned i = 0; i != NumVals; ++i)
1194 Node.push_back(WeakVH(Vals[i]));
1197 void MDNode::Profile(FoldingSetNodeID &ID) const {
1198 for (const_elem_iterator I = elem_begin(), E = elem_end(); I != E; ++I)
1202 //---- ConstantExpr::get() implementations...
1207 struct ExprMapKeyType {
1208 typedef SmallVector<unsigned, 4> IndexList;
1210 ExprMapKeyType(unsigned opc,
1211 const std::vector<Constant*> &ops,
1212 unsigned short pred = 0,
1213 const IndexList &inds = IndexList())
1214 : opcode(opc), predicate(pred), operands(ops), indices(inds) {}
1217 std::vector<Constant*> operands;
1219 bool operator==(const ExprMapKeyType& that) const {
1220 return this->opcode == that.opcode &&
1221 this->predicate == that.predicate &&
1222 this->operands == that.operands &&
1223 this->indices == that.indices;
1225 bool operator<(const ExprMapKeyType & that) const {
1226 return this->opcode < that.opcode ||
1227 (this->opcode == that.opcode && this->predicate < that.predicate) ||
1228 (this->opcode == that.opcode && this->predicate == that.predicate &&
1229 this->operands < that.operands) ||
1230 (this->opcode == that.opcode && this->predicate == that.predicate &&
1231 this->operands == that.operands && this->indices < that.indices);
1234 bool operator!=(const ExprMapKeyType& that) const {
1235 return !(*this == that);
1243 struct ConstantCreator<ConstantExpr, Type, ExprMapKeyType> {
1244 static ConstantExpr *create(const Type *Ty, const ExprMapKeyType &V,
1245 unsigned short pred = 0) {
1246 if (Instruction::isCast(V.opcode))
1247 return new UnaryConstantExpr(V.opcode, V.operands[0], Ty);
1248 if ((V.opcode >= Instruction::BinaryOpsBegin &&
1249 V.opcode < Instruction::BinaryOpsEnd))
1250 return new BinaryConstantExpr(V.opcode, V.operands[0], V.operands[1]);
1251 if (V.opcode == Instruction::Select)
1252 return new SelectConstantExpr(V.operands[0], V.operands[1],
1254 if (V.opcode == Instruction::ExtractElement)
1255 return new ExtractElementConstantExpr(V.operands[0], V.operands[1]);
1256 if (V.opcode == Instruction::InsertElement)
1257 return new InsertElementConstantExpr(V.operands[0], V.operands[1],
1259 if (V.opcode == Instruction::ShuffleVector)
1260 return new ShuffleVectorConstantExpr(V.operands[0], V.operands[1],
1262 if (V.opcode == Instruction::InsertValue)
1263 return new InsertValueConstantExpr(V.operands[0], V.operands[1],
1265 if (V.opcode == Instruction::ExtractValue)
1266 return new ExtractValueConstantExpr(V.operands[0], V.indices, Ty);
1267 if (V.opcode == Instruction::GetElementPtr) {
1268 std::vector<Constant*> IdxList(V.operands.begin()+1, V.operands.end());
1269 return GetElementPtrConstantExpr::Create(V.operands[0], IdxList, Ty);
1272 // The compare instructions are weird. We have to encode the predicate
1273 // value and it is combined with the instruction opcode by multiplying
1274 // the opcode by one hundred. We must decode this to get the predicate.
1275 if (V.opcode == Instruction::ICmp)
1276 return new CompareConstantExpr(Ty, Instruction::ICmp, V.predicate,
1277 V.operands[0], V.operands[1]);
1278 if (V.opcode == Instruction::FCmp)
1279 return new CompareConstantExpr(Ty, Instruction::FCmp, V.predicate,
1280 V.operands[0], V.operands[1]);
1281 llvm_unreachable("Invalid ConstantExpr!");
1287 struct ConvertConstantType<ConstantExpr, Type> {
1288 static void convert(ConstantExpr *OldC, const Type *NewTy) {
1290 switch (OldC->getOpcode()) {
1291 case Instruction::Trunc:
1292 case Instruction::ZExt:
1293 case Instruction::SExt:
1294 case Instruction::FPTrunc:
1295 case Instruction::FPExt:
1296 case Instruction::UIToFP:
1297 case Instruction::SIToFP:
1298 case Instruction::FPToUI:
1299 case Instruction::FPToSI:
1300 case Instruction::PtrToInt:
1301 case Instruction::IntToPtr:
1302 case Instruction::BitCast:
1303 New = ConstantExpr::getCast(OldC->getOpcode(), OldC->getOperand(0),
1306 case Instruction::Select:
1307 New = ConstantExpr::getSelectTy(NewTy, OldC->getOperand(0),
1308 OldC->getOperand(1),
1309 OldC->getOperand(2));
1312 assert(OldC->getOpcode() >= Instruction::BinaryOpsBegin &&
1313 OldC->getOpcode() < Instruction::BinaryOpsEnd);
1314 New = ConstantExpr::getTy(NewTy, OldC->getOpcode(), OldC->getOperand(0),
1315 OldC->getOperand(1));
1317 case Instruction::GetElementPtr:
1318 // Make everyone now use a constant of the new type...
1319 std::vector<Value*> Idx(OldC->op_begin()+1, OldC->op_end());
1320 New = ConstantExpr::getGetElementPtrTy(NewTy, OldC->getOperand(0),
1321 &Idx[0], Idx.size());
1325 assert(New != OldC && "Didn't replace constant??");
1326 OldC->uncheckedReplaceAllUsesWith(New);
1327 OldC->destroyConstant(); // This constant is now dead, destroy it.
1330 } // end namespace llvm
1333 static ExprMapKeyType getValType(ConstantExpr *CE) {
1334 std::vector<Constant*> Operands;
1335 Operands.reserve(CE->getNumOperands());
1336 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
1337 Operands.push_back(cast<Constant>(CE->getOperand(i)));
1338 return ExprMapKeyType(CE->getOpcode(), Operands,
1339 CE->isCompare() ? CE->getPredicate() : 0,
1341 CE->getIndices() : SmallVector<unsigned, 4>());
1344 static ManagedStatic<ValueMap<ExprMapKeyType, Type,
1345 ConstantExpr> > ExprConstants;
1347 /// This is a utility function to handle folding of casts and lookup of the
1348 /// cast in the ExprConstants map. It is used by the various get* methods below.
1349 static inline Constant *getFoldedCast(
1350 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1351 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1352 // Fold a few common cases
1354 ConstantFoldCastInstruction(getGlobalContext(), opc, C, Ty))
1357 // Look up the constant in the table first to ensure uniqueness
1358 std::vector<Constant*> argVec(1, C);
1359 ExprMapKeyType Key(opc, argVec);
1361 // Implicitly locked.
1362 return ExprConstants->getOrCreate(Ty, Key);
1365 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1366 Instruction::CastOps opc = Instruction::CastOps(oc);
1367 assert(Instruction::isCast(opc) && "opcode out of range");
1368 assert(C && Ty && "Null arguments to getCast");
1369 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1373 llvm_unreachable("Invalid cast opcode");
1375 case Instruction::Trunc: return getTrunc(C, Ty);
1376 case Instruction::ZExt: return getZExt(C, Ty);
1377 case Instruction::SExt: return getSExt(C, Ty);
1378 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1379 case Instruction::FPExt: return getFPExtend(C, Ty);
1380 case Instruction::UIToFP: return getUIToFP(C, Ty);
1381 case Instruction::SIToFP: return getSIToFP(C, Ty);
1382 case Instruction::FPToUI: return getFPToUI(C, Ty);
1383 case Instruction::FPToSI: return getFPToSI(C, Ty);
1384 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1385 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1386 case Instruction::BitCast: return getBitCast(C, Ty);
1391 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1392 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1393 return getCast(Instruction::BitCast, C, Ty);
1394 return getCast(Instruction::ZExt, C, Ty);
1397 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1398 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1399 return getCast(Instruction::BitCast, C, Ty);
1400 return getCast(Instruction::SExt, C, Ty);
1403 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1404 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1405 return getCast(Instruction::BitCast, C, Ty);
1406 return getCast(Instruction::Trunc, C, Ty);
1409 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1410 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1411 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1413 if (Ty->isInteger())
1414 return getCast(Instruction::PtrToInt, S, Ty);
1415 return getCast(Instruction::BitCast, S, Ty);
1418 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1420 assert(C->getType()->isIntOrIntVector() &&
1421 Ty->isIntOrIntVector() && "Invalid cast");
1422 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1423 unsigned DstBits = Ty->getScalarSizeInBits();
1424 Instruction::CastOps opcode =
1425 (SrcBits == DstBits ? Instruction::BitCast :
1426 (SrcBits > DstBits ? Instruction::Trunc :
1427 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1428 return getCast(opcode, C, Ty);
1431 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1432 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1434 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1435 unsigned DstBits = Ty->getScalarSizeInBits();
1436 if (SrcBits == DstBits)
1437 return C; // Avoid a useless cast
1438 Instruction::CastOps opcode =
1439 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1440 return getCast(opcode, C, Ty);
1443 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1445 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1446 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1448 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1449 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1450 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1451 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1452 "SrcTy must be larger than DestTy for Trunc!");
1454 return getFoldedCast(Instruction::Trunc, C, Ty);
1457 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1459 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1460 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1462 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1463 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1464 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1465 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1466 "SrcTy must be smaller than DestTy for SExt!");
1468 return getFoldedCast(Instruction::SExt, C, Ty);
1471 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1473 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1474 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1476 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1477 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1478 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1479 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1480 "SrcTy must be smaller than DestTy for ZExt!");
1482 return getFoldedCast(Instruction::ZExt, C, Ty);
1485 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1487 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1488 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1490 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1491 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1492 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1493 "This is an illegal floating point truncation!");
1494 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1497 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1499 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1500 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1502 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1503 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1504 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1505 "This is an illegal floating point extension!");
1506 return getFoldedCast(Instruction::FPExt, C, Ty);
1509 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1511 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1512 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1514 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1515 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1516 "This is an illegal uint to floating point cast!");
1517 return getFoldedCast(Instruction::UIToFP, C, Ty);
1520 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1522 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1523 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1525 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1526 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1527 "This is an illegal sint to floating point cast!");
1528 return getFoldedCast(Instruction::SIToFP, C, Ty);
1531 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1533 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1534 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1536 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1537 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1538 "This is an illegal floating point to uint cast!");
1539 return getFoldedCast(Instruction::FPToUI, C, Ty);
1542 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1544 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1545 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1547 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1548 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1549 "This is an illegal floating point to sint cast!");
1550 return getFoldedCast(Instruction::FPToSI, C, Ty);
1553 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1554 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1555 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1556 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1559 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1560 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1561 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1562 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1565 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1566 // BitCast implies a no-op cast of type only. No bits change. However, you
1567 // can't cast pointers to anything but pointers.
1569 const Type *SrcTy = C->getType();
1570 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1571 "BitCast cannot cast pointer to non-pointer and vice versa");
1573 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1574 // or nonptr->ptr). For all the other types, the cast is okay if source and
1575 // destination bit widths are identical.
1576 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1577 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1579 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1581 // It is common to ask for a bitcast of a value to its own type, handle this
1583 if (C->getType() == DstTy) return C;
1585 return getFoldedCast(Instruction::BitCast, C, DstTy);
1588 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1589 Constant *C1, Constant *C2) {
1590 // Check the operands for consistency first
1591 assert(Opcode >= Instruction::BinaryOpsBegin &&
1592 Opcode < Instruction::BinaryOpsEnd &&
1593 "Invalid opcode in binary constant expression");
1594 assert(C1->getType() == C2->getType() &&
1595 "Operand types in binary constant expression should match");
1597 if (ReqTy == C1->getType() || ReqTy == Type::Int1Ty)
1598 if (Constant *FC = ConstantFoldBinaryInstruction(
1599 getGlobalContext(), Opcode, C1, C2))
1600 return FC; // Fold a few common cases...
1602 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1603 ExprMapKeyType Key(Opcode, argVec);
1605 // Implicitly locked.
1606 return ExprConstants->getOrCreate(ReqTy, Key);
1609 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1610 Constant *C1, Constant *C2) {
1611 switch (predicate) {
1612 default: llvm_unreachable("Invalid CmpInst predicate");
1613 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1614 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1615 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1616 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1617 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1618 case CmpInst::FCMP_TRUE:
1619 return getFCmp(predicate, C1, C2);
1621 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1622 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1623 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1624 case CmpInst::ICMP_SLE:
1625 return getICmp(predicate, C1, C2);
1629 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2) {
1630 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1631 if (C1->getType()->isFPOrFPVector()) {
1632 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1633 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1634 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1638 case Instruction::Add:
1639 case Instruction::Sub:
1640 case Instruction::Mul:
1641 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1642 assert(C1->getType()->isIntOrIntVector() &&
1643 "Tried to create an integer operation on a non-integer type!");
1645 case Instruction::FAdd:
1646 case Instruction::FSub:
1647 case Instruction::FMul:
1648 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1649 assert(C1->getType()->isFPOrFPVector() &&
1650 "Tried to create a floating-point operation on a "
1651 "non-floating-point type!");
1653 case Instruction::UDiv:
1654 case Instruction::SDiv:
1655 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1656 assert(C1->getType()->isIntOrIntVector() &&
1657 "Tried to create an arithmetic operation on a non-arithmetic type!");
1659 case Instruction::FDiv:
1660 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1661 assert(C1->getType()->isFPOrFPVector() &&
1662 "Tried to create an arithmetic operation on a non-arithmetic type!");
1664 case Instruction::URem:
1665 case Instruction::SRem:
1666 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1667 assert(C1->getType()->isIntOrIntVector() &&
1668 "Tried to create an arithmetic operation on a non-arithmetic type!");
1670 case Instruction::FRem:
1671 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1672 assert(C1->getType()->isFPOrFPVector() &&
1673 "Tried to create an arithmetic operation on a non-arithmetic type!");
1675 case Instruction::And:
1676 case Instruction::Or:
1677 case Instruction::Xor:
1678 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1679 assert(C1->getType()->isIntOrIntVector() &&
1680 "Tried to create a logical operation on a non-integral type!");
1682 case Instruction::Shl:
1683 case Instruction::LShr:
1684 case Instruction::AShr:
1685 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1686 assert(C1->getType()->isIntOrIntVector() &&
1687 "Tried to create a shift operation on a non-integer type!");
1694 return getTy(C1->getType(), Opcode, C1, C2);
1697 Constant *ConstantExpr::getCompare(unsigned short pred,
1698 Constant *C1, Constant *C2) {
1699 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1700 return getCompareTy(pred, C1, C2);
1703 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1704 Constant *V1, Constant *V2) {
1705 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1707 if (ReqTy == V1->getType())
1708 if (Constant *SC = ConstantFoldSelectInstruction(
1709 getGlobalContext(), C, V1, V2))
1710 return SC; // Fold common cases
1712 std::vector<Constant*> argVec(3, C);
1715 ExprMapKeyType Key(Instruction::Select, argVec);
1717 // Implicitly locked.
1718 return ExprConstants->getOrCreate(ReqTy, Key);
1721 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1724 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1726 cast<PointerType>(ReqTy)->getElementType() &&
1727 "GEP indices invalid!");
1729 if (Constant *FC = ConstantFoldGetElementPtr(
1730 getGlobalContext(), C, (Constant**)Idxs, NumIdx))
1731 return FC; // Fold a few common cases...
1733 assert(isa<PointerType>(C->getType()) &&
1734 "Non-pointer type for constant GetElementPtr expression");
1735 // Look up the constant in the table first to ensure uniqueness
1736 std::vector<Constant*> ArgVec;
1737 ArgVec.reserve(NumIdx+1);
1738 ArgVec.push_back(C);
1739 for (unsigned i = 0; i != NumIdx; ++i)
1740 ArgVec.push_back(cast<Constant>(Idxs[i]));
1741 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1743 // Implicitly locked.
1744 return ExprConstants->getOrCreate(ReqTy, Key);
1747 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1749 // Get the result type of the getelementptr!
1751 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1752 assert(Ty && "GEP indices invalid!");
1753 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1754 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1757 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1759 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1764 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1765 assert(LHS->getType() == RHS->getType());
1766 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1767 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1769 if (Constant *FC = ConstantFoldCompareInstruction(
1770 getGlobalContext(),pred, LHS, RHS))
1771 return FC; // Fold a few common cases...
1773 // Look up the constant in the table first to ensure uniqueness
1774 std::vector<Constant*> ArgVec;
1775 ArgVec.push_back(LHS);
1776 ArgVec.push_back(RHS);
1777 // Get the key type with both the opcode and predicate
1778 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1780 // Implicitly locked.
1781 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1785 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1786 assert(LHS->getType() == RHS->getType());
1787 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1789 if (Constant *FC = ConstantFoldCompareInstruction(
1790 getGlobalContext(), pred, LHS, RHS))
1791 return FC; // Fold a few common cases...
1793 // Look up the constant in the table first to ensure uniqueness
1794 std::vector<Constant*> ArgVec;
1795 ArgVec.push_back(LHS);
1796 ArgVec.push_back(RHS);
1797 // Get the key type with both the opcode and predicate
1798 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1800 // Implicitly locked.
1801 return ExprConstants->getOrCreate(Type::Int1Ty, Key);
1804 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1806 if (Constant *FC = ConstantFoldExtractElementInstruction(
1807 getGlobalContext(), Val, Idx))
1808 return FC; // Fold a few common cases...
1809 // Look up the constant in the table first to ensure uniqueness
1810 std::vector<Constant*> ArgVec(1, Val);
1811 ArgVec.push_back(Idx);
1812 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1814 // Implicitly locked.
1815 return ExprConstants->getOrCreate(ReqTy, Key);
1818 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1819 assert(isa<VectorType>(Val->getType()) &&
1820 "Tried to create extractelement operation on non-vector type!");
1821 assert(Idx->getType() == Type::Int32Ty &&
1822 "Extractelement index must be i32 type!");
1823 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1827 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1828 Constant *Elt, Constant *Idx) {
1829 if (Constant *FC = ConstantFoldInsertElementInstruction(
1830 getGlobalContext(), Val, Elt, Idx))
1831 return FC; // Fold a few common cases...
1832 // Look up the constant in the table first to ensure uniqueness
1833 std::vector<Constant*> ArgVec(1, Val);
1834 ArgVec.push_back(Elt);
1835 ArgVec.push_back(Idx);
1836 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1838 // Implicitly locked.
1839 return ExprConstants->getOrCreate(ReqTy, Key);
1842 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1844 assert(isa<VectorType>(Val->getType()) &&
1845 "Tried to create insertelement operation on non-vector type!");
1846 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1847 && "Insertelement types must match!");
1848 assert(Idx->getType() == Type::Int32Ty &&
1849 "Insertelement index must be i32 type!");
1850 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1853 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1854 Constant *V2, Constant *Mask) {
1855 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1856 getGlobalContext(), V1, V2, Mask))
1857 return FC; // Fold a few common cases...
1858 // Look up the constant in the table first to ensure uniqueness
1859 std::vector<Constant*> ArgVec(1, V1);
1860 ArgVec.push_back(V2);
1861 ArgVec.push_back(Mask);
1862 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1864 // Implicitly locked.
1865 return ExprConstants->getOrCreate(ReqTy, Key);
1868 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1870 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1871 "Invalid shuffle vector constant expr operands!");
1873 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1874 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1875 const Type *ShufTy = VectorType::get(EltTy, NElts);
1876 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1879 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1881 const unsigned *Idxs, unsigned NumIdx) {
1882 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1883 Idxs+NumIdx) == Val->getType() &&
1884 "insertvalue indices invalid!");
1885 assert(Agg->getType() == ReqTy &&
1886 "insertvalue type invalid!");
1887 assert(Agg->getType()->isFirstClassType() &&
1888 "Non-first-class type for constant InsertValue expression");
1889 Constant *FC = ConstantFoldInsertValueInstruction(
1890 getGlobalContext(), Agg, Val, Idxs, NumIdx);
1891 assert(FC && "InsertValue constant expr couldn't be folded!");
1895 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1896 const unsigned *IdxList, unsigned NumIdx) {
1897 assert(Agg->getType()->isFirstClassType() &&
1898 "Tried to create insertelement operation on non-first-class type!");
1900 const Type *ReqTy = Agg->getType();
1903 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1905 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1906 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1909 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1910 const unsigned *Idxs, unsigned NumIdx) {
1911 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1912 Idxs+NumIdx) == ReqTy &&
1913 "extractvalue indices invalid!");
1914 assert(Agg->getType()->isFirstClassType() &&
1915 "Non-first-class type for constant extractvalue expression");
1916 Constant *FC = ConstantFoldExtractValueInstruction(
1917 getGlobalContext(), Agg, Idxs, NumIdx);
1918 assert(FC && "ExtractValue constant expr couldn't be folded!");
1922 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1923 const unsigned *IdxList, unsigned NumIdx) {
1924 assert(Agg->getType()->isFirstClassType() &&
1925 "Tried to create extractelement operation on non-first-class type!");
1928 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1929 assert(ReqTy && "extractvalue indices invalid!");
1930 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1933 // destroyConstant - Remove the constant from the constant table...
1935 void ConstantExpr::destroyConstant() {
1936 // Implicitly locked.
1937 ExprConstants->remove(this);
1938 destroyConstantImpl();
1941 const char *ConstantExpr::getOpcodeName() const {
1942 return Instruction::getOpcodeName(getOpcode());
1945 //===----------------------------------------------------------------------===//
1946 // replaceUsesOfWithOnConstant implementations
1948 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1949 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1952 /// Note that we intentionally replace all uses of From with To here. Consider
1953 /// a large array that uses 'From' 1000 times. By handling this case all here,
1954 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1955 /// single invocation handles all 1000 uses. Handling them one at a time would
1956 /// work, but would be really slow because it would have to unique each updated
1959 static std::vector<Constant*> getValType(ConstantArray *CA) {
1960 std::vector<Constant*> Elements;
1961 Elements.reserve(CA->getNumOperands());
1962 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1963 Elements.push_back(cast<Constant>(CA->getOperand(i)));
1968 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1970 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1971 Constant *ToC = cast<Constant>(To);
1973 LLVMContext &Context = getType()->getContext();
1974 LLVMContextImpl *pImpl = Context.pImpl;
1976 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, Constant*> Lookup;
1977 Lookup.first.first = getType();
1978 Lookup.second = this;
1980 std::vector<Constant*> &Values = Lookup.first.second;
1981 Values.reserve(getNumOperands()); // Build replacement array.
1983 // Fill values with the modified operands of the constant array. Also,
1984 // compute whether this turns into an all-zeros array.
1985 bool isAllZeros = false;
1986 unsigned NumUpdated = 0;
1987 if (!ToC->isNullValue()) {
1988 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1989 Constant *Val = cast<Constant>(O->get());
1994 Values.push_back(Val);
1998 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1999 Constant *Val = cast<Constant>(O->get());
2004 Values.push_back(Val);
2005 if (isAllZeros) isAllZeros = Val->isNullValue();
2009 Constant *Replacement = 0;
2011 Replacement = Context.getConstantAggregateZero(getType());
2013 // Check to see if we have this array type already.
2014 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
2016 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2017 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
2020 Replacement = I->second;
2022 // Okay, the new shape doesn't exist in the system yet. Instead of
2023 // creating a new constant array, inserting it, replaceallusesof'ing the
2024 // old with the new, then deleting the old... just update the current one
2026 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
2028 // Update to the new value. Optimize for the case when we have a single
2029 // operand that we're changing, but handle bulk updates efficiently.
2030 if (NumUpdated == 1) {
2031 unsigned OperandToUpdate = U - OperandList;
2032 assert(getOperand(OperandToUpdate) == From &&
2033 "ReplaceAllUsesWith broken!");
2034 setOperand(OperandToUpdate, ToC);
2036 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2037 if (getOperand(i) == From)
2044 // Otherwise, I do need to replace this with an existing value.
2045 assert(Replacement != this && "I didn't contain From!");
2047 // Everyone using this now uses the replacement.
2048 uncheckedReplaceAllUsesWith(Replacement);
2050 // Delete the old constant!
2054 static std::vector<Constant*> getValType(ConstantStruct *CS) {
2055 std::vector<Constant*> Elements;
2056 Elements.reserve(CS->getNumOperands());
2057 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
2058 Elements.push_back(cast<Constant>(CS->getOperand(i)));
2062 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2064 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2065 Constant *ToC = cast<Constant>(To);
2067 unsigned OperandToUpdate = U-OperandList;
2068 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2070 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, Constant*> Lookup;
2071 Lookup.first.first = getType();
2072 Lookup.second = this;
2073 std::vector<Constant*> &Values = Lookup.first.second;
2074 Values.reserve(getNumOperands()); // Build replacement struct.
2077 // Fill values with the modified operands of the constant struct. Also,
2078 // compute whether this turns into an all-zeros struct.
2079 bool isAllZeros = false;
2080 if (!ToC->isNullValue()) {
2081 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2082 Values.push_back(cast<Constant>(O->get()));
2085 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2086 Constant *Val = cast<Constant>(O->get());
2087 Values.push_back(Val);
2088 if (isAllZeros) isAllZeros = Val->isNullValue();
2091 Values[OperandToUpdate] = ToC;
2093 LLVMContext &Context = getType()->getContext();
2094 LLVMContextImpl *pImpl = Context.pImpl;
2096 Constant *Replacement = 0;
2098 Replacement = Context.getConstantAggregateZero(getType());
2100 // Check to see if we have this array type already.
2101 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
2103 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2104 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2107 Replacement = I->second;
2109 // Okay, the new shape doesn't exist in the system yet. Instead of
2110 // creating a new constant struct, inserting it, replaceallusesof'ing the
2111 // old with the new, then deleting the old... just update the current one
2113 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2115 // Update to the new value.
2116 setOperand(OperandToUpdate, ToC);
2121 assert(Replacement != this && "I didn't contain From!");
2123 // Everyone using this now uses the replacement.
2124 uncheckedReplaceAllUsesWith(Replacement);
2126 // Delete the old constant!
2130 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2132 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2134 std::vector<Constant*> Values;
2135 Values.reserve(getNumOperands()); // Build replacement array...
2136 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2137 Constant *Val = getOperand(i);
2138 if (Val == From) Val = cast<Constant>(To);
2139 Values.push_back(Val);
2142 Constant *Replacement =
2143 getType()->getContext().getConstantVector(getType(), Values);
2144 assert(Replacement != this && "I didn't contain From!");
2146 // Everyone using this now uses the replacement.
2147 uncheckedReplaceAllUsesWith(Replacement);
2149 // Delete the old constant!
2153 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2155 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2156 Constant *To = cast<Constant>(ToV);
2158 Constant *Replacement = 0;
2159 if (getOpcode() == Instruction::GetElementPtr) {
2160 SmallVector<Constant*, 8> Indices;
2161 Constant *Pointer = getOperand(0);
2162 Indices.reserve(getNumOperands()-1);
2163 if (Pointer == From) Pointer = To;
2165 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2166 Constant *Val = getOperand(i);
2167 if (Val == From) Val = To;
2168 Indices.push_back(Val);
2170 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2171 &Indices[0], Indices.size());
2172 } else if (getOpcode() == Instruction::ExtractValue) {
2173 Constant *Agg = getOperand(0);
2174 if (Agg == From) Agg = To;
2176 const SmallVector<unsigned, 4> &Indices = getIndices();
2177 Replacement = ConstantExpr::getExtractValue(Agg,
2178 &Indices[0], Indices.size());
2179 } else if (getOpcode() == Instruction::InsertValue) {
2180 Constant *Agg = getOperand(0);
2181 Constant *Val = getOperand(1);
2182 if (Agg == From) Agg = To;
2183 if (Val == From) Val = To;
2185 const SmallVector<unsigned, 4> &Indices = getIndices();
2186 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2187 &Indices[0], Indices.size());
2188 } else if (isCast()) {
2189 assert(getOperand(0) == From && "Cast only has one use!");
2190 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2191 } else if (getOpcode() == Instruction::Select) {
2192 Constant *C1 = getOperand(0);
2193 Constant *C2 = getOperand(1);
2194 Constant *C3 = getOperand(2);
2195 if (C1 == From) C1 = To;
2196 if (C2 == From) C2 = To;
2197 if (C3 == From) C3 = To;
2198 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2199 } else if (getOpcode() == Instruction::ExtractElement) {
2200 Constant *C1 = getOperand(0);
2201 Constant *C2 = getOperand(1);
2202 if (C1 == From) C1 = To;
2203 if (C2 == From) C2 = To;
2204 Replacement = ConstantExpr::getExtractElement(C1, C2);
2205 } else if (getOpcode() == Instruction::InsertElement) {
2206 Constant *C1 = getOperand(0);
2207 Constant *C2 = getOperand(1);
2208 Constant *C3 = getOperand(1);
2209 if (C1 == From) C1 = To;
2210 if (C2 == From) C2 = To;
2211 if (C3 == From) C3 = To;
2212 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2213 } else if (getOpcode() == Instruction::ShuffleVector) {
2214 Constant *C1 = getOperand(0);
2215 Constant *C2 = getOperand(1);
2216 Constant *C3 = getOperand(2);
2217 if (C1 == From) C1 = To;
2218 if (C2 == From) C2 = To;
2219 if (C3 == From) C3 = To;
2220 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2221 } else if (isCompare()) {
2222 Constant *C1 = getOperand(0);
2223 Constant *C2 = getOperand(1);
2224 if (C1 == From) C1 = To;
2225 if (C2 == From) C2 = To;
2226 if (getOpcode() == Instruction::ICmp)
2227 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2229 assert(getOpcode() == Instruction::FCmp);
2230 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2232 } else if (getNumOperands() == 2) {
2233 Constant *C1 = getOperand(0);
2234 Constant *C2 = getOperand(1);
2235 if (C1 == From) C1 = To;
2236 if (C2 == From) C2 = To;
2237 Replacement = ConstantExpr::get(getOpcode(), C1, C2);
2239 llvm_unreachable("Unknown ConstantExpr type!");
2243 assert(Replacement != this && "I didn't contain From!");
2245 // Everyone using this now uses the replacement.
2246 uncheckedReplaceAllUsesWith(Replacement);
2248 // Delete the old constant!
2252 void MDNode::replaceElement(Value *From, Value *To) {
2253 SmallVector<Value*, 4> Values;
2254 Values.reserve(getNumElements()); // Build replacement array...
2255 for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
2256 Value *Val = getElement(i);
2257 if (Val == From) Val = To;
2258 Values.push_back(Val);
2261 MDNode *Replacement =
2262 getType()->getContext().getMDNode(&Values[0], Values.size());
2263 assert(Replacement != this && "I didn't contain From!");
2265 uncheckedReplaceAllUsesWith(Replacement);