1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes...
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/System/Mutex.h"
33 #include "llvm/System/RWMutex.h"
34 #include "llvm/System/Threading.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/SmallVector.h"
41 //===----------------------------------------------------------------------===//
43 //===----------------------------------------------------------------------===//
45 // Constructor to create a '0' constant of arbitrary type...
46 static const uint64_t zero[2] = {0, 0};
47 Constant* Constant::getNullValue(const Type* Ty) {
48 switch (Ty->getTypeID()) {
49 case Type::IntegerTyID:
50 return ConstantInt::get(Ty, 0);
52 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
53 case Type::DoubleTyID:
54 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
55 case Type::X86_FP80TyID:
56 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
58 return ConstantFP::get(Ty->getContext(),
59 APFloat(APInt(128, 2, zero), true));
60 case Type::PPC_FP128TyID:
61 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
62 case Type::PointerTyID:
63 return ConstantPointerNull::get(cast<PointerType>(Ty));
64 case Type::StructTyID:
66 case Type::VectorTyID:
67 return ConstantAggregateZero::get(Ty);
69 // Function, Label, or Opaque type?
70 assert(!"Cannot create a null constant of that type!");
75 Constant* Constant::getIntegerValue(const Type* Ty, const APInt &V) {
76 const Type *ScalarTy = Ty->getScalarType();
78 // Create the base integer constant.
79 Constant *C = ConstantInt::get(Ty->getContext(), V);
81 // Convert an integer to a pointer, if necessary.
82 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
83 C = ConstantExpr::getIntToPtr(C, PTy);
85 // Broadcast a scalar to a vector, if necessary.
86 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
87 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
92 Constant* Constant::getAllOnesValue(const Type* Ty) {
93 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty))
94 return ConstantInt::get(Ty->getContext(),
95 APInt::getAllOnesValue(ITy->getBitWidth()));
97 std::vector<Constant*> Elts;
98 const VectorType* VTy = cast<VectorType>(Ty);
99 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
100 assert(Elts[0] && "Not a vector integer type!");
101 return cast<ConstantVector>(ConstantVector::get(Elts));
104 void Constant::destroyConstantImpl() {
105 // When a Constant is destroyed, there may be lingering
106 // references to the constant by other constants in the constant pool. These
107 // constants are implicitly dependent on the module that is being deleted,
108 // but they don't know that. Because we only find out when the CPV is
109 // deleted, we must now notify all of our users (that should only be
110 // Constants) that they are, in fact, invalid now and should be deleted.
112 while (!use_empty()) {
113 Value *V = use_back();
114 #ifndef NDEBUG // Only in -g mode...
115 if (!isa<Constant>(V)) {
116 errs() << "While deleting: " << *this
117 << "\n\nUse still stuck around after Def is destroyed: "
121 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
122 Constant *CV = cast<Constant>(V);
123 CV->destroyConstant();
125 // The constant should remove itself from our use list...
126 assert((use_empty() || use_back() != V) && "Constant not removed!");
129 // Value has no outstanding references it is safe to delete it now...
133 /// canTrap - Return true if evaluation of this constant could trap. This is
134 /// true for things like constant expressions that could divide by zero.
135 bool Constant::canTrap() const {
136 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
137 // The only thing that could possibly trap are constant exprs.
138 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
139 if (!CE) return false;
141 // ConstantExpr traps if any operands can trap.
142 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
143 if (getOperand(i)->canTrap())
146 // Otherwise, only specific operations can trap.
147 switch (CE->getOpcode()) {
150 case Instruction::UDiv:
151 case Instruction::SDiv:
152 case Instruction::FDiv:
153 case Instruction::URem:
154 case Instruction::SRem:
155 case Instruction::FRem:
156 // Div and rem can trap if the RHS is not known to be non-zero.
157 if (!isa<ConstantInt>(getOperand(1)) || getOperand(1)->isNullValue())
164 /// getRelocationInfo - This method classifies the entry according to
165 /// whether or not it may generate a relocation entry. This must be
166 /// conservative, so if it might codegen to a relocatable entry, it should say
167 /// so. The return values are:
169 /// NoRelocation: This constant pool entry is guaranteed to never have a
170 /// relocation applied to it (because it holds a simple constant like
172 /// LocalRelocation: This entry has relocations, but the entries are
173 /// guaranteed to be resolvable by the static linker, so the dynamic
174 /// linker will never see them.
175 /// GlobalRelocations: This entry may have arbitrary relocations.
177 /// FIXME: This really should not be in VMCore.
178 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
179 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
180 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
181 return LocalRelocation; // Local to this file/library.
182 return GlobalRelocations; // Global reference.
185 PossibleRelocationsTy Result = NoRelocation;
186 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
187 Result = std::max(Result, getOperand(i)->getRelocationInfo());
193 /// getVectorElements - This method, which is only valid on constant of vector
194 /// type, returns the elements of the vector in the specified smallvector.
195 /// This handles breaking down a vector undef into undef elements, etc. For
196 /// constant exprs and other cases we can't handle, we return an empty vector.
197 void Constant::getVectorElements(LLVMContext &Context,
198 SmallVectorImpl<Constant*> &Elts) const {
199 assert(isa<VectorType>(getType()) && "Not a vector constant!");
201 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
202 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
203 Elts.push_back(CV->getOperand(i));
207 const VectorType *VT = cast<VectorType>(getType());
208 if (isa<ConstantAggregateZero>(this)) {
209 Elts.assign(VT->getNumElements(),
210 Constant::getNullValue(VT->getElementType()));
214 if (isa<UndefValue>(this)) {
215 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
219 // Unknown type, must be constant expr etc.
224 //===----------------------------------------------------------------------===//
226 //===----------------------------------------------------------------------===//
228 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
229 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
230 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
233 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
234 LLVMContextImpl *pImpl = Context.pImpl;
235 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
236 if (pImpl->TheTrueVal)
237 return pImpl->TheTrueVal;
239 return (pImpl->TheTrueVal =
240 ConstantInt::get(IntegerType::get(Context, 1), 1));
243 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
244 LLVMContextImpl *pImpl = Context.pImpl;
245 sys::SmartScopedWriter<true>(pImpl->ConstantsLock);
246 if (pImpl->TheFalseVal)
247 return pImpl->TheFalseVal;
249 return (pImpl->TheFalseVal =
250 ConstantInt::get(IntegerType::get(Context, 1), 0));
254 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
255 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
256 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
257 // compare APInt's of different widths, which would violate an APInt class
258 // invariant which generates an assertion.
259 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
260 // Get the corresponding integer type for the bit width of the value.
261 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
262 // get an existing value or the insertion position
263 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
265 Context.pImpl->ConstantsLock.reader_acquire();
266 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
267 Context.pImpl->ConstantsLock.reader_release();
270 sys::SmartScopedWriter<true> Writer(Context.pImpl->ConstantsLock);
271 ConstantInt *&NewSlot = Context.pImpl->IntConstants[Key];
273 NewSlot = new ConstantInt(ITy, V);
282 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
283 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
286 // For vectors, broadcast the value.
287 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
288 return ConstantVector::get(
289 std::vector<Constant *>(VTy->getNumElements(), C));
294 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
296 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
299 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
300 return get(Ty, V, true);
303 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
304 return get(Ty, V, true);
307 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
308 ConstantInt *C = get(Ty->getContext(), V);
309 assert(C->getType() == Ty->getScalarType() &&
310 "ConstantInt type doesn't match the type implied by its value!");
312 // For vectors, broadcast the value.
313 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
314 return ConstantVector::get(
315 std::vector<Constant *>(VTy->getNumElements(), C));
320 ConstantInt* ConstantInt::get(const IntegerType* Ty, const StringRef& Str,
322 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
325 //===----------------------------------------------------------------------===//
327 //===----------------------------------------------------------------------===//
329 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
330 if (Ty == Type::getFloatTy(Ty->getContext()))
331 return &APFloat::IEEEsingle;
332 if (Ty == Type::getDoubleTy(Ty->getContext()))
333 return &APFloat::IEEEdouble;
334 if (Ty == Type::getX86_FP80Ty(Ty->getContext()))
335 return &APFloat::x87DoubleExtended;
336 else if (Ty == Type::getFP128Ty(Ty->getContext()))
337 return &APFloat::IEEEquad;
339 assert(Ty == Type::getPPC_FP128Ty(Ty->getContext()) && "Unknown FP format");
340 return &APFloat::PPCDoubleDouble;
343 /// get() - This returns a constant fp for the specified value in the
344 /// specified type. This should only be used for simple constant values like
345 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
346 Constant* ConstantFP::get(const Type* Ty, double V) {
347 LLVMContext &Context = Ty->getContext();
351 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
352 APFloat::rmNearestTiesToEven, &ignored);
353 Constant *C = get(Context, FV);
355 // For vectors, broadcast the value.
356 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
357 return ConstantVector::get(
358 std::vector<Constant *>(VTy->getNumElements(), C));
364 Constant* ConstantFP::get(const Type* Ty, const StringRef& Str) {
365 LLVMContext &Context = Ty->getContext();
367 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
368 Constant *C = get(Context, FV);
370 // For vectors, broadcast the value.
371 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
372 return ConstantVector::get(
373 std::vector<Constant *>(VTy->getNumElements(), C));
379 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
380 LLVMContext &Context = Ty->getContext();
381 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
383 return get(Context, apf);
387 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
388 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
389 if (PTy->getElementType()->isFloatingPoint()) {
390 std::vector<Constant*> zeros(PTy->getNumElements(),
391 getNegativeZero(PTy->getElementType()));
392 return ConstantVector::get(PTy, zeros);
395 if (Ty->isFloatingPoint())
396 return getNegativeZero(Ty);
398 return Constant::getNullValue(Ty);
402 // ConstantFP accessors.
403 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
404 DenseMapAPFloatKeyInfo::KeyTy Key(V);
406 LLVMContextImpl* pImpl = Context.pImpl;
408 pImpl->ConstantsLock.reader_acquire();
409 ConstantFP *&Slot = pImpl->FPConstants[Key];
410 pImpl->ConstantsLock.reader_release();
413 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
414 ConstantFP *&NewSlot = pImpl->FPConstants[Key];
417 if (&V.getSemantics() == &APFloat::IEEEsingle)
418 Ty = Type::getFloatTy(Context);
419 else if (&V.getSemantics() == &APFloat::IEEEdouble)
420 Ty = Type::getDoubleTy(Context);
421 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
422 Ty = Type::getX86_FP80Ty(Context);
423 else if (&V.getSemantics() == &APFloat::IEEEquad)
424 Ty = Type::getFP128Ty(Context);
426 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
427 "Unknown FP format");
428 Ty = Type::getPPC_FP128Ty(Context);
430 NewSlot = new ConstantFP(Ty, V);
439 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
440 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
441 return ConstantFP::get(Ty->getContext(),
442 APFloat::getInf(Semantics, Negative));
445 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
446 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
447 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
451 bool ConstantFP::isNullValue() const {
452 return Val.isZero() && !Val.isNegative();
455 bool ConstantFP::isExactlyValue(const APFloat& V) const {
456 return Val.bitwiseIsEqual(V);
459 //===----------------------------------------------------------------------===//
460 // ConstantXXX Classes
461 //===----------------------------------------------------------------------===//
464 ConstantArray::ConstantArray(const ArrayType *T,
465 const std::vector<Constant*> &V)
466 : Constant(T, ConstantArrayVal,
467 OperandTraits<ConstantArray>::op_end(this) - V.size(),
469 assert(V.size() == T->getNumElements() &&
470 "Invalid initializer vector for constant array");
471 Use *OL = OperandList;
472 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
475 assert((C->getType() == T->getElementType() ||
477 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
478 "Initializer for array element doesn't match array element type!");
483 Constant *ConstantArray::get(const ArrayType *Ty,
484 const std::vector<Constant*> &V) {
485 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
486 // If this is an all-zero array, return a ConstantAggregateZero object
489 if (!C->isNullValue()) {
490 // Implicitly locked.
491 return pImpl->ArrayConstants.getOrCreate(Ty, V);
493 for (unsigned i = 1, e = V.size(); i != e; ++i)
495 // Implicitly locked.
496 return pImpl->ArrayConstants.getOrCreate(Ty, V);
500 return ConstantAggregateZero::get(Ty);
504 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
506 // FIXME: make this the primary ctor method.
507 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
510 /// ConstantArray::get(const string&) - Return an array that is initialized to
511 /// contain the specified string. If length is zero then a null terminator is
512 /// added to the specified string so that it may be used in a natural way.
513 /// Otherwise, the length parameter specifies how much of the string to use
514 /// and it won't be null terminated.
516 Constant* ConstantArray::get(LLVMContext &Context, const StringRef &Str,
518 std::vector<Constant*> ElementVals;
519 for (unsigned i = 0; i < Str.size(); ++i)
520 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
522 // Add a null terminator to the string...
524 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
527 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
528 return get(ATy, ElementVals);
533 ConstantStruct::ConstantStruct(const StructType *T,
534 const std::vector<Constant*> &V)
535 : Constant(T, ConstantStructVal,
536 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
538 assert(V.size() == T->getNumElements() &&
539 "Invalid initializer vector for constant structure");
540 Use *OL = OperandList;
541 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
544 assert((C->getType() == T->getElementType(I-V.begin()) ||
545 ((T->getElementType(I-V.begin())->isAbstract() ||
546 C->getType()->isAbstract()) &&
547 T->getElementType(I-V.begin())->getTypeID() ==
548 C->getType()->getTypeID())) &&
549 "Initializer for struct element doesn't match struct element type!");
554 // ConstantStruct accessors.
555 Constant* ConstantStruct::get(const StructType* T,
556 const std::vector<Constant*>& V) {
557 LLVMContextImpl* pImpl = T->getContext().pImpl;
559 // Create a ConstantAggregateZero value if all elements are zeros...
560 for (unsigned i = 0, e = V.size(); i != e; ++i)
561 if (!V[i]->isNullValue())
562 // Implicitly locked.
563 return pImpl->StructConstants.getOrCreate(T, V);
565 return ConstantAggregateZero::get(T);
568 Constant* ConstantStruct::get(LLVMContext &Context,
569 const std::vector<Constant*>& V, bool packed) {
570 std::vector<const Type*> StructEls;
571 StructEls.reserve(V.size());
572 for (unsigned i = 0, e = V.size(); i != e; ++i)
573 StructEls.push_back(V[i]->getType());
574 return get(StructType::get(Context, StructEls, packed), V);
577 Constant* ConstantStruct::get(LLVMContext &Context,
578 Constant* const *Vals, unsigned NumVals,
580 // FIXME: make this the primary ctor method.
581 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
584 ConstantVector::ConstantVector(const VectorType *T,
585 const std::vector<Constant*> &V)
586 : Constant(T, ConstantVectorVal,
587 OperandTraits<ConstantVector>::op_end(this) - V.size(),
589 Use *OL = OperandList;
590 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
593 assert((C->getType() == T->getElementType() ||
595 C->getType()->getTypeID() == T->getElementType()->getTypeID())) &&
596 "Initializer for vector element doesn't match vector element type!");
601 // ConstantVector accessors.
602 Constant* ConstantVector::get(const VectorType* T,
603 const std::vector<Constant*>& V) {
604 assert(!V.empty() && "Vectors can't be empty");
605 LLVMContext &Context = T->getContext();
606 LLVMContextImpl *pImpl = Context.pImpl;
608 // If this is an all-undef or alll-zero vector, return a
609 // ConstantAggregateZero or UndefValue.
611 bool isZero = C->isNullValue();
612 bool isUndef = isa<UndefValue>(C);
614 if (isZero || isUndef) {
615 for (unsigned i = 1, e = V.size(); i != e; ++i)
617 isZero = isUndef = false;
623 return ConstantAggregateZero::get(T);
625 return UndefValue::get(T);
627 // Implicitly locked.
628 return pImpl->VectorConstants.getOrCreate(T, V);
631 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
632 assert(!V.empty() && "Cannot infer type if V is empty");
633 return get(VectorType::get(V.front()->getType(),V.size()), V);
636 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
637 // FIXME: make this the primary ctor method.
638 return get(std::vector<Constant*>(Vals, Vals+NumVals));
641 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
642 return getTy(C1->getType(), Instruction::Add, C1, C2,
643 OverflowingBinaryOperator::NoSignedWrap);
646 Constant* ConstantExpr::getNSWSub(Constant* C1, Constant* C2) {
647 return getTy(C1->getType(), Instruction::Sub, C1, C2,
648 OverflowingBinaryOperator::NoSignedWrap);
651 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
652 return getTy(C1->getType(), Instruction::SDiv, C1, C2,
653 SDivOperator::IsExact);
656 // Utility function for determining if a ConstantExpr is a CastOp or not. This
657 // can't be inline because we don't want to #include Instruction.h into
659 bool ConstantExpr::isCast() const {
660 return Instruction::isCast(getOpcode());
663 bool ConstantExpr::isCompare() const {
664 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
667 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
668 if (getOpcode() != Instruction::GetElementPtr) return false;
670 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
671 User::const_op_iterator OI = next(this->op_begin());
673 // Skip the first index, as it has no static limit.
677 // The remaining indices must be compile-time known integers within the
678 // bounds of the corresponding notional static array types.
679 for (; GEPI != E; ++GEPI, ++OI) {
680 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
681 if (!CI) return false;
682 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
683 if (CI->getValue().getActiveBits() > 64 ||
684 CI->getZExtValue() >= ATy->getNumElements())
688 // All the indices checked out.
692 bool ConstantExpr::hasIndices() const {
693 return getOpcode() == Instruction::ExtractValue ||
694 getOpcode() == Instruction::InsertValue;
697 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
698 if (const ExtractValueConstantExpr *EVCE =
699 dyn_cast<ExtractValueConstantExpr>(this))
700 return EVCE->Indices;
702 return cast<InsertValueConstantExpr>(this)->Indices;
705 unsigned ConstantExpr::getPredicate() const {
706 assert(getOpcode() == Instruction::FCmp ||
707 getOpcode() == Instruction::ICmp);
708 return ((const CompareConstantExpr*)this)->predicate;
711 /// getWithOperandReplaced - Return a constant expression identical to this
712 /// one, but with the specified operand set to the specified value.
714 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
715 assert(OpNo < getNumOperands() && "Operand num is out of range!");
716 assert(Op->getType() == getOperand(OpNo)->getType() &&
717 "Replacing operand with value of different type!");
718 if (getOperand(OpNo) == Op)
719 return const_cast<ConstantExpr*>(this);
721 Constant *Op0, *Op1, *Op2;
722 switch (getOpcode()) {
723 case Instruction::Trunc:
724 case Instruction::ZExt:
725 case Instruction::SExt:
726 case Instruction::FPTrunc:
727 case Instruction::FPExt:
728 case Instruction::UIToFP:
729 case Instruction::SIToFP:
730 case Instruction::FPToUI:
731 case Instruction::FPToSI:
732 case Instruction::PtrToInt:
733 case Instruction::IntToPtr:
734 case Instruction::BitCast:
735 return ConstantExpr::getCast(getOpcode(), Op, getType());
736 case Instruction::Select:
737 Op0 = (OpNo == 0) ? Op : getOperand(0);
738 Op1 = (OpNo == 1) ? Op : getOperand(1);
739 Op2 = (OpNo == 2) ? Op : getOperand(2);
740 return ConstantExpr::getSelect(Op0, Op1, Op2);
741 case Instruction::InsertElement:
742 Op0 = (OpNo == 0) ? Op : getOperand(0);
743 Op1 = (OpNo == 1) ? Op : getOperand(1);
744 Op2 = (OpNo == 2) ? Op : getOperand(2);
745 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
746 case Instruction::ExtractElement:
747 Op0 = (OpNo == 0) ? Op : getOperand(0);
748 Op1 = (OpNo == 1) ? Op : getOperand(1);
749 return ConstantExpr::getExtractElement(Op0, Op1);
750 case Instruction::ShuffleVector:
751 Op0 = (OpNo == 0) ? Op : getOperand(0);
752 Op1 = (OpNo == 1) ? Op : getOperand(1);
753 Op2 = (OpNo == 2) ? Op : getOperand(2);
754 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
755 case Instruction::GetElementPtr: {
756 SmallVector<Constant*, 8> Ops;
757 Ops.resize(getNumOperands()-1);
758 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
759 Ops[i-1] = getOperand(i);
761 return cast<GEPOperator>(this)->isInBounds() ?
762 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
763 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
765 return cast<GEPOperator>(this)->isInBounds() ?
766 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0], Ops.size()) :
767 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
770 assert(getNumOperands() == 2 && "Must be binary operator?");
771 Op0 = (OpNo == 0) ? Op : getOperand(0);
772 Op1 = (OpNo == 1) ? Op : getOperand(1);
773 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassData);
777 /// getWithOperands - This returns the current constant expression with the
778 /// operands replaced with the specified values. The specified operands must
779 /// match count and type with the existing ones.
780 Constant *ConstantExpr::
781 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
782 assert(NumOps == getNumOperands() && "Operand count mismatch!");
783 bool AnyChange = false;
784 for (unsigned i = 0; i != NumOps; ++i) {
785 assert(Ops[i]->getType() == getOperand(i)->getType() &&
786 "Operand type mismatch!");
787 AnyChange |= Ops[i] != getOperand(i);
789 if (!AnyChange) // No operands changed, return self.
790 return const_cast<ConstantExpr*>(this);
792 switch (getOpcode()) {
793 case Instruction::Trunc:
794 case Instruction::ZExt:
795 case Instruction::SExt:
796 case Instruction::FPTrunc:
797 case Instruction::FPExt:
798 case Instruction::UIToFP:
799 case Instruction::SIToFP:
800 case Instruction::FPToUI:
801 case Instruction::FPToSI:
802 case Instruction::PtrToInt:
803 case Instruction::IntToPtr:
804 case Instruction::BitCast:
805 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
806 case Instruction::Select:
807 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
808 case Instruction::InsertElement:
809 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
810 case Instruction::ExtractElement:
811 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
812 case Instruction::ShuffleVector:
813 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
814 case Instruction::GetElementPtr:
815 return cast<GEPOperator>(this)->isInBounds() ?
816 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
817 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
818 case Instruction::ICmp:
819 case Instruction::FCmp:
820 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
822 assert(getNumOperands() == 2 && "Must be binary operator?");
823 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassData);
828 //===----------------------------------------------------------------------===//
829 // isValueValidForType implementations
831 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
832 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
833 if (Ty == Type::getInt1Ty(Ty->getContext()))
834 return Val == 0 || Val == 1;
836 return true; // always true, has to fit in largest type
837 uint64_t Max = (1ll << NumBits) - 1;
841 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
842 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
843 if (Ty == Type::getInt1Ty(Ty->getContext()))
844 return Val == 0 || Val == 1 || Val == -1;
846 return true; // always true, has to fit in largest type
847 int64_t Min = -(1ll << (NumBits-1));
848 int64_t Max = (1ll << (NumBits-1)) - 1;
849 return (Val >= Min && Val <= Max);
852 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
853 // convert modifies in place, so make a copy.
854 APFloat Val2 = APFloat(Val);
856 switch (Ty->getTypeID()) {
858 return false; // These can't be represented as floating point!
860 // FIXME rounding mode needs to be more flexible
861 case Type::FloatTyID: {
862 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
864 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
867 case Type::DoubleTyID: {
868 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
869 &Val2.getSemantics() == &APFloat::IEEEdouble)
871 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
874 case Type::X86_FP80TyID:
875 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
876 &Val2.getSemantics() == &APFloat::IEEEdouble ||
877 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
878 case Type::FP128TyID:
879 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
880 &Val2.getSemantics() == &APFloat::IEEEdouble ||
881 &Val2.getSemantics() == &APFloat::IEEEquad;
882 case Type::PPC_FP128TyID:
883 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
884 &Val2.getSemantics() == &APFloat::IEEEdouble ||
885 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
889 //===----------------------------------------------------------------------===//
890 // Factory Function Implementation
892 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
893 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
894 "Cannot create an aggregate zero of non-aggregate type!");
896 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
897 // Implicitly locked.
898 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
901 /// destroyConstant - Remove the constant from the constant table...
903 void ConstantAggregateZero::destroyConstant() {
904 // Implicitly locked.
905 getType()->getContext().pImpl->AggZeroConstants.remove(this);
906 destroyConstantImpl();
909 /// destroyConstant - Remove the constant from the constant table...
911 void ConstantArray::destroyConstant() {
912 // Implicitly locked.
913 getType()->getContext().pImpl->ArrayConstants.remove(this);
914 destroyConstantImpl();
917 /// isString - This method returns true if the array is an array of i8, and
918 /// if the elements of the array are all ConstantInt's.
919 bool ConstantArray::isString() const {
920 // Check the element type for i8...
921 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
923 // Check the elements to make sure they are all integers, not constant
925 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
926 if (!isa<ConstantInt>(getOperand(i)))
931 /// isCString - This method returns true if the array is a string (see
932 /// isString) and it ends in a null byte \\0 and does not contains any other
933 /// null bytes except its terminator.
934 bool ConstantArray::isCString() const {
935 // Check the element type for i8...
936 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
939 // Last element must be a null.
940 if (!getOperand(getNumOperands()-1)->isNullValue())
942 // Other elements must be non-null integers.
943 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
944 if (!isa<ConstantInt>(getOperand(i)))
946 if (getOperand(i)->isNullValue())
953 /// getAsString - If the sub-element type of this array is i8
954 /// then this method converts the array to an std::string and returns it.
955 /// Otherwise, it asserts out.
957 std::string ConstantArray::getAsString() const {
958 assert(isString() && "Not a string!");
960 Result.reserve(getNumOperands());
961 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
962 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
967 //---- ConstantStruct::get() implementation...
974 // destroyConstant - Remove the constant from the constant table...
976 void ConstantStruct::destroyConstant() {
977 // Implicitly locked.
978 getType()->getContext().pImpl->StructConstants.remove(this);
979 destroyConstantImpl();
982 // destroyConstant - Remove the constant from the constant table...
984 void ConstantVector::destroyConstant() {
985 // Implicitly locked.
986 getType()->getContext().pImpl->VectorConstants.remove(this);
987 destroyConstantImpl();
990 /// This function will return true iff every element in this vector constant
991 /// is set to all ones.
992 /// @returns true iff this constant's emements are all set to all ones.
993 /// @brief Determine if the value is all ones.
994 bool ConstantVector::isAllOnesValue() const {
995 // Check out first element.
996 const Constant *Elt = getOperand(0);
997 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
998 if (!CI || !CI->isAllOnesValue()) return false;
999 // Then make sure all remaining elements point to the same value.
1000 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1001 if (getOperand(I) != Elt) return false;
1006 /// getSplatValue - If this is a splat constant, where all of the
1007 /// elements have the same value, return that value. Otherwise return null.
1008 Constant *ConstantVector::getSplatValue() {
1009 // Check out first element.
1010 Constant *Elt = getOperand(0);
1011 // Then make sure all remaining elements point to the same value.
1012 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1013 if (getOperand(I) != Elt) return 0;
1017 //---- ConstantPointerNull::get() implementation...
1020 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1021 // Implicitly locked.
1022 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1025 // destroyConstant - Remove the constant from the constant table...
1027 void ConstantPointerNull::destroyConstant() {
1028 // Implicitly locked.
1029 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1030 destroyConstantImpl();
1034 //---- UndefValue::get() implementation...
1037 UndefValue *UndefValue::get(const Type *Ty) {
1038 // Implicitly locked.
1039 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1042 // destroyConstant - Remove the constant from the constant table.
1044 void UndefValue::destroyConstant() {
1045 // Implicitly locked.
1046 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1047 destroyConstantImpl();
1050 //---- ConstantExpr::get() implementations...
1053 /// This is a utility function to handle folding of casts and lookup of the
1054 /// cast in the ExprConstants map. It is used by the various get* methods below.
1055 static inline Constant *getFoldedCast(
1056 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1057 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1058 // Fold a few common cases
1059 if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1062 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1064 // Look up the constant in the table first to ensure uniqueness
1065 std::vector<Constant*> argVec(1, C);
1066 ExprMapKeyType Key(opc, argVec);
1068 // Implicitly locked.
1069 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1072 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1073 Instruction::CastOps opc = Instruction::CastOps(oc);
1074 assert(Instruction::isCast(opc) && "opcode out of range");
1075 assert(C && Ty && "Null arguments to getCast");
1076 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1080 llvm_unreachable("Invalid cast opcode");
1082 case Instruction::Trunc: return getTrunc(C, Ty);
1083 case Instruction::ZExt: return getZExt(C, Ty);
1084 case Instruction::SExt: return getSExt(C, Ty);
1085 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1086 case Instruction::FPExt: return getFPExtend(C, Ty);
1087 case Instruction::UIToFP: return getUIToFP(C, Ty);
1088 case Instruction::SIToFP: return getSIToFP(C, Ty);
1089 case Instruction::FPToUI: return getFPToUI(C, Ty);
1090 case Instruction::FPToSI: return getFPToSI(C, Ty);
1091 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1092 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1093 case Instruction::BitCast: return getBitCast(C, Ty);
1098 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1099 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1100 return getCast(Instruction::BitCast, C, Ty);
1101 return getCast(Instruction::ZExt, C, Ty);
1104 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1105 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1106 return getCast(Instruction::BitCast, C, Ty);
1107 return getCast(Instruction::SExt, C, Ty);
1110 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1111 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1112 return getCast(Instruction::BitCast, C, Ty);
1113 return getCast(Instruction::Trunc, C, Ty);
1116 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1117 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1118 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1120 if (Ty->isInteger())
1121 return getCast(Instruction::PtrToInt, S, Ty);
1122 return getCast(Instruction::BitCast, S, Ty);
1125 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1127 assert(C->getType()->isIntOrIntVector() &&
1128 Ty->isIntOrIntVector() && "Invalid cast");
1129 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1130 unsigned DstBits = Ty->getScalarSizeInBits();
1131 Instruction::CastOps opcode =
1132 (SrcBits == DstBits ? Instruction::BitCast :
1133 (SrcBits > DstBits ? Instruction::Trunc :
1134 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1135 return getCast(opcode, C, Ty);
1138 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1139 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1141 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1142 unsigned DstBits = Ty->getScalarSizeInBits();
1143 if (SrcBits == DstBits)
1144 return C; // Avoid a useless cast
1145 Instruction::CastOps opcode =
1146 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1147 return getCast(opcode, C, Ty);
1150 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1152 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1153 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1155 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1156 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1157 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1158 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1159 "SrcTy must be larger than DestTy for Trunc!");
1161 return getFoldedCast(Instruction::Trunc, C, Ty);
1164 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1166 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1167 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1169 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1170 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1171 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1172 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1173 "SrcTy must be smaller than DestTy for SExt!");
1175 return getFoldedCast(Instruction::SExt, C, Ty);
1178 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1180 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1181 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1183 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1184 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1185 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1186 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1187 "SrcTy must be smaller than DestTy for ZExt!");
1189 return getFoldedCast(Instruction::ZExt, C, Ty);
1192 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1194 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1195 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1197 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1198 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1199 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1200 "This is an illegal floating point truncation!");
1201 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1204 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1206 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1207 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1209 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1210 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1211 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1212 "This is an illegal floating point extension!");
1213 return getFoldedCast(Instruction::FPExt, C, Ty);
1216 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1218 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1219 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1221 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1222 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1223 "This is an illegal uint to floating point cast!");
1224 return getFoldedCast(Instruction::UIToFP, C, Ty);
1227 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1229 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1230 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1232 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1233 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1234 "This is an illegal sint to floating point cast!");
1235 return getFoldedCast(Instruction::SIToFP, C, Ty);
1238 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1240 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1241 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1243 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1244 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1245 "This is an illegal floating point to uint cast!");
1246 return getFoldedCast(Instruction::FPToUI, C, Ty);
1249 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1251 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1252 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1254 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1255 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1256 "This is an illegal floating point to sint cast!");
1257 return getFoldedCast(Instruction::FPToSI, C, Ty);
1260 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1261 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1262 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1263 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1266 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1267 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1268 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1269 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1272 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1273 // BitCast implies a no-op cast of type only. No bits change. However, you
1274 // can't cast pointers to anything but pointers.
1276 const Type *SrcTy = C->getType();
1277 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1278 "BitCast cannot cast pointer to non-pointer and vice versa");
1280 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1281 // or nonptr->ptr). For all the other types, the cast is okay if source and
1282 // destination bit widths are identical.
1283 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1284 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1286 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1288 // It is common to ask for a bitcast of a value to its own type, handle this
1290 if (C->getType() == DstTy) return C;
1292 return getFoldedCast(Instruction::BitCast, C, DstTy);
1295 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1296 Constant *C1, Constant *C2,
1298 // Check the operands for consistency first
1299 assert(Opcode >= Instruction::BinaryOpsBegin &&
1300 Opcode < Instruction::BinaryOpsEnd &&
1301 "Invalid opcode in binary constant expression");
1302 assert(C1->getType() == C2->getType() &&
1303 "Operand types in binary constant expression should match");
1305 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1306 if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1308 return FC; // Fold a few common cases...
1310 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1311 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1313 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1315 // Implicitly locked.
1316 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1319 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1320 Constant *C1, Constant *C2) {
1321 switch (predicate) {
1322 default: llvm_unreachable("Invalid CmpInst predicate");
1323 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1324 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1325 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1326 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1327 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1328 case CmpInst::FCMP_TRUE:
1329 return getFCmp(predicate, C1, C2);
1331 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1332 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1333 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1334 case CmpInst::ICMP_SLE:
1335 return getICmp(predicate, C1, C2);
1339 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1341 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1342 if (C1->getType()->isFPOrFPVector()) {
1343 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1344 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1345 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1349 case Instruction::Add:
1350 case Instruction::Sub:
1351 case Instruction::Mul:
1352 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1353 assert(C1->getType()->isIntOrIntVector() &&
1354 "Tried to create an integer operation on a non-integer type!");
1356 case Instruction::FAdd:
1357 case Instruction::FSub:
1358 case Instruction::FMul:
1359 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1360 assert(C1->getType()->isFPOrFPVector() &&
1361 "Tried to create a floating-point operation on a "
1362 "non-floating-point type!");
1364 case Instruction::UDiv:
1365 case Instruction::SDiv:
1366 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1367 assert(C1->getType()->isIntOrIntVector() &&
1368 "Tried to create an arithmetic operation on a non-arithmetic type!");
1370 case Instruction::FDiv:
1371 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1372 assert(C1->getType()->isFPOrFPVector() &&
1373 "Tried to create an arithmetic operation on a non-arithmetic type!");
1375 case Instruction::URem:
1376 case Instruction::SRem:
1377 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1378 assert(C1->getType()->isIntOrIntVector() &&
1379 "Tried to create an arithmetic operation on a non-arithmetic type!");
1381 case Instruction::FRem:
1382 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1383 assert(C1->getType()->isFPOrFPVector() &&
1384 "Tried to create an arithmetic operation on a non-arithmetic type!");
1386 case Instruction::And:
1387 case Instruction::Or:
1388 case Instruction::Xor:
1389 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1390 assert(C1->getType()->isIntOrIntVector() &&
1391 "Tried to create a logical operation on a non-integral type!");
1393 case Instruction::Shl:
1394 case Instruction::LShr:
1395 case Instruction::AShr:
1396 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1397 assert(C1->getType()->isIntOrIntVector() &&
1398 "Tried to create a shift operation on a non-integer type!");
1405 return getTy(C1->getType(), Opcode, C1, C2, Flags);
1408 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1409 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1410 // Note that a non-inbounds gep is used, as null isn't within any object.
1411 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1412 Constant *GEP = getGetElementPtr(
1413 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1414 return getCast(Instruction::PtrToInt, GEP,
1415 Type::getInt64Ty(Ty->getContext()));
1418 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1419 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1420 // Note that a non-inbounds gep is used, as null isn't within any object.
1421 const Type *AligningTy = StructType::get(Ty->getContext(),
1422 Type::getInt8Ty(Ty->getContext()), Ty, NULL);
1423 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1424 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
1425 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1426 Constant *Indices[2] = { Zero, One };
1427 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1428 return getCast(Instruction::PtrToInt, GEP,
1429 Type::getInt32Ty(Ty->getContext()));
1432 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1433 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1434 // Note that a non-inbounds gep is used, as null isn't within any object.
1435 Constant *GEPIdx[] = {
1436 ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
1437 ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
1439 Constant *GEP = getGetElementPtr(
1440 Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
1441 return getCast(Instruction::PtrToInt, GEP,
1442 Type::getInt64Ty(STy->getContext()));
1445 Constant *ConstantExpr::getCompare(unsigned short pred,
1446 Constant *C1, Constant *C2) {
1447 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1448 return getCompareTy(pred, C1, C2);
1451 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1452 Constant *V1, Constant *V2) {
1453 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1455 if (ReqTy == V1->getType())
1456 if (Constant *SC = ConstantFoldSelectInstruction(
1457 ReqTy->getContext(), C, V1, V2))
1458 return SC; // Fold common cases
1460 std::vector<Constant*> argVec(3, C);
1463 ExprMapKeyType Key(Instruction::Select, argVec);
1465 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1467 // Implicitly locked.
1468 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1471 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1474 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1476 cast<PointerType>(ReqTy)->getElementType() &&
1477 "GEP indices invalid!");
1479 if (Constant *FC = ConstantFoldGetElementPtr(
1480 ReqTy->getContext(), C, /*inBounds=*/false,
1481 (Constant**)Idxs, NumIdx))
1482 return FC; // Fold a few common cases...
1484 assert(isa<PointerType>(C->getType()) &&
1485 "Non-pointer type for constant GetElementPtr expression");
1486 // Look up the constant in the table first to ensure uniqueness
1487 std::vector<Constant*> ArgVec;
1488 ArgVec.reserve(NumIdx+1);
1489 ArgVec.push_back(C);
1490 for (unsigned i = 0; i != NumIdx; ++i)
1491 ArgVec.push_back(cast<Constant>(Idxs[i]));
1492 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1494 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1496 // Implicitly locked.
1497 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1500 Constant *ConstantExpr::getInBoundsGetElementPtrTy(const Type *ReqTy,
1504 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1506 cast<PointerType>(ReqTy)->getElementType() &&
1507 "GEP indices invalid!");
1509 if (Constant *FC = ConstantFoldGetElementPtr(
1510 ReqTy->getContext(), C, /*inBounds=*/true,
1511 (Constant**)Idxs, NumIdx))
1512 return FC; // Fold a few common cases...
1514 assert(isa<PointerType>(C->getType()) &&
1515 "Non-pointer type for constant GetElementPtr expression");
1516 // Look up the constant in the table first to ensure uniqueness
1517 std::vector<Constant*> ArgVec;
1518 ArgVec.reserve(NumIdx+1);
1519 ArgVec.push_back(C);
1520 for (unsigned i = 0; i != NumIdx; ++i)
1521 ArgVec.push_back(cast<Constant>(Idxs[i]));
1522 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1523 GEPOperator::IsInBounds);
1525 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1527 // Implicitly locked.
1528 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1531 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1533 // Get the result type of the getelementptr!
1535 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1536 assert(Ty && "GEP indices invalid!");
1537 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1538 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1541 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1544 // Get the result type of the getelementptr!
1546 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1547 assert(Ty && "GEP indices invalid!");
1548 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1549 return getInBoundsGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1552 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1554 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1557 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1558 Constant* const *Idxs,
1560 return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1564 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1565 assert(LHS->getType() == RHS->getType());
1566 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1567 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1569 if (Constant *FC = ConstantFoldCompareInstruction(
1570 LHS->getContext(), pred, LHS, RHS))
1571 return FC; // Fold a few common cases...
1573 // Look up the constant in the table first to ensure uniqueness
1574 std::vector<Constant*> ArgVec;
1575 ArgVec.push_back(LHS);
1576 ArgVec.push_back(RHS);
1577 // Get the key type with both the opcode and predicate
1578 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1580 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1582 // Implicitly locked.
1584 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1588 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1589 assert(LHS->getType() == RHS->getType());
1590 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1592 if (Constant *FC = ConstantFoldCompareInstruction(
1593 LHS->getContext(), pred, LHS, RHS))
1594 return FC; // Fold a few common cases...
1596 // Look up the constant in the table first to ensure uniqueness
1597 std::vector<Constant*> ArgVec;
1598 ArgVec.push_back(LHS);
1599 ArgVec.push_back(RHS);
1600 // Get the key type with both the opcode and predicate
1601 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1603 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1605 // Implicitly locked.
1607 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1610 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1612 if (Constant *FC = ConstantFoldExtractElementInstruction(
1613 ReqTy->getContext(), Val, Idx))
1614 return FC; // Fold a few common cases...
1615 // Look up the constant in the table first to ensure uniqueness
1616 std::vector<Constant*> ArgVec(1, Val);
1617 ArgVec.push_back(Idx);
1618 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1620 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1622 // Implicitly locked.
1623 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1626 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1627 assert(isa<VectorType>(Val->getType()) &&
1628 "Tried to create extractelement operation on non-vector type!");
1629 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1630 "Extractelement index must be i32 type!");
1631 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1635 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1636 Constant *Elt, Constant *Idx) {
1637 if (Constant *FC = ConstantFoldInsertElementInstruction(
1638 ReqTy->getContext(), Val, Elt, Idx))
1639 return FC; // Fold a few common cases...
1640 // Look up the constant in the table first to ensure uniqueness
1641 std::vector<Constant*> ArgVec(1, Val);
1642 ArgVec.push_back(Elt);
1643 ArgVec.push_back(Idx);
1644 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1646 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1648 // Implicitly locked.
1649 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1652 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1654 assert(isa<VectorType>(Val->getType()) &&
1655 "Tried to create insertelement operation on non-vector type!");
1656 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1657 && "Insertelement types must match!");
1658 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1659 "Insertelement index must be i32 type!");
1660 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1663 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1664 Constant *V2, Constant *Mask) {
1665 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1666 ReqTy->getContext(), V1, V2, Mask))
1667 return FC; // Fold a few common cases...
1668 // Look up the constant in the table first to ensure uniqueness
1669 std::vector<Constant*> ArgVec(1, V1);
1670 ArgVec.push_back(V2);
1671 ArgVec.push_back(Mask);
1672 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1674 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1676 // Implicitly locked.
1677 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1680 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1682 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1683 "Invalid shuffle vector constant expr operands!");
1685 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1686 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1687 const Type *ShufTy = VectorType::get(EltTy, NElts);
1688 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1691 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1693 const unsigned *Idxs, unsigned NumIdx) {
1694 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1695 Idxs+NumIdx) == Val->getType() &&
1696 "insertvalue indices invalid!");
1697 assert(Agg->getType() == ReqTy &&
1698 "insertvalue type invalid!");
1699 assert(Agg->getType()->isFirstClassType() &&
1700 "Non-first-class type for constant InsertValue expression");
1701 Constant *FC = ConstantFoldInsertValueInstruction(
1702 ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1703 assert(FC && "InsertValue constant expr couldn't be folded!");
1707 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1708 const unsigned *IdxList, unsigned NumIdx) {
1709 assert(Agg->getType()->isFirstClassType() &&
1710 "Tried to create insertelement operation on non-first-class type!");
1712 const Type *ReqTy = Agg->getType();
1715 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1717 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1718 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1721 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1722 const unsigned *Idxs, unsigned NumIdx) {
1723 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1724 Idxs+NumIdx) == ReqTy &&
1725 "extractvalue indices invalid!");
1726 assert(Agg->getType()->isFirstClassType() &&
1727 "Non-first-class type for constant extractvalue expression");
1728 Constant *FC = ConstantFoldExtractValueInstruction(
1729 ReqTy->getContext(), Agg, Idxs, NumIdx);
1730 assert(FC && "ExtractValue constant expr couldn't be folded!");
1734 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1735 const unsigned *IdxList, unsigned NumIdx) {
1736 assert(Agg->getType()->isFirstClassType() &&
1737 "Tried to create extractelement operation on non-first-class type!");
1740 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1741 assert(ReqTy && "extractvalue indices invalid!");
1742 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1745 Constant* ConstantExpr::getNeg(Constant* C) {
1746 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1747 if (C->getType()->isFPOrFPVector())
1749 assert(C->getType()->isIntOrIntVector() &&
1750 "Cannot NEG a nonintegral value!");
1751 return get(Instruction::Sub,
1752 ConstantFP::getZeroValueForNegation(C->getType()),
1756 Constant* ConstantExpr::getFNeg(Constant* C) {
1757 assert(C->getType()->isFPOrFPVector() &&
1758 "Cannot FNEG a non-floating-point value!");
1759 return get(Instruction::FSub,
1760 ConstantFP::getZeroValueForNegation(C->getType()),
1764 Constant* ConstantExpr::getNot(Constant* C) {
1765 assert(C->getType()->isIntOrIntVector() &&
1766 "Cannot NOT a nonintegral value!");
1767 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1770 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1771 return get(Instruction::Add, C1, C2);
1774 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1775 return get(Instruction::FAdd, C1, C2);
1778 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1779 return get(Instruction::Sub, C1, C2);
1782 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1783 return get(Instruction::FSub, C1, C2);
1786 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1787 return get(Instruction::Mul, C1, C2);
1790 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1791 return get(Instruction::FMul, C1, C2);
1794 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1795 return get(Instruction::UDiv, C1, C2);
1798 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1799 return get(Instruction::SDiv, C1, C2);
1802 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1803 return get(Instruction::FDiv, C1, C2);
1806 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1807 return get(Instruction::URem, C1, C2);
1810 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1811 return get(Instruction::SRem, C1, C2);
1814 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1815 return get(Instruction::FRem, C1, C2);
1818 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1819 return get(Instruction::And, C1, C2);
1822 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1823 return get(Instruction::Or, C1, C2);
1826 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1827 return get(Instruction::Xor, C1, C2);
1830 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1831 return get(Instruction::Shl, C1, C2);
1834 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1835 return get(Instruction::LShr, C1, C2);
1838 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1839 return get(Instruction::AShr, C1, C2);
1842 // destroyConstant - Remove the constant from the constant table...
1844 void ConstantExpr::destroyConstant() {
1845 // Implicitly locked.
1846 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1847 pImpl->ExprConstants.remove(this);
1848 destroyConstantImpl();
1851 const char *ConstantExpr::getOpcodeName() const {
1852 return Instruction::getOpcodeName(getOpcode());
1855 //===----------------------------------------------------------------------===//
1856 // replaceUsesOfWithOnConstant implementations
1858 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1859 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1862 /// Note that we intentionally replace all uses of From with To here. Consider
1863 /// a large array that uses 'From' 1000 times. By handling this case all here,
1864 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1865 /// single invocation handles all 1000 uses. Handling them one at a time would
1866 /// work, but would be really slow because it would have to unique each updated
1869 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1871 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1872 Constant *ToC = cast<Constant>(To);
1874 LLVMContext &Context = getType()->getContext();
1875 LLVMContextImpl *pImpl = Context.pImpl;
1877 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1878 Lookup.first.first = getType();
1879 Lookup.second = this;
1881 std::vector<Constant*> &Values = Lookup.first.second;
1882 Values.reserve(getNumOperands()); // Build replacement array.
1884 // Fill values with the modified operands of the constant array. Also,
1885 // compute whether this turns into an all-zeros array.
1886 bool isAllZeros = false;
1887 unsigned NumUpdated = 0;
1888 if (!ToC->isNullValue()) {
1889 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1890 Constant *Val = cast<Constant>(O->get());
1895 Values.push_back(Val);
1899 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1900 Constant *Val = cast<Constant>(O->get());
1905 Values.push_back(Val);
1906 if (isAllZeros) isAllZeros = Val->isNullValue();
1910 Constant *Replacement = 0;
1912 Replacement = ConstantAggregateZero::get(getType());
1914 // Check to see if we have this array type already.
1915 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1917 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1918 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1921 Replacement = I->second;
1923 // Okay, the new shape doesn't exist in the system yet. Instead of
1924 // creating a new constant array, inserting it, replaceallusesof'ing the
1925 // old with the new, then deleting the old... just update the current one
1927 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1929 // Update to the new value. Optimize for the case when we have a single
1930 // operand that we're changing, but handle bulk updates efficiently.
1931 if (NumUpdated == 1) {
1932 unsigned OperandToUpdate = U - OperandList;
1933 assert(getOperand(OperandToUpdate) == From &&
1934 "ReplaceAllUsesWith broken!");
1935 setOperand(OperandToUpdate, ToC);
1937 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1938 if (getOperand(i) == From)
1945 // Otherwise, I do need to replace this with an existing value.
1946 assert(Replacement != this && "I didn't contain From!");
1948 // Everyone using this now uses the replacement.
1949 uncheckedReplaceAllUsesWith(Replacement);
1951 // Delete the old constant!
1955 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1957 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1958 Constant *ToC = cast<Constant>(To);
1960 unsigned OperandToUpdate = U-OperandList;
1961 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1963 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1964 Lookup.first.first = getType();
1965 Lookup.second = this;
1966 std::vector<Constant*> &Values = Lookup.first.second;
1967 Values.reserve(getNumOperands()); // Build replacement struct.
1970 // Fill values with the modified operands of the constant struct. Also,
1971 // compute whether this turns into an all-zeros struct.
1972 bool isAllZeros = false;
1973 if (!ToC->isNullValue()) {
1974 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
1975 Values.push_back(cast<Constant>(O->get()));
1978 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1979 Constant *Val = cast<Constant>(O->get());
1980 Values.push_back(Val);
1981 if (isAllZeros) isAllZeros = Val->isNullValue();
1984 Values[OperandToUpdate] = ToC;
1986 LLVMContext &Context = getType()->getContext();
1987 LLVMContextImpl *pImpl = Context.pImpl;
1989 Constant *Replacement = 0;
1991 Replacement = ConstantAggregateZero::get(getType());
1993 // Check to see if we have this array type already.
1994 sys::SmartScopedWriter<true> Writer(pImpl->ConstantsLock);
1996 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
1997 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2000 Replacement = I->second;
2002 // Okay, the new shape doesn't exist in the system yet. Instead of
2003 // creating a new constant struct, inserting it, replaceallusesof'ing the
2004 // old with the new, then deleting the old... just update the current one
2006 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2008 // Update to the new value.
2009 setOperand(OperandToUpdate, ToC);
2014 assert(Replacement != this && "I didn't contain From!");
2016 // Everyone using this now uses the replacement.
2017 uncheckedReplaceAllUsesWith(Replacement);
2019 // Delete the old constant!
2023 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2025 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2027 std::vector<Constant*> Values;
2028 Values.reserve(getNumOperands()); // Build replacement array...
2029 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2030 Constant *Val = getOperand(i);
2031 if (Val == From) Val = cast<Constant>(To);
2032 Values.push_back(Val);
2035 Constant *Replacement = get(getType(), Values);
2036 assert(Replacement != this && "I didn't contain From!");
2038 // Everyone using this now uses the replacement.
2039 uncheckedReplaceAllUsesWith(Replacement);
2041 // Delete the old constant!
2045 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2047 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2048 Constant *To = cast<Constant>(ToV);
2050 Constant *Replacement = 0;
2051 if (getOpcode() == Instruction::GetElementPtr) {
2052 SmallVector<Constant*, 8> Indices;
2053 Constant *Pointer = getOperand(0);
2054 Indices.reserve(getNumOperands()-1);
2055 if (Pointer == From) Pointer = To;
2057 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2058 Constant *Val = getOperand(i);
2059 if (Val == From) Val = To;
2060 Indices.push_back(Val);
2062 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2063 &Indices[0], Indices.size());
2064 } else if (getOpcode() == Instruction::ExtractValue) {
2065 Constant *Agg = getOperand(0);
2066 if (Agg == From) Agg = To;
2068 const SmallVector<unsigned, 4> &Indices = getIndices();
2069 Replacement = ConstantExpr::getExtractValue(Agg,
2070 &Indices[0], Indices.size());
2071 } else if (getOpcode() == Instruction::InsertValue) {
2072 Constant *Agg = getOperand(0);
2073 Constant *Val = getOperand(1);
2074 if (Agg == From) Agg = To;
2075 if (Val == From) Val = To;
2077 const SmallVector<unsigned, 4> &Indices = getIndices();
2078 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2079 &Indices[0], Indices.size());
2080 } else if (isCast()) {
2081 assert(getOperand(0) == From && "Cast only has one use!");
2082 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2083 } else if (getOpcode() == Instruction::Select) {
2084 Constant *C1 = getOperand(0);
2085 Constant *C2 = getOperand(1);
2086 Constant *C3 = getOperand(2);
2087 if (C1 == From) C1 = To;
2088 if (C2 == From) C2 = To;
2089 if (C3 == From) C3 = To;
2090 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2091 } else if (getOpcode() == Instruction::ExtractElement) {
2092 Constant *C1 = getOperand(0);
2093 Constant *C2 = getOperand(1);
2094 if (C1 == From) C1 = To;
2095 if (C2 == From) C2 = To;
2096 Replacement = ConstantExpr::getExtractElement(C1, C2);
2097 } else if (getOpcode() == Instruction::InsertElement) {
2098 Constant *C1 = getOperand(0);
2099 Constant *C2 = getOperand(1);
2100 Constant *C3 = getOperand(1);
2101 if (C1 == From) C1 = To;
2102 if (C2 == From) C2 = To;
2103 if (C3 == From) C3 = To;
2104 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2105 } else if (getOpcode() == Instruction::ShuffleVector) {
2106 Constant *C1 = getOperand(0);
2107 Constant *C2 = getOperand(1);
2108 Constant *C3 = getOperand(2);
2109 if (C1 == From) C1 = To;
2110 if (C2 == From) C2 = To;
2111 if (C3 == From) C3 = To;
2112 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2113 } else if (isCompare()) {
2114 Constant *C1 = getOperand(0);
2115 Constant *C2 = getOperand(1);
2116 if (C1 == From) C1 = To;
2117 if (C2 == From) C2 = To;
2118 if (getOpcode() == Instruction::ICmp)
2119 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2121 assert(getOpcode() == Instruction::FCmp);
2122 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2124 } else if (getNumOperands() == 2) {
2125 Constant *C1 = getOperand(0);
2126 Constant *C2 = getOperand(1);
2127 if (C1 == From) C1 = To;
2128 if (C2 == From) C2 = To;
2129 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassData);
2131 llvm_unreachable("Unknown ConstantExpr type!");
2135 assert(Replacement != this && "I didn't contain From!");
2137 // Everyone using this now uses the replacement.
2138 uncheckedReplaceAllUsesWith(Replacement);
2140 // Delete the old constant!