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/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 // Constructor to create a '0' constant of arbitrary type...
44 Constant *Constant::getNullValue(const Type *Ty) {
45 switch (Ty->getTypeID()) {
46 case Type::IntegerTyID:
47 return ConstantInt::get(Ty, 0);
49 return ConstantFP::get(Ty->getContext(),
50 APFloat::getZero(APFloat::IEEEsingle));
51 case Type::DoubleTyID:
52 return ConstantFP::get(Ty->getContext(),
53 APFloat::getZero(APFloat::IEEEdouble));
54 case Type::X86_FP80TyID:
55 return ConstantFP::get(Ty->getContext(),
56 APFloat::getZero(APFloat::x87DoubleExtended));
58 return ConstantFP::get(Ty->getContext(),
59 APFloat::getZero(APFloat::IEEEquad));
60 case Type::PPC_FP128TyID:
61 return ConstantFP::get(Ty->getContext(),
62 APFloat(APInt::getNullValue(128)));
63 case Type::PointerTyID:
64 return ConstantPointerNull::get(cast<PointerType>(Ty));
65 case Type::StructTyID:
67 case Type::VectorTyID:
68 return ConstantAggregateZero::get(Ty);
70 // Function, Label, or Opaque type?
71 assert(!"Cannot create a null constant of that type!");
76 Constant *Constant::getIntegerValue(const Type *Ty, const APInt &V) {
77 const Type *ScalarTy = Ty->getScalarType();
79 // Create the base integer constant.
80 Constant *C = ConstantInt::get(Ty->getContext(), V);
82 // Convert an integer to a pointer, if necessary.
83 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
84 C = ConstantExpr::getIntToPtr(C, PTy);
86 // Broadcast a scalar to a vector, if necessary.
87 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
88 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
93 Constant *Constant::getAllOnesValue(const Type *Ty) {
94 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
95 return ConstantInt::get(Ty->getContext(),
96 APInt::getAllOnesValue(ITy->getBitWidth()));
98 if (Ty->isFloatingPointTy()) {
99 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
100 !Ty->isPPC_FP128Ty());
101 return ConstantFP::get(Ty->getContext(), FL);
104 SmallVector<Constant*, 16> Elts;
105 const VectorType *VTy = cast<VectorType>(Ty);
106 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
107 assert(Elts[0] && "Not a vector integer type!");
108 return cast<ConstantVector>(ConstantVector::get(Elts));
111 void Constant::destroyConstantImpl() {
112 // When a Constant is destroyed, there may be lingering
113 // references to the constant by other constants in the constant pool. These
114 // constants are implicitly dependent on the module that is being deleted,
115 // but they don't know that. Because we only find out when the CPV is
116 // deleted, we must now notify all of our users (that should only be
117 // Constants) that they are, in fact, invalid now and should be deleted.
119 while (!use_empty()) {
120 Value *V = use_back();
121 #ifndef NDEBUG // Only in -g mode...
122 if (!isa<Constant>(V)) {
123 dbgs() << "While deleting: " << *this
124 << "\n\nUse still stuck around after Def is destroyed: "
128 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
129 Constant *CV = cast<Constant>(V);
130 CV->destroyConstant();
132 // The constant should remove itself from our use list...
133 assert((use_empty() || use_back() != V) && "Constant not removed!");
136 // Value has no outstanding references it is safe to delete it now...
140 /// canTrap - Return true if evaluation of this constant could trap. This is
141 /// true for things like constant expressions that could divide by zero.
142 bool Constant::canTrap() const {
143 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
144 // The only thing that could possibly trap are constant exprs.
145 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
146 if (!CE) return false;
148 // ConstantExpr traps if any operands can trap.
149 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
150 if (CE->getOperand(i)->canTrap())
153 // Otherwise, only specific operations can trap.
154 switch (CE->getOpcode()) {
157 case Instruction::UDiv:
158 case Instruction::SDiv:
159 case Instruction::FDiv:
160 case Instruction::URem:
161 case Instruction::SRem:
162 case Instruction::FRem:
163 // Div and rem can trap if the RHS is not known to be non-zero.
164 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
170 /// isConstantUsed - Return true if the constant has users other than constant
171 /// exprs and other dangling things.
172 bool Constant::isConstantUsed() const {
173 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
174 const Constant *UC = dyn_cast<Constant>(*UI);
175 if (UC == 0 || isa<GlobalValue>(UC))
178 if (UC->isConstantUsed())
186 /// getRelocationInfo - This method classifies the entry according to
187 /// whether or not it may generate a relocation entry. This must be
188 /// conservative, so if it might codegen to a relocatable entry, it should say
189 /// so. The return values are:
191 /// NoRelocation: This constant pool entry is guaranteed to never have a
192 /// relocation applied to it (because it holds a simple constant like
194 /// LocalRelocation: This entry has relocations, but the entries are
195 /// guaranteed to be resolvable by the static linker, so the dynamic
196 /// linker will never see them.
197 /// GlobalRelocations: This entry may have arbitrary relocations.
199 /// FIXME: This really should not be in VMCore.
200 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
201 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
202 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
203 return LocalRelocation; // Local to this file/library.
204 return GlobalRelocations; // Global reference.
207 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
208 return BA->getFunction()->getRelocationInfo();
210 // While raw uses of blockaddress need to be relocated, differences between
211 // two of them don't when they are for labels in the same function. This is a
212 // common idiom when creating a table for the indirect goto extension, so we
213 // handle it efficiently here.
214 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
215 if (CE->getOpcode() == Instruction::Sub) {
216 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
217 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
219 LHS->getOpcode() == Instruction::PtrToInt &&
220 RHS->getOpcode() == Instruction::PtrToInt &&
221 isa<BlockAddress>(LHS->getOperand(0)) &&
222 isa<BlockAddress>(RHS->getOperand(0)) &&
223 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
224 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
228 PossibleRelocationsTy Result = NoRelocation;
229 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
230 Result = std::max(Result,
231 cast<Constant>(getOperand(i))->getRelocationInfo());
237 /// getVectorElements - This method, which is only valid on constant of vector
238 /// type, returns the elements of the vector in the specified smallvector.
239 /// This handles breaking down a vector undef into undef elements, etc. For
240 /// constant exprs and other cases we can't handle, we return an empty vector.
241 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
242 assert(getType()->isVectorTy() && "Not a vector constant!");
244 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
245 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
246 Elts.push_back(CV->getOperand(i));
250 const VectorType *VT = cast<VectorType>(getType());
251 if (isa<ConstantAggregateZero>(this)) {
252 Elts.assign(VT->getNumElements(),
253 Constant::getNullValue(VT->getElementType()));
257 if (isa<UndefValue>(this)) {
258 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
262 // Unknown type, must be constant expr etc.
266 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
267 /// it. This involves recursively eliminating any dead users of the
269 static bool removeDeadUsersOfConstant(const Constant *C) {
270 if (isa<GlobalValue>(C)) return false; // Cannot remove this
272 while (!C->use_empty()) {
273 const Constant *User = dyn_cast<Constant>(C->use_back());
274 if (!User) return false; // Non-constant usage;
275 if (!removeDeadUsersOfConstant(User))
276 return false; // Constant wasn't dead
279 const_cast<Constant*>(C)->destroyConstant();
284 /// removeDeadConstantUsers - If there are any dead constant users dangling
285 /// off of this constant, remove them. This method is useful for clients
286 /// that want to check to see if a global is unused, but don't want to deal
287 /// with potentially dead constants hanging off of the globals.
288 void Constant::removeDeadConstantUsers() const {
289 Value::const_use_iterator I = use_begin(), E = use_end();
290 Value::const_use_iterator LastNonDeadUser = E;
292 const Constant *User = dyn_cast<Constant>(*I);
299 if (!removeDeadUsersOfConstant(User)) {
300 // If the constant wasn't dead, remember that this was the last live use
301 // and move on to the next constant.
307 // If the constant was dead, then the iterator is invalidated.
308 if (LastNonDeadUser == E) {
320 //===----------------------------------------------------------------------===//
322 //===----------------------------------------------------------------------===//
324 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
325 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
326 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
329 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
330 LLVMContextImpl *pImpl = Context.pImpl;
331 if (!pImpl->TheTrueVal)
332 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
333 return pImpl->TheTrueVal;
336 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
337 LLVMContextImpl *pImpl = Context.pImpl;
338 if (!pImpl->TheFalseVal)
339 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
340 return pImpl->TheFalseVal;
344 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
345 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
346 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
347 // compare APInt's of different widths, which would violate an APInt class
348 // invariant which generates an assertion.
349 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
350 // Get the corresponding integer type for the bit width of the value.
351 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
352 // get an existing value or the insertion position
353 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
354 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
355 if (!Slot) Slot = new ConstantInt(ITy, V);
359 Constant *ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
360 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
363 // For vectors, broadcast the value.
364 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
365 return ConstantVector::get(SmallVector<Constant*,
366 16>(VTy->getNumElements(), C));
371 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
373 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
376 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
377 return get(Ty, V, true);
380 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
381 return get(Ty, V, true);
384 Constant *ConstantInt::get(const Type* Ty, const APInt& V) {
385 ConstantInt *C = get(Ty->getContext(), V);
386 assert(C->getType() == Ty->getScalarType() &&
387 "ConstantInt type doesn't match the type implied by its value!");
389 // For vectors, broadcast the value.
390 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
391 return ConstantVector::get(
392 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
397 ConstantInt* ConstantInt::get(const IntegerType* Ty, StringRef Str,
399 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
402 //===----------------------------------------------------------------------===//
404 //===----------------------------------------------------------------------===//
406 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
408 return &APFloat::IEEEsingle;
409 if (Ty->isDoubleTy())
410 return &APFloat::IEEEdouble;
411 if (Ty->isX86_FP80Ty())
412 return &APFloat::x87DoubleExtended;
413 else if (Ty->isFP128Ty())
414 return &APFloat::IEEEquad;
416 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
417 return &APFloat::PPCDoubleDouble;
420 /// get() - This returns a constant fp for the specified value in the
421 /// specified type. This should only be used for simple constant values like
422 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
423 Constant *ConstantFP::get(const Type* Ty, double V) {
424 LLVMContext &Context = Ty->getContext();
428 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
429 APFloat::rmNearestTiesToEven, &ignored);
430 Constant *C = get(Context, FV);
432 // For vectors, broadcast the value.
433 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
434 return ConstantVector::get(
435 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
441 Constant *ConstantFP::get(const Type* Ty, StringRef Str) {
442 LLVMContext &Context = Ty->getContext();
444 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
445 Constant *C = get(Context, FV);
447 // For vectors, broadcast the value.
448 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
449 return ConstantVector::get(
450 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
456 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
457 LLVMContext &Context = Ty->getContext();
458 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
460 return get(Context, apf);
464 Constant *ConstantFP::getZeroValueForNegation(const Type* Ty) {
465 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
466 if (PTy->getElementType()->isFloatingPointTy()) {
467 SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
468 getNegativeZero(PTy->getElementType()));
469 return ConstantVector::get(zeros);
472 if (Ty->isFloatingPointTy())
473 return getNegativeZero(Ty);
475 return Constant::getNullValue(Ty);
479 // ConstantFP accessors.
480 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
481 DenseMapAPFloatKeyInfo::KeyTy Key(V);
483 LLVMContextImpl* pImpl = Context.pImpl;
485 ConstantFP *&Slot = pImpl->FPConstants[Key];
489 if (&V.getSemantics() == &APFloat::IEEEsingle)
490 Ty = Type::getFloatTy(Context);
491 else if (&V.getSemantics() == &APFloat::IEEEdouble)
492 Ty = Type::getDoubleTy(Context);
493 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
494 Ty = Type::getX86_FP80Ty(Context);
495 else if (&V.getSemantics() == &APFloat::IEEEquad)
496 Ty = Type::getFP128Ty(Context);
498 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
499 "Unknown FP format");
500 Ty = Type::getPPC_FP128Ty(Context);
502 Slot = new ConstantFP(Ty, V);
508 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
509 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
510 return ConstantFP::get(Ty->getContext(),
511 APFloat::getInf(Semantics, Negative));
514 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
515 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
516 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
520 bool ConstantFP::isNullValue() const {
521 return Val.isZero() && !Val.isNegative();
524 bool ConstantFP::isExactlyValue(const APFloat& V) const {
525 return Val.bitwiseIsEqual(V);
528 //===----------------------------------------------------------------------===//
529 // ConstantXXX Classes
530 //===----------------------------------------------------------------------===//
533 ConstantArray::ConstantArray(const ArrayType *T,
534 const std::vector<Constant*> &V)
535 : Constant(T, ConstantArrayVal,
536 OperandTraits<ConstantArray>::op_end(this) - V.size(),
538 assert(V.size() == T->getNumElements() &&
539 "Invalid initializer vector for constant array");
540 Use *OL = OperandList;
541 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
544 assert(C->getType() == T->getElementType() &&
545 "Initializer for array element doesn't match array element type!");
550 Constant *ConstantArray::get(const ArrayType *Ty,
551 const std::vector<Constant*> &V) {
552 for (unsigned i = 0, e = V.size(); i != e; ++i) {
553 assert(V[i]->getType() == Ty->getElementType() &&
554 "Wrong type in array element initializer");
556 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
557 // If this is an all-zero array, return a ConstantAggregateZero object
560 if (!C->isNullValue())
561 return pImpl->ArrayConstants.getOrCreate(Ty, V);
563 for (unsigned i = 1, e = V.size(); i != e; ++i)
565 return pImpl->ArrayConstants.getOrCreate(Ty, V);
568 return ConstantAggregateZero::get(Ty);
572 Constant *ConstantArray::get(const ArrayType* T, Constant *const* Vals,
574 // FIXME: make this the primary ctor method.
575 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
578 /// ConstantArray::get(const string&) - Return an array that is initialized to
579 /// contain the specified string. If length is zero then a null terminator is
580 /// added to the specified string so that it may be used in a natural way.
581 /// Otherwise, the length parameter specifies how much of the string to use
582 /// and it won't be null terminated.
584 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
586 std::vector<Constant*> ElementVals;
587 ElementVals.reserve(Str.size() + size_t(AddNull));
588 for (unsigned i = 0; i < Str.size(); ++i)
589 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
591 // Add a null terminator to the string...
593 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
596 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
597 return get(ATy, ElementVals);
600 ConstantStruct::ConstantStruct(const StructType *T,
601 const std::vector<Constant*> &V)
602 : Constant(T, ConstantStructVal,
603 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
605 assert(V.size() == T->getNumElements() &&
606 "Invalid initializer vector for constant structure");
607 Use *OL = OperandList;
608 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
611 assert(C->getType() == T->getElementType(I-V.begin()) &&
612 "Initializer for struct element doesn't match struct element type!");
617 // ConstantStruct accessors.
618 Constant *ConstantStruct::get(const StructType* T,
619 const std::vector<Constant*>& V) {
620 LLVMContextImpl* pImpl = T->getContext().pImpl;
622 // Create a ConstantAggregateZero value if all elements are zeros...
623 for (unsigned i = 0, e = V.size(); i != e; ++i)
624 if (!V[i]->isNullValue())
625 return pImpl->StructConstants.getOrCreate(T, V);
627 return ConstantAggregateZero::get(T);
630 Constant *ConstantStruct::get(LLVMContext &Context,
631 const std::vector<Constant*>& V, bool packed) {
632 std::vector<const Type*> StructEls;
633 StructEls.reserve(V.size());
634 for (unsigned i = 0, e = V.size(); i != e; ++i)
635 StructEls.push_back(V[i]->getType());
636 return get(StructType::get(Context, StructEls, packed), V);
639 Constant *ConstantStruct::get(LLVMContext &Context,
640 Constant *const *Vals, unsigned NumVals,
642 // FIXME: make this the primary ctor method.
643 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
646 Constant* ConstantStruct::get(LLVMContext &Context, bool Packed,
647 Constant * Val, ...) {
649 std::vector<Constant*> Values;
652 Values.push_back(Val);
653 Val = va_arg(ap, llvm::Constant*);
655 return get(Context, Values, Packed);
658 ConstantVector::ConstantVector(const VectorType *T,
659 const std::vector<Constant*> &V)
660 : Constant(T, ConstantVectorVal,
661 OperandTraits<ConstantVector>::op_end(this) - V.size(),
663 Use *OL = OperandList;
664 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
667 assert(C->getType() == T->getElementType() &&
668 "Initializer for vector element doesn't match vector element type!");
673 // ConstantVector accessors.
674 Constant *ConstantVector::get(const VectorType *T,
675 const std::vector<Constant*> &V) {
676 assert(!V.empty() && "Vectors can't be empty");
677 LLVMContextImpl *pImpl = T->getContext().pImpl;
679 // If this is an all-undef or all-zero vector, return a
680 // ConstantAggregateZero or UndefValue.
682 bool isZero = C->isNullValue();
683 bool isUndef = isa<UndefValue>(C);
685 if (isZero || isUndef) {
686 for (unsigned i = 1, e = V.size(); i != e; ++i)
688 isZero = isUndef = false;
694 return ConstantAggregateZero::get(T);
696 return UndefValue::get(T);
698 return pImpl->VectorConstants.getOrCreate(T, V);
701 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
702 // FIXME: make this the primary ctor method.
703 assert(!V.empty() && "Vectors cannot be empty");
704 return get(VectorType::get(V.front()->getType(), V.size()), V.vec());
707 // Utility function for determining if a ConstantExpr is a CastOp or not. This
708 // can't be inline because we don't want to #include Instruction.h into
710 bool ConstantExpr::isCast() const {
711 return Instruction::isCast(getOpcode());
714 bool ConstantExpr::isCompare() const {
715 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
718 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
719 if (getOpcode() != Instruction::GetElementPtr) return false;
721 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
722 User::const_op_iterator OI = llvm::next(this->op_begin());
724 // Skip the first index, as it has no static limit.
728 // The remaining indices must be compile-time known integers within the
729 // bounds of the corresponding notional static array types.
730 for (; GEPI != E; ++GEPI, ++OI) {
731 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
732 if (!CI) return false;
733 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
734 if (CI->getValue().getActiveBits() > 64 ||
735 CI->getZExtValue() >= ATy->getNumElements())
739 // All the indices checked out.
743 bool ConstantExpr::hasIndices() const {
744 return getOpcode() == Instruction::ExtractValue ||
745 getOpcode() == Instruction::InsertValue;
748 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
749 if (const ExtractValueConstantExpr *EVCE =
750 dyn_cast<ExtractValueConstantExpr>(this))
751 return EVCE->Indices;
753 return cast<InsertValueConstantExpr>(this)->Indices;
756 unsigned ConstantExpr::getPredicate() const {
757 assert(getOpcode() == Instruction::FCmp ||
758 getOpcode() == Instruction::ICmp);
759 return ((const CompareConstantExpr*)this)->predicate;
762 /// getWithOperandReplaced - Return a constant expression identical to this
763 /// one, but with the specified operand set to the specified value.
765 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
766 assert(OpNo < getNumOperands() && "Operand num is out of range!");
767 assert(Op->getType() == getOperand(OpNo)->getType() &&
768 "Replacing operand with value of different type!");
769 if (getOperand(OpNo) == Op)
770 return const_cast<ConstantExpr*>(this);
772 Constant *Op0, *Op1, *Op2;
773 switch (getOpcode()) {
774 case Instruction::Trunc:
775 case Instruction::ZExt:
776 case Instruction::SExt:
777 case Instruction::FPTrunc:
778 case Instruction::FPExt:
779 case Instruction::UIToFP:
780 case Instruction::SIToFP:
781 case Instruction::FPToUI:
782 case Instruction::FPToSI:
783 case Instruction::PtrToInt:
784 case Instruction::IntToPtr:
785 case Instruction::BitCast:
786 return ConstantExpr::getCast(getOpcode(), Op, getType());
787 case Instruction::Select:
788 Op0 = (OpNo == 0) ? Op : getOperand(0);
789 Op1 = (OpNo == 1) ? Op : getOperand(1);
790 Op2 = (OpNo == 2) ? Op : getOperand(2);
791 return ConstantExpr::getSelect(Op0, Op1, Op2);
792 case Instruction::InsertElement:
793 Op0 = (OpNo == 0) ? Op : getOperand(0);
794 Op1 = (OpNo == 1) ? Op : getOperand(1);
795 Op2 = (OpNo == 2) ? Op : getOperand(2);
796 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
797 case Instruction::ExtractElement:
798 Op0 = (OpNo == 0) ? Op : getOperand(0);
799 Op1 = (OpNo == 1) ? Op : getOperand(1);
800 return ConstantExpr::getExtractElement(Op0, Op1);
801 case Instruction::ShuffleVector:
802 Op0 = (OpNo == 0) ? Op : getOperand(0);
803 Op1 = (OpNo == 1) ? Op : getOperand(1);
804 Op2 = (OpNo == 2) ? Op : getOperand(2);
805 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
806 case Instruction::GetElementPtr: {
807 SmallVector<Constant*, 8> Ops;
808 Ops.resize(getNumOperands()-1);
809 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
810 Ops[i-1] = getOperand(i);
812 return cast<GEPOperator>(this)->isInBounds() ?
813 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
814 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
816 return cast<GEPOperator>(this)->isInBounds() ?
817 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
818 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
821 assert(getNumOperands() == 2 && "Must be binary operator?");
822 Op0 = (OpNo == 0) ? Op : getOperand(0);
823 Op1 = (OpNo == 1) ? Op : getOperand(1);
824 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
828 /// getWithOperands - This returns the current constant expression with the
829 /// operands replaced with the specified values. The specified operands must
830 /// match count and type with the existing ones.
831 Constant *ConstantExpr::
832 getWithOperands(Constant *const *Ops, unsigned NumOps) const {
833 assert(NumOps == getNumOperands() && "Operand count mismatch!");
834 bool AnyChange = false;
835 for (unsigned i = 0; i != NumOps; ++i) {
836 assert(Ops[i]->getType() == getOperand(i)->getType() &&
837 "Operand type mismatch!");
838 AnyChange |= Ops[i] != getOperand(i);
840 if (!AnyChange) // No operands changed, return self.
841 return const_cast<ConstantExpr*>(this);
843 switch (getOpcode()) {
844 case Instruction::Trunc:
845 case Instruction::ZExt:
846 case Instruction::SExt:
847 case Instruction::FPTrunc:
848 case Instruction::FPExt:
849 case Instruction::UIToFP:
850 case Instruction::SIToFP:
851 case Instruction::FPToUI:
852 case Instruction::FPToSI:
853 case Instruction::PtrToInt:
854 case Instruction::IntToPtr:
855 case Instruction::BitCast:
856 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
857 case Instruction::Select:
858 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
859 case Instruction::InsertElement:
860 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
861 case Instruction::ExtractElement:
862 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
863 case Instruction::ShuffleVector:
864 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
865 case Instruction::GetElementPtr:
866 return cast<GEPOperator>(this)->isInBounds() ?
867 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
868 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
869 case Instruction::ICmp:
870 case Instruction::FCmp:
871 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
873 assert(getNumOperands() == 2 && "Must be binary operator?");
874 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
879 //===----------------------------------------------------------------------===//
880 // isValueValidForType implementations
882 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
883 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
884 if (Ty == Type::getInt1Ty(Ty->getContext()))
885 return Val == 0 || Val == 1;
887 return true; // always true, has to fit in largest type
888 uint64_t Max = (1ll << NumBits) - 1;
892 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
893 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
894 if (Ty == Type::getInt1Ty(Ty->getContext()))
895 return Val == 0 || Val == 1 || Val == -1;
897 return true; // always true, has to fit in largest type
898 int64_t Min = -(1ll << (NumBits-1));
899 int64_t Max = (1ll << (NumBits-1)) - 1;
900 return (Val >= Min && Val <= Max);
903 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
904 // convert modifies in place, so make a copy.
905 APFloat Val2 = APFloat(Val);
907 switch (Ty->getTypeID()) {
909 return false; // These can't be represented as floating point!
911 // FIXME rounding mode needs to be more flexible
912 case Type::FloatTyID: {
913 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
915 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
918 case Type::DoubleTyID: {
919 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
920 &Val2.getSemantics() == &APFloat::IEEEdouble)
922 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
925 case Type::X86_FP80TyID:
926 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
927 &Val2.getSemantics() == &APFloat::IEEEdouble ||
928 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
929 case Type::FP128TyID:
930 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
931 &Val2.getSemantics() == &APFloat::IEEEdouble ||
932 &Val2.getSemantics() == &APFloat::IEEEquad;
933 case Type::PPC_FP128TyID:
934 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
935 &Val2.getSemantics() == &APFloat::IEEEdouble ||
936 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
940 //===----------------------------------------------------------------------===//
941 // Factory Function Implementation
943 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
944 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
945 "Cannot create an aggregate zero of non-aggregate type!");
947 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
948 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
951 /// destroyConstant - Remove the constant from the constant table...
953 void ConstantAggregateZero::destroyConstant() {
954 getRawType()->getContext().pImpl->AggZeroConstants.remove(this);
955 destroyConstantImpl();
958 /// destroyConstant - Remove the constant from the constant table...
960 void ConstantArray::destroyConstant() {
961 getRawType()->getContext().pImpl->ArrayConstants.remove(this);
962 destroyConstantImpl();
965 /// isString - This method returns true if the array is an array of i8, and
966 /// if the elements of the array are all ConstantInt's.
967 bool ConstantArray::isString() const {
968 // Check the element type for i8...
969 if (!getType()->getElementType()->isIntegerTy(8))
971 // Check the elements to make sure they are all integers, not constant
973 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
974 if (!isa<ConstantInt>(getOperand(i)))
979 /// isCString - This method returns true if the array is a string (see
980 /// isString) and it ends in a null byte \\0 and does not contains any other
981 /// null bytes except its terminator.
982 bool ConstantArray::isCString() const {
983 // Check the element type for i8...
984 if (!getType()->getElementType()->isIntegerTy(8))
987 // Last element must be a null.
988 if (!getOperand(getNumOperands()-1)->isNullValue())
990 // Other elements must be non-null integers.
991 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
992 if (!isa<ConstantInt>(getOperand(i)))
994 if (getOperand(i)->isNullValue())
1001 /// getAsString - If the sub-element type of this array is i8
1002 /// then this method converts the array to an std::string and returns it.
1003 /// Otherwise, it asserts out.
1005 std::string ConstantArray::getAsString() const {
1006 assert(isString() && "Not a string!");
1008 Result.reserve(getNumOperands());
1009 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1010 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
1015 //---- ConstantStruct::get() implementation...
1022 // destroyConstant - Remove the constant from the constant table...
1024 void ConstantStruct::destroyConstant() {
1025 getRawType()->getContext().pImpl->StructConstants.remove(this);
1026 destroyConstantImpl();
1029 // destroyConstant - Remove the constant from the constant table...
1031 void ConstantVector::destroyConstant() {
1032 getRawType()->getContext().pImpl->VectorConstants.remove(this);
1033 destroyConstantImpl();
1036 /// This function will return true iff every element in this vector constant
1037 /// is set to all ones.
1038 /// @returns true iff this constant's emements are all set to all ones.
1039 /// @brief Determine if the value is all ones.
1040 bool ConstantVector::isAllOnesValue() const {
1041 // Check out first element.
1042 const Constant *Elt = getOperand(0);
1043 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1044 if (!CI || !CI->isAllOnesValue()) return false;
1045 // Then make sure all remaining elements point to the same value.
1046 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1047 if (getOperand(I) != Elt) return false;
1052 /// getSplatValue - If this is a splat constant, where all of the
1053 /// elements have the same value, return that value. Otherwise return null.
1054 Constant *ConstantVector::getSplatValue() const {
1055 // Check out first element.
1056 Constant *Elt = getOperand(0);
1057 // Then make sure all remaining elements point to the same value.
1058 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1059 if (getOperand(I) != Elt) return 0;
1063 //---- ConstantPointerNull::get() implementation.
1066 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1067 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1070 // destroyConstant - Remove the constant from the constant table...
1072 void ConstantPointerNull::destroyConstant() {
1073 getRawType()->getContext().pImpl->NullPtrConstants.remove(this);
1074 destroyConstantImpl();
1078 //---- UndefValue::get() implementation.
1081 UndefValue *UndefValue::get(const Type *Ty) {
1082 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1085 // destroyConstant - Remove the constant from the constant table.
1087 void UndefValue::destroyConstant() {
1088 getRawType()->getContext().pImpl->UndefValueConstants.remove(this);
1089 destroyConstantImpl();
1092 //---- BlockAddress::get() implementation.
1095 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1096 assert(BB->getParent() != 0 && "Block must have a parent");
1097 return get(BB->getParent(), BB);
1100 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1102 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1104 BA = new BlockAddress(F, BB);
1106 assert(BA->getFunction() == F && "Basic block moved between functions");
1110 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1111 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1115 BB->AdjustBlockAddressRefCount(1);
1119 // destroyConstant - Remove the constant from the constant table.
1121 void BlockAddress::destroyConstant() {
1122 getFunction()->getRawType()->getContext().pImpl
1123 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1124 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1125 destroyConstantImpl();
1128 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1129 // This could be replacing either the Basic Block or the Function. In either
1130 // case, we have to remove the map entry.
1131 Function *NewF = getFunction();
1132 BasicBlock *NewBB = getBasicBlock();
1135 NewF = cast<Function>(To);
1137 NewBB = cast<BasicBlock>(To);
1139 // See if the 'new' entry already exists, if not, just update this in place
1140 // and return early.
1141 BlockAddress *&NewBA =
1142 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1144 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1146 // Remove the old entry, this can't cause the map to rehash (just a
1147 // tombstone will get added).
1148 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1151 setOperand(0, NewF);
1152 setOperand(1, NewBB);
1153 getBasicBlock()->AdjustBlockAddressRefCount(1);
1157 // Otherwise, I do need to replace this with an existing value.
1158 assert(NewBA != this && "I didn't contain From!");
1160 // Everyone using this now uses the replacement.
1161 uncheckedReplaceAllUsesWith(NewBA);
1166 //---- ConstantExpr::get() implementations.
1169 /// This is a utility function to handle folding of casts and lookup of the
1170 /// cast in the ExprConstants map. It is used by the various get* methods below.
1171 static inline Constant *getFoldedCast(
1172 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1173 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1174 // Fold a few common cases
1175 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1178 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1180 // Look up the constant in the table first to ensure uniqueness
1181 std::vector<Constant*> argVec(1, C);
1182 ExprMapKeyType Key(opc, argVec);
1184 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1187 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1188 Instruction::CastOps opc = Instruction::CastOps(oc);
1189 assert(Instruction::isCast(opc) && "opcode out of range");
1190 assert(C && Ty && "Null arguments to getCast");
1191 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1195 llvm_unreachable("Invalid cast opcode");
1197 case Instruction::Trunc: return getTrunc(C, Ty);
1198 case Instruction::ZExt: return getZExt(C, Ty);
1199 case Instruction::SExt: return getSExt(C, Ty);
1200 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1201 case Instruction::FPExt: return getFPExtend(C, Ty);
1202 case Instruction::UIToFP: return getUIToFP(C, Ty);
1203 case Instruction::SIToFP: return getSIToFP(C, Ty);
1204 case Instruction::FPToUI: return getFPToUI(C, Ty);
1205 case Instruction::FPToSI: return getFPToSI(C, Ty);
1206 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1207 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1208 case Instruction::BitCast: return getBitCast(C, Ty);
1213 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1214 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1215 return getBitCast(C, Ty);
1216 return getZExt(C, Ty);
1219 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1220 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1221 return getBitCast(C, Ty);
1222 return getSExt(C, Ty);
1225 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1226 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1227 return getBitCast(C, Ty);
1228 return getTrunc(C, Ty);
1231 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1232 assert(S->getType()->isPointerTy() && "Invalid cast");
1233 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1235 if (Ty->isIntegerTy())
1236 return getPtrToInt(S, Ty);
1237 return getBitCast(S, Ty);
1240 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1242 assert(C->getType()->isIntOrIntVectorTy() &&
1243 Ty->isIntOrIntVectorTy() && "Invalid cast");
1244 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1245 unsigned DstBits = Ty->getScalarSizeInBits();
1246 Instruction::CastOps opcode =
1247 (SrcBits == DstBits ? Instruction::BitCast :
1248 (SrcBits > DstBits ? Instruction::Trunc :
1249 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1250 return getCast(opcode, C, Ty);
1253 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1254 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1256 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1257 unsigned DstBits = Ty->getScalarSizeInBits();
1258 if (SrcBits == DstBits)
1259 return C; // Avoid a useless cast
1260 Instruction::CastOps opcode =
1261 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1262 return getCast(opcode, C, Ty);
1265 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1267 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1268 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1270 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1271 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1272 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1273 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1274 "SrcTy must be larger than DestTy for Trunc!");
1276 return getFoldedCast(Instruction::Trunc, C, Ty);
1279 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1281 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1282 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1284 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1285 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1286 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1287 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1288 "SrcTy must be smaller than DestTy for SExt!");
1290 return getFoldedCast(Instruction::SExt, C, Ty);
1293 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1295 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1296 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1298 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1299 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1300 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1301 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1302 "SrcTy must be smaller than DestTy for ZExt!");
1304 return getFoldedCast(Instruction::ZExt, C, Ty);
1307 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1309 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1310 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1312 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1313 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1314 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1315 "This is an illegal floating point truncation!");
1316 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1319 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1321 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1322 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1324 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1325 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1326 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1327 "This is an illegal floating point extension!");
1328 return getFoldedCast(Instruction::FPExt, C, Ty);
1331 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1333 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1334 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1336 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1337 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1338 "This is an illegal uint to floating point cast!");
1339 return getFoldedCast(Instruction::UIToFP, C, Ty);
1342 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1344 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1345 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1347 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1348 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1349 "This is an illegal sint to floating point cast!");
1350 return getFoldedCast(Instruction::SIToFP, C, Ty);
1353 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1355 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1356 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1358 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1359 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1360 "This is an illegal floating point to uint cast!");
1361 return getFoldedCast(Instruction::FPToUI, C, Ty);
1364 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1366 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1367 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1369 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1370 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1371 "This is an illegal floating point to sint cast!");
1372 return getFoldedCast(Instruction::FPToSI, C, Ty);
1375 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1376 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1377 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1378 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1381 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1382 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1383 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1384 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1387 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1388 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1389 "Invalid constantexpr bitcast!");
1391 // It is common to ask for a bitcast of a value to its own type, handle this
1393 if (C->getType() == DstTy) return C;
1395 return getFoldedCast(Instruction::BitCast, C, DstTy);
1398 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1399 Constant *C1, Constant *C2,
1401 // Check the operands for consistency first
1402 assert(Opcode >= Instruction::BinaryOpsBegin &&
1403 Opcode < Instruction::BinaryOpsEnd &&
1404 "Invalid opcode in binary constant expression");
1405 assert(C1->getType() == C2->getType() &&
1406 "Operand types in binary constant expression should match");
1408 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1409 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1410 return FC; // Fold a few common cases...
1412 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1413 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1415 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1416 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1419 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1420 Constant *C1, Constant *C2) {
1421 switch (predicate) {
1422 default: llvm_unreachable("Invalid CmpInst predicate");
1423 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1424 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1425 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1426 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1427 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1428 case CmpInst::FCMP_TRUE:
1429 return getFCmp(predicate, C1, C2);
1431 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1432 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1433 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1434 case CmpInst::ICMP_SLE:
1435 return getICmp(predicate, C1, C2);
1439 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1443 case Instruction::Add:
1444 case Instruction::Sub:
1445 case Instruction::Mul:
1446 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1447 assert(C1->getType()->isIntOrIntVectorTy() &&
1448 "Tried to create an integer operation on a non-integer type!");
1450 case Instruction::FAdd:
1451 case Instruction::FSub:
1452 case Instruction::FMul:
1453 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1454 assert(C1->getType()->isFPOrFPVectorTy() &&
1455 "Tried to create a floating-point operation on a "
1456 "non-floating-point type!");
1458 case Instruction::UDiv:
1459 case Instruction::SDiv:
1460 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1461 assert(C1->getType()->isIntOrIntVectorTy() &&
1462 "Tried to create an arithmetic operation on a non-arithmetic type!");
1464 case Instruction::FDiv:
1465 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1466 assert(C1->getType()->isFPOrFPVectorTy() &&
1467 "Tried to create an arithmetic operation on a non-arithmetic type!");
1469 case Instruction::URem:
1470 case Instruction::SRem:
1471 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1472 assert(C1->getType()->isIntOrIntVectorTy() &&
1473 "Tried to create an arithmetic operation on a non-arithmetic type!");
1475 case Instruction::FRem:
1476 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1477 assert(C1->getType()->isFPOrFPVectorTy() &&
1478 "Tried to create an arithmetic operation on a non-arithmetic type!");
1480 case Instruction::And:
1481 case Instruction::Or:
1482 case Instruction::Xor:
1483 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1484 assert(C1->getType()->isIntOrIntVectorTy() &&
1485 "Tried to create a logical operation on a non-integral type!");
1487 case Instruction::Shl:
1488 case Instruction::LShr:
1489 case Instruction::AShr:
1490 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1491 assert(C1->getType()->isIntOrIntVectorTy() &&
1492 "Tried to create a shift operation on a non-integer type!");
1499 return getTy(C1->getType(), Opcode, C1, C2, Flags);
1502 Constant *ConstantExpr::getSizeOf(const Type* Ty) {
1503 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1504 // Note that a non-inbounds gep is used, as null isn't within any object.
1505 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1506 Constant *GEP = getGetElementPtr(
1507 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1508 return getPtrToInt(GEP,
1509 Type::getInt64Ty(Ty->getContext()));
1512 Constant *ConstantExpr::getAlignOf(const Type* Ty) {
1513 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1514 // Note that a non-inbounds gep is used, as null isn't within any object.
1515 const Type *AligningTy = StructType::get(Ty->getContext(),
1516 Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1517 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1518 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1519 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1520 Constant *Indices[2] = { Zero, One };
1521 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1522 return getPtrToInt(GEP,
1523 Type::getInt64Ty(Ty->getContext()));
1526 Constant *ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1527 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1531 Constant *ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
1532 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1533 // Note that a non-inbounds gep is used, as null isn't within any object.
1534 Constant *GEPIdx[] = {
1535 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1538 Constant *GEP = getGetElementPtr(
1539 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1540 return getPtrToInt(GEP,
1541 Type::getInt64Ty(Ty->getContext()));
1544 Constant *ConstantExpr::getCompare(unsigned short pred,
1545 Constant *C1, Constant *C2) {
1546 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1547 return getCompareTy(pred, C1, C2);
1550 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1551 Constant *V1, Constant *V2) {
1552 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1554 if (ReqTy == V1->getType())
1555 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1556 return SC; // Fold common cases
1558 std::vector<Constant*> argVec(3, C);
1561 ExprMapKeyType Key(Instruction::Select, argVec);
1563 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1564 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1567 template<typename IndexTy>
1568 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1569 IndexTy const *Idxs,
1570 unsigned NumIdx, bool InBounds) {
1571 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1573 cast<PointerType>(ReqTy)->getElementType() &&
1574 "GEP indices invalid!");
1576 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs, NumIdx))
1577 return FC; // Fold a few common cases.
1579 assert(C->getType()->isPointerTy() &&
1580 "Non-pointer type for constant GetElementPtr expression");
1581 // Look up the constant in the table first to ensure uniqueness
1582 std::vector<Constant*> ArgVec;
1583 ArgVec.reserve(NumIdx+1);
1584 ArgVec.push_back(C);
1585 for (unsigned i = 0; i != NumIdx; ++i)
1586 ArgVec.push_back(cast<Constant>(Idxs[i]));
1587 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1588 InBounds ? GEPOperator::IsInBounds : 0);
1590 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1591 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1594 template<typename IndexTy>
1595 Constant *ConstantExpr::getGetElementPtrImpl(Constant *C, IndexTy const *Idxs,
1596 unsigned NumIdx, bool InBounds) {
1597 // Get the result type of the getelementptr!
1599 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1600 assert(Ty && "GEP indices invalid!");
1601 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1602 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx,InBounds);
1605 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1606 unsigned NumIdx, bool InBounds) {
1607 return getGetElementPtrImpl(C, Idxs, NumIdx, InBounds);
1610 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant *const *Idxs,
1611 unsigned NumIdx, bool InBounds) {
1612 return getGetElementPtrImpl(C, Idxs, NumIdx, InBounds);
1616 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1617 assert(LHS->getType() == RHS->getType());
1618 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1619 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1621 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1622 return FC; // Fold a few common cases...
1624 // Look up the constant in the table first to ensure uniqueness
1625 std::vector<Constant*> ArgVec;
1626 ArgVec.push_back(LHS);
1627 ArgVec.push_back(RHS);
1628 // Get the key type with both the opcode and predicate
1629 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1631 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1632 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1633 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1635 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1636 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1640 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1641 assert(LHS->getType() == RHS->getType());
1642 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1644 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1645 return FC; // Fold a few common cases...
1647 // Look up the constant in the table first to ensure uniqueness
1648 std::vector<Constant*> ArgVec;
1649 ArgVec.push_back(LHS);
1650 ArgVec.push_back(RHS);
1651 // Get the key type with both the opcode and predicate
1652 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1654 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1655 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1656 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1658 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1659 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1662 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1664 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1665 return FC; // Fold a few common cases.
1666 // Look up the constant in the table first to ensure uniqueness
1667 std::vector<Constant*> ArgVec(1, Val);
1668 ArgVec.push_back(Idx);
1669 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1671 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1672 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1675 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1676 assert(Val->getType()->isVectorTy() &&
1677 "Tried to create extractelement operation on non-vector type!");
1678 assert(Idx->getType()->isIntegerTy(32) &&
1679 "Extractelement index must be i32 type!");
1680 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1684 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1685 Constant *Elt, Constant *Idx) {
1686 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1687 return FC; // Fold a few common cases.
1688 // Look up the constant in the table first to ensure uniqueness
1689 std::vector<Constant*> ArgVec(1, Val);
1690 ArgVec.push_back(Elt);
1691 ArgVec.push_back(Idx);
1692 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1694 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1695 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1698 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1700 assert(Val->getType()->isVectorTy() &&
1701 "Tried to create insertelement operation on non-vector type!");
1702 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1703 && "Insertelement types must match!");
1704 assert(Idx->getType()->isIntegerTy(32) &&
1705 "Insertelement index must be i32 type!");
1706 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1709 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1710 Constant *V2, Constant *Mask) {
1711 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1712 return FC; // Fold a few common cases...
1713 // Look up the constant in the table first to ensure uniqueness
1714 std::vector<Constant*> ArgVec(1, V1);
1715 ArgVec.push_back(V2);
1716 ArgVec.push_back(Mask);
1717 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1719 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1720 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1723 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1725 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1726 "Invalid shuffle vector constant expr operands!");
1728 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1729 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1730 const Type *ShufTy = VectorType::get(EltTy, NElts);
1731 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1734 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1736 const unsigned *Idxs, unsigned NumIdx) {
1737 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1738 Idxs+NumIdx) == Val->getType() &&
1739 "insertvalue indices invalid!");
1740 assert(Agg->getType() == ReqTy &&
1741 "insertvalue type invalid!");
1742 assert(Agg->getType()->isFirstClassType() &&
1743 "Non-first-class type for constant InsertValue expression");
1744 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs, NumIdx);
1745 assert(FC && "InsertValue constant expr couldn't be folded!");
1749 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1750 const unsigned *IdxList, unsigned NumIdx) {
1751 assert(Agg->getType()->isFirstClassType() &&
1752 "Tried to create insertelement operation on non-first-class type!");
1754 const Type *ReqTy = Agg->getType();
1757 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1759 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1760 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1763 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1764 const unsigned *Idxs, unsigned NumIdx) {
1765 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1766 Idxs+NumIdx) == ReqTy &&
1767 "extractvalue indices invalid!");
1768 assert(Agg->getType()->isFirstClassType() &&
1769 "Non-first-class type for constant extractvalue expression");
1770 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs, NumIdx);
1771 assert(FC && "ExtractValue constant expr couldn't be folded!");
1775 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1776 const unsigned *IdxList, unsigned NumIdx) {
1777 assert(Agg->getType()->isFirstClassType() &&
1778 "Tried to create extractelement operation on non-first-class type!");
1781 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1782 assert(ReqTy && "extractvalue indices invalid!");
1783 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1786 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1787 assert(C->getType()->isIntOrIntVectorTy() &&
1788 "Cannot NEG a nonintegral value!");
1789 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1793 Constant *ConstantExpr::getFNeg(Constant *C) {
1794 assert(C->getType()->isFPOrFPVectorTy() &&
1795 "Cannot FNEG a non-floating-point value!");
1796 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1799 Constant *ConstantExpr::getNot(Constant *C) {
1800 assert(C->getType()->isIntOrIntVectorTy() &&
1801 "Cannot NOT a nonintegral value!");
1802 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1805 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1806 bool HasNUW, bool HasNSW) {
1807 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1808 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1809 return get(Instruction::Add, C1, C2, Flags);
1812 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1813 return get(Instruction::FAdd, C1, C2);
1816 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1817 bool HasNUW, bool HasNSW) {
1818 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1819 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1820 return get(Instruction::Sub, C1, C2, Flags);
1823 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1824 return get(Instruction::FSub, C1, C2);
1827 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1828 bool HasNUW, bool HasNSW) {
1829 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1830 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1831 return get(Instruction::Mul, C1, C2, Flags);
1834 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1835 return get(Instruction::FMul, C1, C2);
1838 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1839 return get(Instruction::UDiv, C1, C2,
1840 isExact ? PossiblyExactOperator::IsExact : 0);
1843 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1844 return get(Instruction::SDiv, C1, C2,
1845 isExact ? PossiblyExactOperator::IsExact : 0);
1848 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1849 return get(Instruction::FDiv, C1, C2);
1852 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1853 return get(Instruction::URem, C1, C2);
1856 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1857 return get(Instruction::SRem, C1, C2);
1860 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1861 return get(Instruction::FRem, C1, C2);
1864 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1865 return get(Instruction::And, C1, C2);
1868 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1869 return get(Instruction::Or, C1, C2);
1872 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1873 return get(Instruction::Xor, C1, C2);
1876 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1877 bool HasNUW, bool HasNSW) {
1878 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1879 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1880 return get(Instruction::Shl, C1, C2, Flags);
1883 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1884 return get(Instruction::LShr, C1, C2,
1885 isExact ? PossiblyExactOperator::IsExact : 0);
1888 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1889 return get(Instruction::AShr, C1, C2,
1890 isExact ? PossiblyExactOperator::IsExact : 0);
1893 // destroyConstant - Remove the constant from the constant table...
1895 void ConstantExpr::destroyConstant() {
1896 getRawType()->getContext().pImpl->ExprConstants.remove(this);
1897 destroyConstantImpl();
1900 const char *ConstantExpr::getOpcodeName() const {
1901 return Instruction::getOpcodeName(getOpcode());
1906 GetElementPtrConstantExpr::
1907 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1909 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1910 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1911 - (IdxList.size()+1), IdxList.size()+1) {
1913 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1914 OperandList[i+1] = IdxList[i];
1918 //===----------------------------------------------------------------------===//
1919 // replaceUsesOfWithOnConstant implementations
1921 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1922 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1925 /// Note that we intentionally replace all uses of From with To here. Consider
1926 /// a large array that uses 'From' 1000 times. By handling this case all here,
1927 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1928 /// single invocation handles all 1000 uses. Handling them one at a time would
1929 /// work, but would be really slow because it would have to unique each updated
1932 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1934 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1935 Constant *ToC = cast<Constant>(To);
1937 LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
1939 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1940 Lookup.first.first = cast<ArrayType>(getRawType());
1941 Lookup.second = this;
1943 std::vector<Constant*> &Values = Lookup.first.second;
1944 Values.reserve(getNumOperands()); // Build replacement array.
1946 // Fill values with the modified operands of the constant array. Also,
1947 // compute whether this turns into an all-zeros array.
1948 bool isAllZeros = false;
1949 unsigned NumUpdated = 0;
1950 if (!ToC->isNullValue()) {
1951 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1952 Constant *Val = cast<Constant>(O->get());
1957 Values.push_back(Val);
1961 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1962 Constant *Val = cast<Constant>(O->get());
1967 Values.push_back(Val);
1968 if (isAllZeros) isAllZeros = Val->isNullValue();
1972 Constant *Replacement = 0;
1974 Replacement = ConstantAggregateZero::get(getRawType());
1976 // Check to see if we have this array type already.
1978 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1979 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1982 Replacement = I->second;
1984 // Okay, the new shape doesn't exist in the system yet. Instead of
1985 // creating a new constant array, inserting it, replaceallusesof'ing the
1986 // old with the new, then deleting the old... just update the current one
1988 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1990 // Update to the new value. Optimize for the case when we have a single
1991 // operand that we're changing, but handle bulk updates efficiently.
1992 if (NumUpdated == 1) {
1993 unsigned OperandToUpdate = U - OperandList;
1994 assert(getOperand(OperandToUpdate) == From &&
1995 "ReplaceAllUsesWith broken!");
1996 setOperand(OperandToUpdate, ToC);
1998 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1999 if (getOperand(i) == From)
2006 // Otherwise, I do need to replace this with an existing value.
2007 assert(Replacement != this && "I didn't contain From!");
2009 // Everyone using this now uses the replacement.
2010 uncheckedReplaceAllUsesWith(Replacement);
2012 // Delete the old constant!
2016 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2018 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2019 Constant *ToC = cast<Constant>(To);
2021 unsigned OperandToUpdate = U-OperandList;
2022 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2024 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2025 Lookup.first.first = cast<StructType>(getRawType());
2026 Lookup.second = this;
2027 std::vector<Constant*> &Values = Lookup.first.second;
2028 Values.reserve(getNumOperands()); // Build replacement struct.
2031 // Fill values with the modified operands of the constant struct. Also,
2032 // compute whether this turns into an all-zeros struct.
2033 bool isAllZeros = false;
2034 if (!ToC->isNullValue()) {
2035 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2036 Values.push_back(cast<Constant>(O->get()));
2039 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2040 Constant *Val = cast<Constant>(O->get());
2041 Values.push_back(Val);
2042 if (isAllZeros) isAllZeros = Val->isNullValue();
2045 Values[OperandToUpdate] = ToC;
2047 LLVMContextImpl *pImpl = getRawType()->getContext().pImpl;
2049 Constant *Replacement = 0;
2051 Replacement = ConstantAggregateZero::get(getRawType());
2053 // Check to see if we have this struct type already.
2055 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2056 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2059 Replacement = I->second;
2061 // Okay, the new shape doesn't exist in the system yet. Instead of
2062 // creating a new constant struct, inserting it, replaceallusesof'ing the
2063 // old with the new, then deleting the old... just update the current one
2065 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2067 // Update to the new value.
2068 setOperand(OperandToUpdate, ToC);
2073 assert(Replacement != this && "I didn't contain From!");
2075 // Everyone using this now uses the replacement.
2076 uncheckedReplaceAllUsesWith(Replacement);
2078 // Delete the old constant!
2082 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2084 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2086 std::vector<Constant*> Values;
2087 Values.reserve(getNumOperands()); // Build replacement array...
2088 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2089 Constant *Val = getOperand(i);
2090 if (Val == From) Val = cast<Constant>(To);
2091 Values.push_back(Val);
2094 Constant *Replacement = get(cast<VectorType>(getRawType()), Values);
2095 assert(Replacement != this && "I didn't contain From!");
2097 // Everyone using this now uses the replacement.
2098 uncheckedReplaceAllUsesWith(Replacement);
2100 // Delete the old constant!
2104 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2106 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2107 Constant *To = cast<Constant>(ToV);
2109 Constant *Replacement = 0;
2110 if (getOpcode() == Instruction::GetElementPtr) {
2111 SmallVector<Constant*, 8> Indices;
2112 Constant *Pointer = getOperand(0);
2113 Indices.reserve(getNumOperands()-1);
2114 if (Pointer == From) Pointer = To;
2116 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2117 Constant *Val = getOperand(i);
2118 if (Val == From) Val = To;
2119 Indices.push_back(Val);
2121 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2122 &Indices[0], Indices.size(),
2123 cast<GEPOperator>(this)->isInBounds());
2124 } else if (getOpcode() == Instruction::ExtractValue) {
2125 Constant *Agg = getOperand(0);
2126 if (Agg == From) Agg = To;
2128 const SmallVector<unsigned, 4> &Indices = getIndices();
2129 Replacement = ConstantExpr::getExtractValue(Agg,
2130 &Indices[0], Indices.size());
2131 } else if (getOpcode() == Instruction::InsertValue) {
2132 Constant *Agg = getOperand(0);
2133 Constant *Val = getOperand(1);
2134 if (Agg == From) Agg = To;
2135 if (Val == From) Val = To;
2137 const SmallVector<unsigned, 4> &Indices = getIndices();
2138 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2139 &Indices[0], Indices.size());
2140 } else if (isCast()) {
2141 assert(getOperand(0) == From && "Cast only has one use!");
2142 Replacement = ConstantExpr::getCast(getOpcode(), To, getRawType());
2143 } else if (getOpcode() == Instruction::Select) {
2144 Constant *C1 = getOperand(0);
2145 Constant *C2 = getOperand(1);
2146 Constant *C3 = getOperand(2);
2147 if (C1 == From) C1 = To;
2148 if (C2 == From) C2 = To;
2149 if (C3 == From) C3 = To;
2150 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2151 } else if (getOpcode() == Instruction::ExtractElement) {
2152 Constant *C1 = getOperand(0);
2153 Constant *C2 = getOperand(1);
2154 if (C1 == From) C1 = To;
2155 if (C2 == From) C2 = To;
2156 Replacement = ConstantExpr::getExtractElement(C1, C2);
2157 } else if (getOpcode() == Instruction::InsertElement) {
2158 Constant *C1 = getOperand(0);
2159 Constant *C2 = getOperand(1);
2160 Constant *C3 = getOperand(1);
2161 if (C1 == From) C1 = To;
2162 if (C2 == From) C2 = To;
2163 if (C3 == From) C3 = To;
2164 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2165 } else if (getOpcode() == Instruction::ShuffleVector) {
2166 Constant *C1 = getOperand(0);
2167 Constant *C2 = getOperand(1);
2168 Constant *C3 = getOperand(2);
2169 if (C1 == From) C1 = To;
2170 if (C2 == From) C2 = To;
2171 if (C3 == From) C3 = To;
2172 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2173 } else if (isCompare()) {
2174 Constant *C1 = getOperand(0);
2175 Constant *C2 = getOperand(1);
2176 if (C1 == From) C1 = To;
2177 if (C2 == From) C2 = To;
2178 if (getOpcode() == Instruction::ICmp)
2179 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2181 assert(getOpcode() == Instruction::FCmp);
2182 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2184 } else if (getNumOperands() == 2) {
2185 Constant *C1 = getOperand(0);
2186 Constant *C2 = getOperand(1);
2187 if (C1 == From) C1 = To;
2188 if (C2 == From) C2 = To;
2189 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2191 llvm_unreachable("Unknown ConstantExpr type!");
2195 assert(Replacement != this && "I didn't contain From!");
2197 // Everyone using this now uses the replacement.
2198 uncheckedReplaceAllUsesWith(Replacement);
2200 // Delete the old constant!