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"
34 #include "llvm/ADT/STLExtras.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 bool Constant::isNegativeZeroValue() const {
44 // Floating point values have an explicit -0.0 value.
45 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
46 return CFP->isZero() && CFP->isNegative();
48 // Otherwise, just use +0.0.
52 bool Constant::isNullValue() const {
54 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero() && !CFP->isNegative();
61 // constant zero is zero for aggregates and cpnull is null for pointers.
62 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
65 // Constructor to create a '0' constant of arbitrary type...
66 Constant *Constant::getNullValue(const Type *Ty) {
67 switch (Ty->getTypeID()) {
68 case Type::IntegerTyID:
69 return ConstantInt::get(Ty, 0);
71 return ConstantFP::get(Ty->getContext(),
72 APFloat::getZero(APFloat::IEEEsingle));
73 case Type::DoubleTyID:
74 return ConstantFP::get(Ty->getContext(),
75 APFloat::getZero(APFloat::IEEEdouble));
76 case Type::X86_FP80TyID:
77 return ConstantFP::get(Ty->getContext(),
78 APFloat::getZero(APFloat::x87DoubleExtended));
80 return ConstantFP::get(Ty->getContext(),
81 APFloat::getZero(APFloat::IEEEquad));
82 case Type::PPC_FP128TyID:
83 return ConstantFP::get(Ty->getContext(),
84 APFloat(APInt::getNullValue(128)));
85 case Type::PointerTyID:
86 return ConstantPointerNull::get(cast<PointerType>(Ty));
87 case Type::StructTyID:
89 case Type::VectorTyID:
90 return ConstantAggregateZero::get(Ty);
92 // Function, Label, or Opaque type?
93 assert(!"Cannot create a null constant of that type!");
98 Constant *Constant::getIntegerValue(const Type *Ty, const APInt &V) {
99 const Type *ScalarTy = Ty->getScalarType();
101 // Create the base integer constant.
102 Constant *C = ConstantInt::get(Ty->getContext(), V);
104 // Convert an integer to a pointer, if necessary.
105 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
106 C = ConstantExpr::getIntToPtr(C, PTy);
108 // Broadcast a scalar to a vector, if necessary.
109 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
110 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
115 Constant *Constant::getAllOnesValue(const Type *Ty) {
116 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
117 return ConstantInt::get(Ty->getContext(),
118 APInt::getAllOnesValue(ITy->getBitWidth()));
120 if (Ty->isFloatingPointTy()) {
121 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
122 !Ty->isPPC_FP128Ty());
123 return ConstantFP::get(Ty->getContext(), FL);
126 SmallVector<Constant*, 16> Elts;
127 const VectorType *VTy = cast<VectorType>(Ty);
128 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
129 assert(Elts[0] && "Not a vector integer type!");
130 return cast<ConstantVector>(ConstantVector::get(Elts));
133 void Constant::destroyConstantImpl() {
134 // When a Constant is destroyed, there may be lingering
135 // references to the constant by other constants in the constant pool. These
136 // constants are implicitly dependent on the module that is being deleted,
137 // but they don't know that. Because we only find out when the CPV is
138 // deleted, we must now notify all of our users (that should only be
139 // Constants) that they are, in fact, invalid now and should be deleted.
141 while (!use_empty()) {
142 Value *V = use_back();
143 #ifndef NDEBUG // Only in -g mode...
144 if (!isa<Constant>(V)) {
145 dbgs() << "While deleting: " << *this
146 << "\n\nUse still stuck around after Def is destroyed: "
150 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
151 Constant *CV = cast<Constant>(V);
152 CV->destroyConstant();
154 // The constant should remove itself from our use list...
155 assert((use_empty() || use_back() != V) && "Constant not removed!");
158 // Value has no outstanding references it is safe to delete it now...
162 /// canTrap - Return true if evaluation of this constant could trap. This is
163 /// true for things like constant expressions that could divide by zero.
164 bool Constant::canTrap() const {
165 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
166 // The only thing that could possibly trap are constant exprs.
167 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
168 if (!CE) return false;
170 // ConstantExpr traps if any operands can trap.
171 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
172 if (CE->getOperand(i)->canTrap())
175 // Otherwise, only specific operations can trap.
176 switch (CE->getOpcode()) {
179 case Instruction::UDiv:
180 case Instruction::SDiv:
181 case Instruction::FDiv:
182 case Instruction::URem:
183 case Instruction::SRem:
184 case Instruction::FRem:
185 // Div and rem can trap if the RHS is not known to be non-zero.
186 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
192 /// isConstantUsed - Return true if the constant has users other than constant
193 /// exprs and other dangling things.
194 bool Constant::isConstantUsed() const {
195 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
196 const Constant *UC = dyn_cast<Constant>(*UI);
197 if (UC == 0 || isa<GlobalValue>(UC))
200 if (UC->isConstantUsed())
208 /// getRelocationInfo - This method classifies the entry according to
209 /// whether or not it may generate a relocation entry. This must be
210 /// conservative, so if it might codegen to a relocatable entry, it should say
211 /// so. The return values are:
213 /// NoRelocation: This constant pool entry is guaranteed to never have a
214 /// relocation applied to it (because it holds a simple constant like
216 /// LocalRelocation: This entry has relocations, but the entries are
217 /// guaranteed to be resolvable by the static linker, so the dynamic
218 /// linker will never see them.
219 /// GlobalRelocations: This entry may have arbitrary relocations.
221 /// FIXME: This really should not be in VMCore.
222 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
223 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
224 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
225 return LocalRelocation; // Local to this file/library.
226 return GlobalRelocations; // Global reference.
229 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
230 return BA->getFunction()->getRelocationInfo();
232 // While raw uses of blockaddress need to be relocated, differences between
233 // two of them don't when they are for labels in the same function. This is a
234 // common idiom when creating a table for the indirect goto extension, so we
235 // handle it efficiently here.
236 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
237 if (CE->getOpcode() == Instruction::Sub) {
238 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
239 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
241 LHS->getOpcode() == Instruction::PtrToInt &&
242 RHS->getOpcode() == Instruction::PtrToInt &&
243 isa<BlockAddress>(LHS->getOperand(0)) &&
244 isa<BlockAddress>(RHS->getOperand(0)) &&
245 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
246 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
250 PossibleRelocationsTy Result = NoRelocation;
251 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
252 Result = std::max(Result,
253 cast<Constant>(getOperand(i))->getRelocationInfo());
259 /// getVectorElements - This method, which is only valid on constant of vector
260 /// type, returns the elements of the vector in the specified smallvector.
261 /// This handles breaking down a vector undef into undef elements, etc. For
262 /// constant exprs and other cases we can't handle, we return an empty vector.
263 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
264 assert(getType()->isVectorTy() && "Not a vector constant!");
266 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
267 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
268 Elts.push_back(CV->getOperand(i));
272 const VectorType *VT = cast<VectorType>(getType());
273 if (isa<ConstantAggregateZero>(this)) {
274 Elts.assign(VT->getNumElements(),
275 Constant::getNullValue(VT->getElementType()));
279 if (isa<UndefValue>(this)) {
280 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
284 // Unknown type, must be constant expr etc.
288 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
289 /// it. This involves recursively eliminating any dead users of the
291 static bool removeDeadUsersOfConstant(const Constant *C) {
292 if (isa<GlobalValue>(C)) return false; // Cannot remove this
294 while (!C->use_empty()) {
295 const Constant *User = dyn_cast<Constant>(C->use_back());
296 if (!User) return false; // Non-constant usage;
297 if (!removeDeadUsersOfConstant(User))
298 return false; // Constant wasn't dead
301 const_cast<Constant*>(C)->destroyConstant();
306 /// removeDeadConstantUsers - If there are any dead constant users dangling
307 /// off of this constant, remove them. This method is useful for clients
308 /// that want to check to see if a global is unused, but don't want to deal
309 /// with potentially dead constants hanging off of the globals.
310 void Constant::removeDeadConstantUsers() const {
311 Value::const_use_iterator I = use_begin(), E = use_end();
312 Value::const_use_iterator LastNonDeadUser = E;
314 const Constant *User = dyn_cast<Constant>(*I);
321 if (!removeDeadUsersOfConstant(User)) {
322 // If the constant wasn't dead, remember that this was the last live use
323 // and move on to the next constant.
329 // If the constant was dead, then the iterator is invalidated.
330 if (LastNonDeadUser == E) {
342 //===----------------------------------------------------------------------===//
344 //===----------------------------------------------------------------------===//
346 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
347 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
348 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
351 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
352 LLVMContextImpl *pImpl = Context.pImpl;
353 if (!pImpl->TheTrueVal)
354 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
355 return pImpl->TheTrueVal;
358 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
359 LLVMContextImpl *pImpl = Context.pImpl;
360 if (!pImpl->TheFalseVal)
361 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
362 return pImpl->TheFalseVal;
365 Constant *ConstantInt::getTrue(const Type *Ty) {
366 const VectorType *VTy = dyn_cast<VectorType>(Ty);
368 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
369 return ConstantInt::getTrue(Ty->getContext());
371 assert(VTy->getElementType()->isIntegerTy(1) &&
372 "True must be vector of i1 or i1.");
373 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
374 ConstantInt::getTrue(Ty->getContext()));
375 return ConstantVector::get(Splat);
378 Constant *ConstantInt::getFalse(const Type *Ty) {
379 const VectorType *VTy = dyn_cast<VectorType>(Ty);
381 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
382 return ConstantInt::getFalse(Ty->getContext());
384 assert(VTy->getElementType()->isIntegerTy(1) &&
385 "False must be vector of i1 or i1.");
386 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
387 ConstantInt::getFalse(Ty->getContext()));
388 return ConstantVector::get(Splat);
392 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
393 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
394 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
395 // compare APInt's of different widths, which would violate an APInt class
396 // invariant which generates an assertion.
397 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
398 // Get the corresponding integer type for the bit width of the value.
399 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
400 // get an existing value or the insertion position
401 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
402 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
403 if (!Slot) Slot = new ConstantInt(ITy, V);
407 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
408 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
410 // For vectors, broadcast the value.
411 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
412 return ConstantVector::get(SmallVector<Constant*,
413 16>(VTy->getNumElements(), C));
418 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
420 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
423 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
424 return get(Ty, V, true);
427 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
428 return get(Ty, V, true);
431 Constant *ConstantInt::get(const Type* Ty, const APInt& V) {
432 ConstantInt *C = get(Ty->getContext(), V);
433 assert(C->getType() == Ty->getScalarType() &&
434 "ConstantInt type doesn't match the type implied by its value!");
436 // For vectors, broadcast the value.
437 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
438 return ConstantVector::get(
439 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
444 ConstantInt* ConstantInt::get(const IntegerType* Ty, StringRef Str,
446 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
449 //===----------------------------------------------------------------------===//
451 //===----------------------------------------------------------------------===//
453 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
455 return &APFloat::IEEEsingle;
456 if (Ty->isDoubleTy())
457 return &APFloat::IEEEdouble;
458 if (Ty->isX86_FP80Ty())
459 return &APFloat::x87DoubleExtended;
460 else if (Ty->isFP128Ty())
461 return &APFloat::IEEEquad;
463 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
464 return &APFloat::PPCDoubleDouble;
467 /// get() - This returns a constant fp for the specified value in the
468 /// specified type. This should only be used for simple constant values like
469 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
470 Constant *ConstantFP::get(const Type* Ty, double V) {
471 LLVMContext &Context = Ty->getContext();
475 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
476 APFloat::rmNearestTiesToEven, &ignored);
477 Constant *C = get(Context, FV);
479 // For vectors, broadcast the value.
480 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
481 return ConstantVector::get(
482 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
488 Constant *ConstantFP::get(const Type* Ty, StringRef Str) {
489 LLVMContext &Context = Ty->getContext();
491 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
492 Constant *C = get(Context, FV);
494 // For vectors, broadcast the value.
495 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
496 return ConstantVector::get(
497 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
503 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
504 LLVMContext &Context = Ty->getContext();
505 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
507 return get(Context, apf);
511 Constant *ConstantFP::getZeroValueForNegation(const Type* Ty) {
512 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
513 if (PTy->getElementType()->isFloatingPointTy()) {
514 SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
515 getNegativeZero(PTy->getElementType()));
516 return ConstantVector::get(zeros);
519 if (Ty->isFloatingPointTy())
520 return getNegativeZero(Ty);
522 return Constant::getNullValue(Ty);
526 // ConstantFP accessors.
527 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
528 DenseMapAPFloatKeyInfo::KeyTy Key(V);
530 LLVMContextImpl* pImpl = Context.pImpl;
532 ConstantFP *&Slot = pImpl->FPConstants[Key];
536 if (&V.getSemantics() == &APFloat::IEEEsingle)
537 Ty = Type::getFloatTy(Context);
538 else if (&V.getSemantics() == &APFloat::IEEEdouble)
539 Ty = Type::getDoubleTy(Context);
540 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
541 Ty = Type::getX86_FP80Ty(Context);
542 else if (&V.getSemantics() == &APFloat::IEEEquad)
543 Ty = Type::getFP128Ty(Context);
545 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
546 "Unknown FP format");
547 Ty = Type::getPPC_FP128Ty(Context);
549 Slot = new ConstantFP(Ty, V);
555 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
556 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
557 return ConstantFP::get(Ty->getContext(),
558 APFloat::getInf(Semantics, Negative));
561 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
562 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
563 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
567 bool ConstantFP::isExactlyValue(const APFloat &V) const {
568 return Val.bitwiseIsEqual(V);
571 //===----------------------------------------------------------------------===//
572 // ConstantXXX Classes
573 //===----------------------------------------------------------------------===//
576 ConstantArray::ConstantArray(const ArrayType *T,
577 const std::vector<Constant*> &V)
578 : Constant(T, ConstantArrayVal,
579 OperandTraits<ConstantArray>::op_end(this) - V.size(),
581 assert(V.size() == T->getNumElements() &&
582 "Invalid initializer vector for constant array");
583 Use *OL = OperandList;
584 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
587 assert(C->getType() == T->getElementType() &&
588 "Initializer for array element doesn't match array element type!");
593 Constant *ConstantArray::get(const ArrayType *Ty, ArrayRef<Constant*> V) {
594 for (unsigned i = 0, e = V.size(); i != e; ++i) {
595 assert(V[i]->getType() == Ty->getElementType() &&
596 "Wrong type in array element initializer");
598 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
599 // If this is an all-zero array, return a ConstantAggregateZero object
602 if (!C->isNullValue())
603 return pImpl->ArrayConstants.getOrCreate(Ty, V);
605 for (unsigned i = 1, e = V.size(); i != e; ++i)
607 return pImpl->ArrayConstants.getOrCreate(Ty, V);
610 return ConstantAggregateZero::get(Ty);
613 /// ConstantArray::get(const string&) - Return an array that is initialized to
614 /// contain the specified string. If length is zero then a null terminator is
615 /// added to the specified string so that it may be used in a natural way.
616 /// Otherwise, the length parameter specifies how much of the string to use
617 /// and it won't be null terminated.
619 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
621 std::vector<Constant*> ElementVals;
622 ElementVals.reserve(Str.size() + size_t(AddNull));
623 for (unsigned i = 0; i < Str.size(); ++i)
624 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
626 // Add a null terminator to the string...
628 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
631 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
632 return get(ATy, ElementVals);
635 /// getTypeForElements - Return an anonymous struct type to use for a constant
636 /// with the specified set of elements. The list must not be empty.
637 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
638 ArrayRef<Constant*> V,
640 SmallVector<Type*, 16> EltTypes;
641 for (unsigned i = 0, e = V.size(); i != e; ++i)
642 EltTypes.push_back(V[i]->getType());
644 return StructType::get(Context, EltTypes, Packed);
648 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
651 "ConstantStruct::getTypeForElements cannot be called on empty list");
652 return getTypeForElements(V[0]->getContext(), V, Packed);
656 ConstantStruct::ConstantStruct(const StructType *T,
657 const std::vector<Constant*> &V)
658 : Constant(T, ConstantStructVal,
659 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
661 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
662 "Invalid initializer vector for constant structure");
663 Use *OL = OperandList;
664 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
667 assert((T->isOpaque() || C->getType() == T->getElementType(I-V.begin())) &&
668 "Initializer for struct element doesn't match struct element type!");
673 // ConstantStruct accessors.
674 Constant *ConstantStruct::get(const StructType *ST, ArrayRef<Constant*> V) {
675 // Create a ConstantAggregateZero value if all elements are zeros.
676 for (unsigned i = 0, e = V.size(); i != e; ++i)
677 if (!V[i]->isNullValue())
678 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
680 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
681 "Incorrect # elements specified to ConstantStruct::get");
682 return ConstantAggregateZero::get(ST);
685 Constant* ConstantStruct::get(const StructType *T, ...) {
687 SmallVector<Constant*, 8> Values;
689 while (Constant *Val = va_arg(ap, llvm::Constant*))
690 Values.push_back(Val);
692 return get(T, Values);
695 ConstantVector::ConstantVector(const VectorType *T,
696 const std::vector<Constant*> &V)
697 : Constant(T, ConstantVectorVal,
698 OperandTraits<ConstantVector>::op_end(this) - V.size(),
700 Use *OL = OperandList;
701 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
704 assert(C->getType() == T->getElementType() &&
705 "Initializer for vector element doesn't match vector element type!");
710 // ConstantVector accessors.
711 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
712 assert(!V.empty() && "Vectors can't be empty");
713 const VectorType *T = VectorType::get(V.front()->getType(), V.size());
714 LLVMContextImpl *pImpl = T->getContext().pImpl;
716 // If this is an all-undef or all-zero vector, return a
717 // ConstantAggregateZero or UndefValue.
719 bool isZero = C->isNullValue();
720 bool isUndef = isa<UndefValue>(C);
722 if (isZero || isUndef) {
723 for (unsigned i = 1, e = V.size(); i != e; ++i)
725 isZero = isUndef = false;
731 return ConstantAggregateZero::get(T);
733 return UndefValue::get(T);
735 return pImpl->VectorConstants.getOrCreate(T, V);
738 // Utility function for determining if a ConstantExpr is a CastOp or not. This
739 // can't be inline because we don't want to #include Instruction.h into
741 bool ConstantExpr::isCast() const {
742 return Instruction::isCast(getOpcode());
745 bool ConstantExpr::isCompare() const {
746 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
749 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
750 if (getOpcode() != Instruction::GetElementPtr) return false;
752 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
753 User::const_op_iterator OI = llvm::next(this->op_begin());
755 // Skip the first index, as it has no static limit.
759 // The remaining indices must be compile-time known integers within the
760 // bounds of the corresponding notional static array types.
761 for (; GEPI != E; ++GEPI, ++OI) {
762 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
763 if (!CI) return false;
764 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
765 if (CI->getValue().getActiveBits() > 64 ||
766 CI->getZExtValue() >= ATy->getNumElements())
770 // All the indices checked out.
774 bool ConstantExpr::hasIndices() const {
775 return getOpcode() == Instruction::ExtractValue ||
776 getOpcode() == Instruction::InsertValue;
779 ArrayRef<unsigned> ConstantExpr::getIndices() const {
780 if (const ExtractValueConstantExpr *EVCE =
781 dyn_cast<ExtractValueConstantExpr>(this))
782 return EVCE->Indices;
784 return cast<InsertValueConstantExpr>(this)->Indices;
787 unsigned ConstantExpr::getPredicate() const {
788 assert(getOpcode() == Instruction::FCmp ||
789 getOpcode() == Instruction::ICmp);
790 return ((const CompareConstantExpr*)this)->predicate;
793 /// getWithOperandReplaced - Return a constant expression identical to this
794 /// one, but with the specified operand set to the specified value.
796 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
797 assert(OpNo < getNumOperands() && "Operand num is out of range!");
798 assert(Op->getType() == getOperand(OpNo)->getType() &&
799 "Replacing operand with value of different type!");
800 if (getOperand(OpNo) == Op)
801 return const_cast<ConstantExpr*>(this);
803 Constant *Op0, *Op1, *Op2;
804 switch (getOpcode()) {
805 case Instruction::Trunc:
806 case Instruction::ZExt:
807 case Instruction::SExt:
808 case Instruction::FPTrunc:
809 case Instruction::FPExt:
810 case Instruction::UIToFP:
811 case Instruction::SIToFP:
812 case Instruction::FPToUI:
813 case Instruction::FPToSI:
814 case Instruction::PtrToInt:
815 case Instruction::IntToPtr:
816 case Instruction::BitCast:
817 return ConstantExpr::getCast(getOpcode(), Op, getType());
818 case Instruction::Select:
819 Op0 = (OpNo == 0) ? Op : getOperand(0);
820 Op1 = (OpNo == 1) ? Op : getOperand(1);
821 Op2 = (OpNo == 2) ? Op : getOperand(2);
822 return ConstantExpr::getSelect(Op0, Op1, Op2);
823 case Instruction::InsertElement:
824 Op0 = (OpNo == 0) ? Op : getOperand(0);
825 Op1 = (OpNo == 1) ? Op : getOperand(1);
826 Op2 = (OpNo == 2) ? Op : getOperand(2);
827 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
828 case Instruction::ExtractElement:
829 Op0 = (OpNo == 0) ? Op : getOperand(0);
830 Op1 = (OpNo == 1) ? Op : getOperand(1);
831 return ConstantExpr::getExtractElement(Op0, Op1);
832 case Instruction::ShuffleVector:
833 Op0 = (OpNo == 0) ? Op : getOperand(0);
834 Op1 = (OpNo == 1) ? Op : getOperand(1);
835 Op2 = (OpNo == 2) ? Op : getOperand(2);
836 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
837 case Instruction::GetElementPtr: {
838 SmallVector<Constant*, 8> Ops;
839 Ops.resize(getNumOperands()-1);
840 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
841 Ops[i-1] = getOperand(i);
843 return cast<GEPOperator>(this)->isInBounds() ?
844 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
845 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
847 return cast<GEPOperator>(this)->isInBounds() ?
848 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
849 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
852 assert(getNumOperands() == 2 && "Must be binary operator?");
853 Op0 = (OpNo == 0) ? Op : getOperand(0);
854 Op1 = (OpNo == 1) ? Op : getOperand(1);
855 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
859 /// getWithOperands - This returns the current constant expression with the
860 /// operands replaced with the specified values. The specified array must
861 /// have the same number of operands as our current one.
862 Constant *ConstantExpr::
863 getWithOperands(ArrayRef<Constant*> Ops, const Type *Ty) const {
864 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
865 bool AnyChange = Ty != getType();
866 for (unsigned i = 0; i != Ops.size(); ++i)
867 AnyChange |= Ops[i] != getOperand(i);
869 if (!AnyChange) // No operands changed, return self.
870 return const_cast<ConstantExpr*>(this);
872 switch (getOpcode()) {
873 case Instruction::Trunc:
874 case Instruction::ZExt:
875 case Instruction::SExt:
876 case Instruction::FPTrunc:
877 case Instruction::FPExt:
878 case Instruction::UIToFP:
879 case Instruction::SIToFP:
880 case Instruction::FPToUI:
881 case Instruction::FPToSI:
882 case Instruction::PtrToInt:
883 case Instruction::IntToPtr:
884 case Instruction::BitCast:
885 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
886 case Instruction::Select:
887 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
888 case Instruction::InsertElement:
889 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
890 case Instruction::ExtractElement:
891 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
892 case Instruction::ShuffleVector:
893 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
894 case Instruction::GetElementPtr:
895 return cast<GEPOperator>(this)->isInBounds() ?
896 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], Ops.size()-1) :
897 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
898 case Instruction::ICmp:
899 case Instruction::FCmp:
900 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
902 assert(getNumOperands() == 2 && "Must be binary operator?");
903 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
908 //===----------------------------------------------------------------------===//
909 // isValueValidForType implementations
911 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
912 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
913 if (Ty == Type::getInt1Ty(Ty->getContext()))
914 return Val == 0 || Val == 1;
916 return true; // always true, has to fit in largest type
917 uint64_t Max = (1ll << NumBits) - 1;
921 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
922 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
923 if (Ty == Type::getInt1Ty(Ty->getContext()))
924 return Val == 0 || Val == 1 || Val == -1;
926 return true; // always true, has to fit in largest type
927 int64_t Min = -(1ll << (NumBits-1));
928 int64_t Max = (1ll << (NumBits-1)) - 1;
929 return (Val >= Min && Val <= Max);
932 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
933 // convert modifies in place, so make a copy.
934 APFloat Val2 = APFloat(Val);
936 switch (Ty->getTypeID()) {
938 return false; // These can't be represented as floating point!
940 // FIXME rounding mode needs to be more flexible
941 case Type::FloatTyID: {
942 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
944 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
947 case Type::DoubleTyID: {
948 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
949 &Val2.getSemantics() == &APFloat::IEEEdouble)
951 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
954 case Type::X86_FP80TyID:
955 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
956 &Val2.getSemantics() == &APFloat::IEEEdouble ||
957 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
958 case Type::FP128TyID:
959 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
960 &Val2.getSemantics() == &APFloat::IEEEdouble ||
961 &Val2.getSemantics() == &APFloat::IEEEquad;
962 case Type::PPC_FP128TyID:
963 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
964 &Val2.getSemantics() == &APFloat::IEEEdouble ||
965 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
969 //===----------------------------------------------------------------------===//
970 // Factory Function Implementation
972 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
973 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
974 "Cannot create an aggregate zero of non-aggregate type!");
976 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
977 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
980 /// destroyConstant - Remove the constant from the constant table...
982 void ConstantAggregateZero::destroyConstant() {
983 getType()->getContext().pImpl->AggZeroConstants.remove(this);
984 destroyConstantImpl();
987 /// destroyConstant - Remove the constant from the constant table...
989 void ConstantArray::destroyConstant() {
990 getType()->getContext().pImpl->ArrayConstants.remove(this);
991 destroyConstantImpl();
994 /// isString - This method returns true if the array is an array of i8, and
995 /// if the elements of the array are all ConstantInt's.
996 bool ConstantArray::isString() const {
997 // Check the element type for i8...
998 if (!getType()->getElementType()->isIntegerTy(8))
1000 // Check the elements to make sure they are all integers, not constant
1002 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1003 if (!isa<ConstantInt>(getOperand(i)))
1008 /// isCString - This method returns true if the array is a string (see
1009 /// isString) and it ends in a null byte \\0 and does not contains any other
1010 /// null bytes except its terminator.
1011 bool ConstantArray::isCString() const {
1012 // Check the element type for i8...
1013 if (!getType()->getElementType()->isIntegerTy(8))
1016 // Last element must be a null.
1017 if (!getOperand(getNumOperands()-1)->isNullValue())
1019 // Other elements must be non-null integers.
1020 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1021 if (!isa<ConstantInt>(getOperand(i)))
1023 if (getOperand(i)->isNullValue())
1030 /// convertToString - Helper function for getAsString() and getAsCString().
1031 static std::string convertToString(const User *U, unsigned len)
1034 Result.reserve(len);
1035 for (unsigned i = 0; i != len; ++i)
1036 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1040 /// getAsString - If this array is isString(), then this method converts the
1041 /// array to an std::string and returns it. Otherwise, it asserts out.
1043 std::string ConstantArray::getAsString() const {
1044 assert(isString() && "Not a string!");
1045 return convertToString(this, getNumOperands());
1049 /// getAsCString - If this array is isCString(), then this method converts the
1050 /// array (without the trailing null byte) to an std::string and returns it.
1051 /// Otherwise, it asserts out.
1053 std::string ConstantArray::getAsCString() const {
1054 assert(isCString() && "Not a string!");
1055 return convertToString(this, getNumOperands() - 1);
1059 //---- ConstantStruct::get() implementation...
1066 // destroyConstant - Remove the constant from the constant table...
1068 void ConstantStruct::destroyConstant() {
1069 getType()->getContext().pImpl->StructConstants.remove(this);
1070 destroyConstantImpl();
1073 // destroyConstant - Remove the constant from the constant table...
1075 void ConstantVector::destroyConstant() {
1076 getType()->getContext().pImpl->VectorConstants.remove(this);
1077 destroyConstantImpl();
1080 /// This function will return true iff every element in this vector constant
1081 /// is set to all ones.
1082 /// @returns true iff this constant's emements are all set to all ones.
1083 /// @brief Determine if the value is all ones.
1084 bool ConstantVector::isAllOnesValue() const {
1085 // Check out first element.
1086 const Constant *Elt = getOperand(0);
1087 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1088 if (!CI || !CI->isAllOnesValue()) return false;
1089 // Then make sure all remaining elements point to the same value.
1090 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1091 if (getOperand(I) != Elt) return false;
1096 /// getSplatValue - If this is a splat constant, where all of the
1097 /// elements have the same value, return that value. Otherwise return null.
1098 Constant *ConstantVector::getSplatValue() const {
1099 // Check out first element.
1100 Constant *Elt = getOperand(0);
1101 // Then make sure all remaining elements point to the same value.
1102 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1103 if (getOperand(I) != Elt) return 0;
1107 //---- ConstantPointerNull::get() implementation.
1110 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1111 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1114 // destroyConstant - Remove the constant from the constant table...
1116 void ConstantPointerNull::destroyConstant() {
1117 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1118 destroyConstantImpl();
1122 //---- UndefValue::get() implementation.
1125 UndefValue *UndefValue::get(const Type *Ty) {
1126 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1129 // destroyConstant - Remove the constant from the constant table.
1131 void UndefValue::destroyConstant() {
1132 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1133 destroyConstantImpl();
1136 //---- BlockAddress::get() implementation.
1139 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1140 assert(BB->getParent() != 0 && "Block must have a parent");
1141 return get(BB->getParent(), BB);
1144 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1146 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1148 BA = new BlockAddress(F, BB);
1150 assert(BA->getFunction() == F && "Basic block moved between functions");
1154 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1155 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1159 BB->AdjustBlockAddressRefCount(1);
1163 // destroyConstant - Remove the constant from the constant table.
1165 void BlockAddress::destroyConstant() {
1166 getFunction()->getType()->getContext().pImpl
1167 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1168 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1169 destroyConstantImpl();
1172 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1173 // This could be replacing either the Basic Block or the Function. In either
1174 // case, we have to remove the map entry.
1175 Function *NewF = getFunction();
1176 BasicBlock *NewBB = getBasicBlock();
1179 NewF = cast<Function>(To);
1181 NewBB = cast<BasicBlock>(To);
1183 // See if the 'new' entry already exists, if not, just update this in place
1184 // and return early.
1185 BlockAddress *&NewBA =
1186 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1188 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1190 // Remove the old entry, this can't cause the map to rehash (just a
1191 // tombstone will get added).
1192 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1195 setOperand(0, NewF);
1196 setOperand(1, NewBB);
1197 getBasicBlock()->AdjustBlockAddressRefCount(1);
1201 // Otherwise, I do need to replace this with an existing value.
1202 assert(NewBA != this && "I didn't contain From!");
1204 // Everyone using this now uses the replacement.
1205 uncheckedReplaceAllUsesWith(NewBA);
1210 //---- ConstantExpr::get() implementations.
1213 /// This is a utility function to handle folding of casts and lookup of the
1214 /// cast in the ExprConstants map. It is used by the various get* methods below.
1215 static inline Constant *getFoldedCast(
1216 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1217 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1218 // Fold a few common cases
1219 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1222 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1224 // Look up the constant in the table first to ensure uniqueness
1225 std::vector<Constant*> argVec(1, C);
1226 ExprMapKeyType Key(opc, argVec);
1228 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1231 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1232 Instruction::CastOps opc = Instruction::CastOps(oc);
1233 assert(Instruction::isCast(opc) && "opcode out of range");
1234 assert(C && Ty && "Null arguments to getCast");
1235 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1239 llvm_unreachable("Invalid cast opcode");
1241 case Instruction::Trunc: return getTrunc(C, Ty);
1242 case Instruction::ZExt: return getZExt(C, Ty);
1243 case Instruction::SExt: return getSExt(C, Ty);
1244 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1245 case Instruction::FPExt: return getFPExtend(C, Ty);
1246 case Instruction::UIToFP: return getUIToFP(C, Ty);
1247 case Instruction::SIToFP: return getSIToFP(C, Ty);
1248 case Instruction::FPToUI: return getFPToUI(C, Ty);
1249 case Instruction::FPToSI: return getFPToSI(C, Ty);
1250 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1251 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1252 case Instruction::BitCast: return getBitCast(C, Ty);
1257 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1258 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1259 return getBitCast(C, Ty);
1260 return getZExt(C, Ty);
1263 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1264 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1265 return getBitCast(C, Ty);
1266 return getSExt(C, Ty);
1269 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1270 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1271 return getBitCast(C, Ty);
1272 return getTrunc(C, Ty);
1275 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1276 assert(S->getType()->isPointerTy() && "Invalid cast");
1277 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1279 if (Ty->isIntegerTy())
1280 return getPtrToInt(S, Ty);
1281 return getBitCast(S, Ty);
1284 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1286 assert(C->getType()->isIntOrIntVectorTy() &&
1287 Ty->isIntOrIntVectorTy() && "Invalid cast");
1288 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1289 unsigned DstBits = Ty->getScalarSizeInBits();
1290 Instruction::CastOps opcode =
1291 (SrcBits == DstBits ? Instruction::BitCast :
1292 (SrcBits > DstBits ? Instruction::Trunc :
1293 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1294 return getCast(opcode, C, Ty);
1297 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1298 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1300 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1301 unsigned DstBits = Ty->getScalarSizeInBits();
1302 if (SrcBits == DstBits)
1303 return C; // Avoid a useless cast
1304 Instruction::CastOps opcode =
1305 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1306 return getCast(opcode, C, Ty);
1309 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1311 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1312 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1314 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1315 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1316 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1317 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1318 "SrcTy must be larger than DestTy for Trunc!");
1320 return getFoldedCast(Instruction::Trunc, C, Ty);
1323 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1325 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1326 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1328 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1329 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1330 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1331 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1332 "SrcTy must be smaller than DestTy for SExt!");
1334 return getFoldedCast(Instruction::SExt, C, Ty);
1337 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1339 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1340 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1342 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1343 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1344 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1345 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1346 "SrcTy must be smaller than DestTy for ZExt!");
1348 return getFoldedCast(Instruction::ZExt, C, Ty);
1351 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1353 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1354 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1356 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1357 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1358 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1359 "This is an illegal floating point truncation!");
1360 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1363 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1365 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1366 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1368 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1369 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1370 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1371 "This is an illegal floating point extension!");
1372 return getFoldedCast(Instruction::FPExt, C, Ty);
1375 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1377 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1378 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1380 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1381 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1382 "This is an illegal uint to floating point cast!");
1383 return getFoldedCast(Instruction::UIToFP, C, Ty);
1386 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1388 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1389 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1391 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1392 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1393 "This is an illegal sint to floating point cast!");
1394 return getFoldedCast(Instruction::SIToFP, C, Ty);
1397 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1399 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1400 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1402 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1403 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1404 "This is an illegal floating point to uint cast!");
1405 return getFoldedCast(Instruction::FPToUI, C, Ty);
1408 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1410 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1411 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1413 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1414 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1415 "This is an illegal floating point to sint cast!");
1416 return getFoldedCast(Instruction::FPToSI, C, Ty);
1419 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1420 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1421 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1422 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1425 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1426 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1427 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1428 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1431 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1432 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1433 "Invalid constantexpr bitcast!");
1435 // It is common to ask for a bitcast of a value to its own type, handle this
1437 if (C->getType() == DstTy) return C;
1439 return getFoldedCast(Instruction::BitCast, C, DstTy);
1442 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1444 // Check the operands for consistency first.
1445 assert(Opcode >= Instruction::BinaryOpsBegin &&
1446 Opcode < Instruction::BinaryOpsEnd &&
1447 "Invalid opcode in binary constant expression");
1448 assert(C1->getType() == C2->getType() &&
1449 "Operand types in binary constant expression should match");
1453 case Instruction::Add:
1454 case Instruction::Sub:
1455 case Instruction::Mul:
1456 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1457 assert(C1->getType()->isIntOrIntVectorTy() &&
1458 "Tried to create an integer operation on a non-integer type!");
1460 case Instruction::FAdd:
1461 case Instruction::FSub:
1462 case Instruction::FMul:
1463 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1464 assert(C1->getType()->isFPOrFPVectorTy() &&
1465 "Tried to create a floating-point operation on a "
1466 "non-floating-point type!");
1468 case Instruction::UDiv:
1469 case Instruction::SDiv:
1470 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1471 assert(C1->getType()->isIntOrIntVectorTy() &&
1472 "Tried to create an arithmetic operation on a non-arithmetic type!");
1474 case Instruction::FDiv:
1475 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1476 assert(C1->getType()->isFPOrFPVectorTy() &&
1477 "Tried to create an arithmetic operation on a non-arithmetic type!");
1479 case Instruction::URem:
1480 case Instruction::SRem:
1481 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1482 assert(C1->getType()->isIntOrIntVectorTy() &&
1483 "Tried to create an arithmetic operation on a non-arithmetic type!");
1485 case Instruction::FRem:
1486 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1487 assert(C1->getType()->isFPOrFPVectorTy() &&
1488 "Tried to create an arithmetic operation on a non-arithmetic type!");
1490 case Instruction::And:
1491 case Instruction::Or:
1492 case Instruction::Xor:
1493 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1494 assert(C1->getType()->isIntOrIntVectorTy() &&
1495 "Tried to create a logical operation on a non-integral type!");
1497 case Instruction::Shl:
1498 case Instruction::LShr:
1499 case Instruction::AShr:
1500 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1501 assert(C1->getType()->isIntOrIntVectorTy() &&
1502 "Tried to create a shift operation on a non-integer type!");
1509 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1510 return FC; // Fold a few common cases.
1512 std::vector<Constant*> argVec(1, C1);
1513 argVec.push_back(C2);
1514 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1516 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1517 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1520 Constant *ConstantExpr::getSizeOf(const Type* Ty) {
1521 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1522 // Note that a non-inbounds gep is used, as null isn't within any object.
1523 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1524 Constant *GEP = getGetElementPtr(
1525 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1526 return getPtrToInt(GEP,
1527 Type::getInt64Ty(Ty->getContext()));
1530 Constant *ConstantExpr::getAlignOf(const Type* Ty) {
1531 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1532 // Note that a non-inbounds gep is used, as null isn't within any object.
1533 const Type *AligningTy =
1534 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1535 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1536 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1537 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1538 Constant *Indices[2] = { Zero, One };
1539 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1540 return getPtrToInt(GEP,
1541 Type::getInt64Ty(Ty->getContext()));
1544 Constant *ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1545 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1549 Constant *ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
1550 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1551 // Note that a non-inbounds gep is used, as null isn't within any object.
1552 Constant *GEPIdx[] = {
1553 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1556 Constant *GEP = getGetElementPtr(
1557 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1558 return getPtrToInt(GEP,
1559 Type::getInt64Ty(Ty->getContext()));
1562 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1563 Constant *C1, Constant *C2) {
1564 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1566 switch (Predicate) {
1567 default: llvm_unreachable("Invalid CmpInst predicate");
1568 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1569 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1570 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1571 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1572 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1573 case CmpInst::FCMP_TRUE:
1574 return getFCmp(Predicate, C1, C2);
1576 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1577 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1578 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1579 case CmpInst::ICMP_SLE:
1580 return getICmp(Predicate, C1, C2);
1584 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1585 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1587 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1588 return SC; // Fold common cases
1590 std::vector<Constant*> argVec(3, C);
1593 ExprMapKeyType Key(Instruction::Select, argVec);
1595 LLVMContextImpl *pImpl = C->getContext().pImpl;
1596 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1599 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1600 unsigned NumIdx, bool InBounds) {
1601 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs, NumIdx))
1602 return FC; // Fold a few common cases.
1604 // Get the result type of the getelementptr!
1606 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1607 assert(Ty && "GEP indices invalid!");
1608 unsigned AS = cast<PointerType>(C->getType())->getAddressSpace();
1609 Type *ReqTy = Ty->getPointerTo(AS);
1611 assert(C->getType()->isPointerTy() &&
1612 "Non-pointer type for constant GetElementPtr expression");
1613 // Look up the constant in the table first to ensure uniqueness
1614 std::vector<Constant*> ArgVec;
1615 ArgVec.reserve(NumIdx+1);
1616 ArgVec.push_back(C);
1617 for (unsigned i = 0; i != NumIdx; ++i)
1618 ArgVec.push_back(cast<Constant>(Idxs[i]));
1619 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1620 InBounds ? GEPOperator::IsInBounds : 0);
1622 LLVMContextImpl *pImpl = C->getContext().pImpl;
1623 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1627 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1628 assert(LHS->getType() == RHS->getType());
1629 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1630 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1632 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1633 return FC; // Fold a few common cases...
1635 // Look up the constant in the table first to ensure uniqueness
1636 std::vector<Constant*> ArgVec;
1637 ArgVec.push_back(LHS);
1638 ArgVec.push_back(RHS);
1639 // Get the key type with both the opcode and predicate
1640 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1642 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1643 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1644 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1646 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1647 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1651 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1652 assert(LHS->getType() == RHS->getType());
1653 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1655 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1656 return FC; // Fold a few common cases...
1658 // Look up the constant in the table first to ensure uniqueness
1659 std::vector<Constant*> ArgVec;
1660 ArgVec.push_back(LHS);
1661 ArgVec.push_back(RHS);
1662 // Get the key type with both the opcode and predicate
1663 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1665 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1666 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1667 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1669 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1670 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1673 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1674 assert(Val->getType()->isVectorTy() &&
1675 "Tried to create extractelement operation on non-vector type!");
1676 assert(Idx->getType()->isIntegerTy(32) &&
1677 "Extractelement index must be i32 type!");
1679 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1680 return FC; // Fold a few common cases.
1682 // Look up the constant in the table first to ensure uniqueness
1683 std::vector<Constant*> ArgVec(1, Val);
1684 ArgVec.push_back(Idx);
1685 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1687 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1688 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
1689 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1692 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1694 assert(Val->getType()->isVectorTy() &&
1695 "Tried to create insertelement operation on non-vector type!");
1696 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1697 && "Insertelement types must match!");
1698 assert(Idx->getType()->isIntegerTy(32) &&
1699 "Insertelement index must be i32 type!");
1701 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1702 return FC; // Fold a few common cases.
1703 // Look up the constant in the table first to ensure uniqueness
1704 std::vector<Constant*> ArgVec(1, Val);
1705 ArgVec.push_back(Elt);
1706 ArgVec.push_back(Idx);
1707 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1709 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1710 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1713 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1715 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1716 "Invalid shuffle vector constant expr operands!");
1718 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1719 return FC; // Fold a few common cases.
1721 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1722 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1723 const Type *ShufTy = VectorType::get(EltTy, NElts);
1725 // Look up the constant in the table first to ensure uniqueness
1726 std::vector<Constant*> ArgVec(1, V1);
1727 ArgVec.push_back(V2);
1728 ArgVec.push_back(Mask);
1729 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1731 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1732 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1735 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1736 ArrayRef<unsigned> Idxs) {
1737 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1738 Idxs) == Val->getType() &&
1739 "insertvalue indices invalid!");
1740 assert(Agg->getType()->isFirstClassType() &&
1741 "Non-first-class type for constant insertvalue expression");
1742 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1743 assert(FC && "insertvalue constant expr couldn't be folded!");
1747 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1748 ArrayRef<unsigned> Idxs) {
1749 assert(Agg->getType()->isFirstClassType() &&
1750 "Tried to create extractelement operation on non-first-class type!");
1752 const Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1754 assert(ReqTy && "extractvalue indices invalid!");
1756 assert(Agg->getType()->isFirstClassType() &&
1757 "Non-first-class type for constant extractvalue expression");
1758 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1759 assert(FC && "ExtractValue constant expr couldn't be folded!");
1763 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1764 assert(C->getType()->isIntOrIntVectorTy() &&
1765 "Cannot NEG a nonintegral value!");
1766 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1770 Constant *ConstantExpr::getFNeg(Constant *C) {
1771 assert(C->getType()->isFPOrFPVectorTy() &&
1772 "Cannot FNEG a non-floating-point value!");
1773 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1776 Constant *ConstantExpr::getNot(Constant *C) {
1777 assert(C->getType()->isIntOrIntVectorTy() &&
1778 "Cannot NOT a nonintegral value!");
1779 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1782 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1783 bool HasNUW, bool HasNSW) {
1784 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1785 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1786 return get(Instruction::Add, C1, C2, Flags);
1789 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1790 return get(Instruction::FAdd, C1, C2);
1793 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1794 bool HasNUW, bool HasNSW) {
1795 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1796 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1797 return get(Instruction::Sub, C1, C2, Flags);
1800 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1801 return get(Instruction::FSub, C1, C2);
1804 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1805 bool HasNUW, bool HasNSW) {
1806 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1807 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1808 return get(Instruction::Mul, C1, C2, Flags);
1811 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1812 return get(Instruction::FMul, C1, C2);
1815 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1816 return get(Instruction::UDiv, C1, C2,
1817 isExact ? PossiblyExactOperator::IsExact : 0);
1820 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1821 return get(Instruction::SDiv, C1, C2,
1822 isExact ? PossiblyExactOperator::IsExact : 0);
1825 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1826 return get(Instruction::FDiv, C1, C2);
1829 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1830 return get(Instruction::URem, C1, C2);
1833 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1834 return get(Instruction::SRem, C1, C2);
1837 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1838 return get(Instruction::FRem, C1, C2);
1841 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1842 return get(Instruction::And, C1, C2);
1845 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1846 return get(Instruction::Or, C1, C2);
1849 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1850 return get(Instruction::Xor, C1, C2);
1853 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1854 bool HasNUW, bool HasNSW) {
1855 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1856 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1857 return get(Instruction::Shl, C1, C2, Flags);
1860 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1861 return get(Instruction::LShr, C1, C2,
1862 isExact ? PossiblyExactOperator::IsExact : 0);
1865 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1866 return get(Instruction::AShr, C1, C2,
1867 isExact ? PossiblyExactOperator::IsExact : 0);
1870 // destroyConstant - Remove the constant from the constant table...
1872 void ConstantExpr::destroyConstant() {
1873 getType()->getContext().pImpl->ExprConstants.remove(this);
1874 destroyConstantImpl();
1877 const char *ConstantExpr::getOpcodeName() const {
1878 return Instruction::getOpcodeName(getOpcode());
1883 GetElementPtrConstantExpr::
1884 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1886 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1887 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1888 - (IdxList.size()+1), IdxList.size()+1) {
1890 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1891 OperandList[i+1] = IdxList[i];
1895 //===----------------------------------------------------------------------===//
1896 // replaceUsesOfWithOnConstant implementations
1898 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1899 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1902 /// Note that we intentionally replace all uses of From with To here. Consider
1903 /// a large array that uses 'From' 1000 times. By handling this case all here,
1904 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1905 /// single invocation handles all 1000 uses. Handling them one at a time would
1906 /// work, but would be really slow because it would have to unique each updated
1909 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1911 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1912 Constant *ToC = cast<Constant>(To);
1914 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1916 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1917 Lookup.first.first = cast<ArrayType>(getType());
1918 Lookup.second = this;
1920 std::vector<Constant*> &Values = Lookup.first.second;
1921 Values.reserve(getNumOperands()); // Build replacement array.
1923 // Fill values with the modified operands of the constant array. Also,
1924 // compute whether this turns into an all-zeros array.
1925 bool isAllZeros = false;
1926 unsigned NumUpdated = 0;
1927 if (!ToC->isNullValue()) {
1928 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1929 Constant *Val = cast<Constant>(O->get());
1934 Values.push_back(Val);
1938 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1939 Constant *Val = cast<Constant>(O->get());
1944 Values.push_back(Val);
1945 if (isAllZeros) isAllZeros = Val->isNullValue();
1949 Constant *Replacement = 0;
1951 Replacement = ConstantAggregateZero::get(getType());
1953 // Check to see if we have this array type already.
1955 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1956 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1959 Replacement = I->second;
1961 // Okay, the new shape doesn't exist in the system yet. Instead of
1962 // creating a new constant array, inserting it, replaceallusesof'ing the
1963 // old with the new, then deleting the old... just update the current one
1965 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1967 // Update to the new value. Optimize for the case when we have a single
1968 // operand that we're changing, but handle bulk updates efficiently.
1969 if (NumUpdated == 1) {
1970 unsigned OperandToUpdate = U - OperandList;
1971 assert(getOperand(OperandToUpdate) == From &&
1972 "ReplaceAllUsesWith broken!");
1973 setOperand(OperandToUpdate, ToC);
1975 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1976 if (getOperand(i) == From)
1983 // Otherwise, I do need to replace this with an existing value.
1984 assert(Replacement != this && "I didn't contain From!");
1986 // Everyone using this now uses the replacement.
1987 uncheckedReplaceAllUsesWith(Replacement);
1989 // Delete the old constant!
1993 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1995 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1996 Constant *ToC = cast<Constant>(To);
1998 unsigned OperandToUpdate = U-OperandList;
1999 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2001 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2002 Lookup.first.first = cast<StructType>(getType());
2003 Lookup.second = this;
2004 std::vector<Constant*> &Values = Lookup.first.second;
2005 Values.reserve(getNumOperands()); // Build replacement struct.
2008 // Fill values with the modified operands of the constant struct. Also,
2009 // compute whether this turns into an all-zeros struct.
2010 bool isAllZeros = false;
2011 if (!ToC->isNullValue()) {
2012 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2013 Values.push_back(cast<Constant>(O->get()));
2016 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2017 Constant *Val = cast<Constant>(O->get());
2018 Values.push_back(Val);
2019 if (isAllZeros) isAllZeros = Val->isNullValue();
2022 Values[OperandToUpdate] = ToC;
2024 LLVMContextImpl *pImpl = getContext().pImpl;
2026 Constant *Replacement = 0;
2028 Replacement = ConstantAggregateZero::get(getType());
2030 // Check to see if we have this struct type already.
2032 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2033 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2036 Replacement = I->second;
2038 // Okay, the new shape doesn't exist in the system yet. Instead of
2039 // creating a new constant struct, inserting it, replaceallusesof'ing the
2040 // old with the new, then deleting the old... just update the current one
2042 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2044 // Update to the new value.
2045 setOperand(OperandToUpdate, ToC);
2050 assert(Replacement != this && "I didn't contain From!");
2052 // Everyone using this now uses the replacement.
2053 uncheckedReplaceAllUsesWith(Replacement);
2055 // Delete the old constant!
2059 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2061 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2063 std::vector<Constant*> Values;
2064 Values.reserve(getNumOperands()); // Build replacement array...
2065 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2066 Constant *Val = getOperand(i);
2067 if (Val == From) Val = cast<Constant>(To);
2068 Values.push_back(Val);
2071 Constant *Replacement = get(Values);
2072 assert(Replacement != this && "I didn't contain From!");
2074 // Everyone using this now uses the replacement.
2075 uncheckedReplaceAllUsesWith(Replacement);
2077 // Delete the old constant!
2081 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2083 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2084 Constant *To = cast<Constant>(ToV);
2086 Constant *Replacement = 0;
2087 if (getOpcode() == Instruction::GetElementPtr) {
2088 SmallVector<Constant*, 8> Indices;
2089 Constant *Pointer = getOperand(0);
2090 Indices.reserve(getNumOperands()-1);
2091 if (Pointer == From) Pointer = To;
2093 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2094 Constant *Val = getOperand(i);
2095 if (Val == From) Val = To;
2096 Indices.push_back(Val);
2098 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2099 &Indices[0], Indices.size(),
2100 cast<GEPOperator>(this)->isInBounds());
2101 } else if (getOpcode() == Instruction::ExtractValue) {
2102 Constant *Agg = getOperand(0);
2103 if (Agg == From) Agg = To;
2105 ArrayRef<unsigned> Indices = getIndices();
2106 Replacement = ConstantExpr::getExtractValue(Agg, Indices);
2107 } else if (getOpcode() == Instruction::InsertValue) {
2108 Constant *Agg = getOperand(0);
2109 Constant *Val = getOperand(1);
2110 if (Agg == From) Agg = To;
2111 if (Val == From) Val = To;
2113 ArrayRef<unsigned> Indices = getIndices();
2114 Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices);
2115 } else if (isCast()) {
2116 assert(getOperand(0) == From && "Cast only has one use!");
2117 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2118 } else if (getOpcode() == Instruction::Select) {
2119 Constant *C1 = getOperand(0);
2120 Constant *C2 = getOperand(1);
2121 Constant *C3 = getOperand(2);
2122 if (C1 == From) C1 = To;
2123 if (C2 == From) C2 = To;
2124 if (C3 == From) C3 = To;
2125 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2126 } else if (getOpcode() == Instruction::ExtractElement) {
2127 Constant *C1 = getOperand(0);
2128 Constant *C2 = getOperand(1);
2129 if (C1 == From) C1 = To;
2130 if (C2 == From) C2 = To;
2131 Replacement = ConstantExpr::getExtractElement(C1, C2);
2132 } else if (getOpcode() == Instruction::InsertElement) {
2133 Constant *C1 = getOperand(0);
2134 Constant *C2 = getOperand(1);
2135 Constant *C3 = getOperand(1);
2136 if (C1 == From) C1 = To;
2137 if (C2 == From) C2 = To;
2138 if (C3 == From) C3 = To;
2139 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2140 } else if (getOpcode() == Instruction::ShuffleVector) {
2141 Constant *C1 = getOperand(0);
2142 Constant *C2 = getOperand(1);
2143 Constant *C3 = getOperand(2);
2144 if (C1 == From) C1 = To;
2145 if (C2 == From) C2 = To;
2146 if (C3 == From) C3 = To;
2147 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2148 } else if (isCompare()) {
2149 Constant *C1 = getOperand(0);
2150 Constant *C2 = getOperand(1);
2151 if (C1 == From) C1 = To;
2152 if (C2 == From) C2 = To;
2153 if (getOpcode() == Instruction::ICmp)
2154 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2156 assert(getOpcode() == Instruction::FCmp);
2157 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2159 } else if (getNumOperands() == 2) {
2160 Constant *C1 = getOperand(0);
2161 Constant *C2 = getOperand(1);
2162 if (C1 == From) C1 = To;
2163 if (C2 == From) C2 = To;
2164 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2166 llvm_unreachable("Unknown ConstantExpr type!");
2170 assert(Replacement != this && "I didn't contain From!");
2172 // Everyone using this now uses the replacement.
2173 uncheckedReplaceAllUsesWith(Replacement);
2175 // Delete the old constant!