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 // Constructor to create a '0' constant of arbitrary type...
53 Constant *Constant::getNullValue(const Type *Ty) {
54 switch (Ty->getTypeID()) {
55 case Type::IntegerTyID:
56 return ConstantInt::get(Ty, 0);
58 return ConstantFP::get(Ty->getContext(),
59 APFloat::getZero(APFloat::IEEEsingle));
60 case Type::DoubleTyID:
61 return ConstantFP::get(Ty->getContext(),
62 APFloat::getZero(APFloat::IEEEdouble));
63 case Type::X86_FP80TyID:
64 return ConstantFP::get(Ty->getContext(),
65 APFloat::getZero(APFloat::x87DoubleExtended));
67 return ConstantFP::get(Ty->getContext(),
68 APFloat::getZero(APFloat::IEEEquad));
69 case Type::PPC_FP128TyID:
70 return ConstantFP::get(Ty->getContext(),
71 APFloat(APInt::getNullValue(128)));
72 case Type::PointerTyID:
73 return ConstantPointerNull::get(cast<PointerType>(Ty));
74 case Type::StructTyID:
76 case Type::VectorTyID:
77 return ConstantAggregateZero::get(Ty);
79 // Function, Label, or Opaque type?
80 assert(!"Cannot create a null constant of that type!");
85 Constant *Constant::getIntegerValue(const Type *Ty, const APInt &V) {
86 const Type *ScalarTy = Ty->getScalarType();
88 // Create the base integer constant.
89 Constant *C = ConstantInt::get(Ty->getContext(), V);
91 // Convert an integer to a pointer, if necessary.
92 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
93 C = ConstantExpr::getIntToPtr(C, PTy);
95 // Broadcast a scalar to a vector, if necessary.
96 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
97 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
102 Constant *Constant::getAllOnesValue(const Type *Ty) {
103 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
104 return ConstantInt::get(Ty->getContext(),
105 APInt::getAllOnesValue(ITy->getBitWidth()));
107 if (Ty->isFloatingPointTy()) {
108 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
109 !Ty->isPPC_FP128Ty());
110 return ConstantFP::get(Ty->getContext(), FL);
113 SmallVector<Constant*, 16> Elts;
114 const VectorType *VTy = cast<VectorType>(Ty);
115 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
116 assert(Elts[0] && "Not a vector integer type!");
117 return cast<ConstantVector>(ConstantVector::get(Elts));
120 void Constant::destroyConstantImpl() {
121 // When a Constant is destroyed, there may be lingering
122 // references to the constant by other constants in the constant pool. These
123 // constants are implicitly dependent on the module that is being deleted,
124 // but they don't know that. Because we only find out when the CPV is
125 // deleted, we must now notify all of our users (that should only be
126 // Constants) that they are, in fact, invalid now and should be deleted.
128 while (!use_empty()) {
129 Value *V = use_back();
130 #ifndef NDEBUG // Only in -g mode...
131 if (!isa<Constant>(V)) {
132 dbgs() << "While deleting: " << *this
133 << "\n\nUse still stuck around after Def is destroyed: "
137 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
138 Constant *CV = cast<Constant>(V);
139 CV->destroyConstant();
141 // The constant should remove itself from our use list...
142 assert((use_empty() || use_back() != V) && "Constant not removed!");
145 // Value has no outstanding references it is safe to delete it now...
149 /// canTrap - Return true if evaluation of this constant could trap. This is
150 /// true for things like constant expressions that could divide by zero.
151 bool Constant::canTrap() const {
152 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
153 // The only thing that could possibly trap are constant exprs.
154 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
155 if (!CE) return false;
157 // ConstantExpr traps if any operands can trap.
158 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
159 if (CE->getOperand(i)->canTrap())
162 // Otherwise, only specific operations can trap.
163 switch (CE->getOpcode()) {
166 case Instruction::UDiv:
167 case Instruction::SDiv:
168 case Instruction::FDiv:
169 case Instruction::URem:
170 case Instruction::SRem:
171 case Instruction::FRem:
172 // Div and rem can trap if the RHS is not known to be non-zero.
173 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
179 /// isConstantUsed - Return true if the constant has users other than constant
180 /// exprs and other dangling things.
181 bool Constant::isConstantUsed() const {
182 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
183 const Constant *UC = dyn_cast<Constant>(*UI);
184 if (UC == 0 || isa<GlobalValue>(UC))
187 if (UC->isConstantUsed())
195 /// getRelocationInfo - This method classifies the entry according to
196 /// whether or not it may generate a relocation entry. This must be
197 /// conservative, so if it might codegen to a relocatable entry, it should say
198 /// so. The return values are:
200 /// NoRelocation: This constant pool entry is guaranteed to never have a
201 /// relocation applied to it (because it holds a simple constant like
203 /// LocalRelocation: This entry has relocations, but the entries are
204 /// guaranteed to be resolvable by the static linker, so the dynamic
205 /// linker will never see them.
206 /// GlobalRelocations: This entry may have arbitrary relocations.
208 /// FIXME: This really should not be in VMCore.
209 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
210 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
211 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
212 return LocalRelocation; // Local to this file/library.
213 return GlobalRelocations; // Global reference.
216 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
217 return BA->getFunction()->getRelocationInfo();
219 // While raw uses of blockaddress need to be relocated, differences between
220 // two of them don't when they are for labels in the same function. This is a
221 // common idiom when creating a table for the indirect goto extension, so we
222 // handle it efficiently here.
223 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
224 if (CE->getOpcode() == Instruction::Sub) {
225 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
226 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
228 LHS->getOpcode() == Instruction::PtrToInt &&
229 RHS->getOpcode() == Instruction::PtrToInt &&
230 isa<BlockAddress>(LHS->getOperand(0)) &&
231 isa<BlockAddress>(RHS->getOperand(0)) &&
232 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
233 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
237 PossibleRelocationsTy Result = NoRelocation;
238 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
239 Result = std::max(Result,
240 cast<Constant>(getOperand(i))->getRelocationInfo());
246 /// getVectorElements - This method, which is only valid on constant of vector
247 /// type, returns the elements of the vector in the specified smallvector.
248 /// This handles breaking down a vector undef into undef elements, etc. For
249 /// constant exprs and other cases we can't handle, we return an empty vector.
250 void Constant::getVectorElements(SmallVectorImpl<Constant*> &Elts) const {
251 assert(getType()->isVectorTy() && "Not a vector constant!");
253 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
254 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
255 Elts.push_back(CV->getOperand(i));
259 const VectorType *VT = cast<VectorType>(getType());
260 if (isa<ConstantAggregateZero>(this)) {
261 Elts.assign(VT->getNumElements(),
262 Constant::getNullValue(VT->getElementType()));
266 if (isa<UndefValue>(this)) {
267 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
271 // Unknown type, must be constant expr etc.
275 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
276 /// it. This involves recursively eliminating any dead users of the
278 static bool removeDeadUsersOfConstant(const Constant *C) {
279 if (isa<GlobalValue>(C)) return false; // Cannot remove this
281 while (!C->use_empty()) {
282 const Constant *User = dyn_cast<Constant>(C->use_back());
283 if (!User) return false; // Non-constant usage;
284 if (!removeDeadUsersOfConstant(User))
285 return false; // Constant wasn't dead
288 const_cast<Constant*>(C)->destroyConstant();
293 /// removeDeadConstantUsers - If there are any dead constant users dangling
294 /// off of this constant, remove them. This method is useful for clients
295 /// that want to check to see if a global is unused, but don't want to deal
296 /// with potentially dead constants hanging off of the globals.
297 void Constant::removeDeadConstantUsers() const {
298 Value::const_use_iterator I = use_begin(), E = use_end();
299 Value::const_use_iterator LastNonDeadUser = E;
301 const Constant *User = dyn_cast<Constant>(*I);
308 if (!removeDeadUsersOfConstant(User)) {
309 // If the constant wasn't dead, remember that this was the last live use
310 // and move on to the next constant.
316 // If the constant was dead, then the iterator is invalidated.
317 if (LastNonDeadUser == E) {
329 //===----------------------------------------------------------------------===//
331 //===----------------------------------------------------------------------===//
333 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
334 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
335 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
338 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
339 LLVMContextImpl *pImpl = Context.pImpl;
340 if (!pImpl->TheTrueVal)
341 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
342 return pImpl->TheTrueVal;
345 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
346 LLVMContextImpl *pImpl = Context.pImpl;
347 if (!pImpl->TheFalseVal)
348 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
349 return pImpl->TheFalseVal;
352 Constant *ConstantInt::getTrue(const Type *Ty) {
353 const VectorType *VTy = dyn_cast<VectorType>(Ty);
355 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
356 return ConstantInt::getTrue(Ty->getContext());
358 assert(VTy->getElementType()->isIntegerTy(1) &&
359 "True must be vector of i1 or i1.");
360 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
361 ConstantInt::getTrue(Ty->getContext()));
362 return ConstantVector::get(Splat);
365 Constant *ConstantInt::getFalse(const Type *Ty) {
366 const VectorType *VTy = dyn_cast<VectorType>(Ty);
368 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
369 return ConstantInt::getFalse(Ty->getContext());
371 assert(VTy->getElementType()->isIntegerTy(1) &&
372 "False must be vector of i1 or i1.");
373 SmallVector<Constant*, 16> Splat(VTy->getNumElements(),
374 ConstantInt::getFalse(Ty->getContext()));
375 return ConstantVector::get(Splat);
379 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
380 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
381 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
382 // compare APInt's of different widths, which would violate an APInt class
383 // invariant which generates an assertion.
384 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
385 // Get the corresponding integer type for the bit width of the value.
386 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
387 // get an existing value or the insertion position
388 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
389 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
390 if (!Slot) Slot = new ConstantInt(ITy, V);
394 Constant *ConstantInt::get(const Type *Ty, uint64_t V, bool isSigned) {
395 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
397 // For vectors, broadcast the value.
398 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
399 return ConstantVector::get(SmallVector<Constant*,
400 16>(VTy->getNumElements(), C));
405 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
407 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
410 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
411 return get(Ty, V, true);
414 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
415 return get(Ty, V, true);
418 Constant *ConstantInt::get(const Type* Ty, const APInt& V) {
419 ConstantInt *C = get(Ty->getContext(), V);
420 assert(C->getType() == Ty->getScalarType() &&
421 "ConstantInt type doesn't match the type implied by its value!");
423 // For vectors, broadcast the value.
424 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
425 return ConstantVector::get(
426 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
431 ConstantInt* ConstantInt::get(const IntegerType* Ty, StringRef Str,
433 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
436 //===----------------------------------------------------------------------===//
438 //===----------------------------------------------------------------------===//
440 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
442 return &APFloat::IEEEsingle;
443 if (Ty->isDoubleTy())
444 return &APFloat::IEEEdouble;
445 if (Ty->isX86_FP80Ty())
446 return &APFloat::x87DoubleExtended;
447 else if (Ty->isFP128Ty())
448 return &APFloat::IEEEquad;
450 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
451 return &APFloat::PPCDoubleDouble;
454 /// get() - This returns a constant fp for the specified value in the
455 /// specified type. This should only be used for simple constant values like
456 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
457 Constant *ConstantFP::get(const Type* Ty, double V) {
458 LLVMContext &Context = Ty->getContext();
462 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
463 APFloat::rmNearestTiesToEven, &ignored);
464 Constant *C = get(Context, FV);
466 // For vectors, broadcast the value.
467 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
468 return ConstantVector::get(
469 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
475 Constant *ConstantFP::get(const Type* Ty, StringRef Str) {
476 LLVMContext &Context = Ty->getContext();
478 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
479 Constant *C = get(Context, FV);
481 // For vectors, broadcast the value.
482 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
483 return ConstantVector::get(
484 SmallVector<Constant *, 16>(VTy->getNumElements(), C));
490 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
491 LLVMContext &Context = Ty->getContext();
492 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
494 return get(Context, apf);
498 Constant *ConstantFP::getZeroValueForNegation(const Type* Ty) {
499 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
500 if (PTy->getElementType()->isFloatingPointTy()) {
501 SmallVector<Constant*, 16> zeros(PTy->getNumElements(),
502 getNegativeZero(PTy->getElementType()));
503 return ConstantVector::get(zeros);
506 if (Ty->isFloatingPointTy())
507 return getNegativeZero(Ty);
509 return Constant::getNullValue(Ty);
513 // ConstantFP accessors.
514 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
515 DenseMapAPFloatKeyInfo::KeyTy Key(V);
517 LLVMContextImpl* pImpl = Context.pImpl;
519 ConstantFP *&Slot = pImpl->FPConstants[Key];
523 if (&V.getSemantics() == &APFloat::IEEEsingle)
524 Ty = Type::getFloatTy(Context);
525 else if (&V.getSemantics() == &APFloat::IEEEdouble)
526 Ty = Type::getDoubleTy(Context);
527 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
528 Ty = Type::getX86_FP80Ty(Context);
529 else if (&V.getSemantics() == &APFloat::IEEEquad)
530 Ty = Type::getFP128Ty(Context);
532 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
533 "Unknown FP format");
534 Ty = Type::getPPC_FP128Ty(Context);
536 Slot = new ConstantFP(Ty, V);
542 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
543 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
544 return ConstantFP::get(Ty->getContext(),
545 APFloat::getInf(Semantics, Negative));
548 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
549 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
550 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
554 bool ConstantFP::isNullValue() const {
555 return Val.isZero() && !Val.isNegative();
558 bool ConstantFP::isExactlyValue(const APFloat& V) const {
559 return Val.bitwiseIsEqual(V);
562 //===----------------------------------------------------------------------===//
563 // ConstantXXX Classes
564 //===----------------------------------------------------------------------===//
567 ConstantArray::ConstantArray(const ArrayType *T,
568 const std::vector<Constant*> &V)
569 : Constant(T, ConstantArrayVal,
570 OperandTraits<ConstantArray>::op_end(this) - V.size(),
572 assert(V.size() == T->getNumElements() &&
573 "Invalid initializer vector for constant array");
574 Use *OL = OperandList;
575 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
578 assert(C->getType() == T->getElementType() &&
579 "Initializer for array element doesn't match array element type!");
584 Constant *ConstantArray::get(const ArrayType *Ty, ArrayRef<Constant*> V) {
585 for (unsigned i = 0, e = V.size(); i != e; ++i) {
586 assert(V[i]->getType() == Ty->getElementType() &&
587 "Wrong type in array element initializer");
589 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
590 // If this is an all-zero array, return a ConstantAggregateZero object
593 if (!C->isNullValue())
594 return pImpl->ArrayConstants.getOrCreate(Ty, V);
596 for (unsigned i = 1, e = V.size(); i != e; ++i)
598 return pImpl->ArrayConstants.getOrCreate(Ty, V);
601 return ConstantAggregateZero::get(Ty);
604 /// ConstantArray::get(const string&) - Return an array that is initialized to
605 /// contain the specified string. If length is zero then a null terminator is
606 /// added to the specified string so that it may be used in a natural way.
607 /// Otherwise, the length parameter specifies how much of the string to use
608 /// and it won't be null terminated.
610 Constant *ConstantArray::get(LLVMContext &Context, StringRef Str,
612 std::vector<Constant*> ElementVals;
613 ElementVals.reserve(Str.size() + size_t(AddNull));
614 for (unsigned i = 0; i < Str.size(); ++i)
615 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
617 // Add a null terminator to the string...
619 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
622 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
623 return get(ATy, ElementVals);
626 /// getTypeForElements - Return an anonymous struct type to use for a constant
627 /// with the specified set of elements. The list must not be empty.
628 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
629 ArrayRef<Constant*> V,
631 SmallVector<Type*, 16> EltTypes;
632 for (unsigned i = 0, e = V.size(); i != e; ++i)
633 EltTypes.push_back(V[i]->getType());
635 return StructType::get(Context, EltTypes, Packed);
639 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
642 "ConstantStruct::getTypeForElements cannot be called on empty list");
643 return getTypeForElements(V[0]->getContext(), V, Packed);
647 ConstantStruct::ConstantStruct(const StructType *T,
648 const std::vector<Constant*> &V)
649 : Constant(T, ConstantStructVal,
650 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
652 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
653 "Invalid initializer vector for constant structure");
654 Use *OL = OperandList;
655 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
658 assert((T->isOpaque() || C->getType() == T->getElementType(I-V.begin())) &&
659 "Initializer for struct element doesn't match struct element type!");
664 // ConstantStruct accessors.
665 Constant *ConstantStruct::get(const StructType *ST, ArrayRef<Constant*> V) {
666 // Create a ConstantAggregateZero value if all elements are zeros.
667 for (unsigned i = 0, e = V.size(); i != e; ++i)
668 if (!V[i]->isNullValue())
669 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
671 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
672 "Incorrect # elements specified to ConstantStruct::get");
673 return ConstantAggregateZero::get(ST);
676 Constant* ConstantStruct::get(const StructType *T, ...) {
678 SmallVector<Constant*, 8> Values;
680 while (Constant *Val = va_arg(ap, llvm::Constant*))
681 Values.push_back(Val);
683 return get(T, Values);
686 ConstantVector::ConstantVector(const VectorType *T,
687 const std::vector<Constant*> &V)
688 : Constant(T, ConstantVectorVal,
689 OperandTraits<ConstantVector>::op_end(this) - V.size(),
691 Use *OL = OperandList;
692 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
695 assert(C->getType() == T->getElementType() &&
696 "Initializer for vector element doesn't match vector element type!");
701 // ConstantVector accessors.
702 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
703 assert(!V.empty() && "Vectors can't be empty");
704 const VectorType *T = VectorType::get(V.front()->getType(), V.size());
705 LLVMContextImpl *pImpl = T->getContext().pImpl;
707 // If this is an all-undef or all-zero vector, return a
708 // ConstantAggregateZero or UndefValue.
710 bool isZero = C->isNullValue();
711 bool isUndef = isa<UndefValue>(C);
713 if (isZero || isUndef) {
714 for (unsigned i = 1, e = V.size(); i != e; ++i)
716 isZero = isUndef = false;
722 return ConstantAggregateZero::get(T);
724 return UndefValue::get(T);
726 return pImpl->VectorConstants.getOrCreate(T, V);
729 // Utility function for determining if a ConstantExpr is a CastOp or not. This
730 // can't be inline because we don't want to #include Instruction.h into
732 bool ConstantExpr::isCast() const {
733 return Instruction::isCast(getOpcode());
736 bool ConstantExpr::isCompare() const {
737 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
740 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
741 if (getOpcode() != Instruction::GetElementPtr) return false;
743 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
744 User::const_op_iterator OI = llvm::next(this->op_begin());
746 // Skip the first index, as it has no static limit.
750 // The remaining indices must be compile-time known integers within the
751 // bounds of the corresponding notional static array types.
752 for (; GEPI != E; ++GEPI, ++OI) {
753 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
754 if (!CI) return false;
755 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
756 if (CI->getValue().getActiveBits() > 64 ||
757 CI->getZExtValue() >= ATy->getNumElements())
761 // All the indices checked out.
765 bool ConstantExpr::hasIndices() const {
766 return getOpcode() == Instruction::ExtractValue ||
767 getOpcode() == Instruction::InsertValue;
770 ArrayRef<unsigned> ConstantExpr::getIndices() const {
771 if (const ExtractValueConstantExpr *EVCE =
772 dyn_cast<ExtractValueConstantExpr>(this))
773 return EVCE->Indices;
775 return cast<InsertValueConstantExpr>(this)->Indices;
778 unsigned ConstantExpr::getPredicate() const {
779 assert(getOpcode() == Instruction::FCmp ||
780 getOpcode() == Instruction::ICmp);
781 return ((const CompareConstantExpr*)this)->predicate;
784 /// getWithOperandReplaced - Return a constant expression identical to this
785 /// one, but with the specified operand set to the specified value.
787 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
788 assert(OpNo < getNumOperands() && "Operand num is out of range!");
789 assert(Op->getType() == getOperand(OpNo)->getType() &&
790 "Replacing operand with value of different type!");
791 if (getOperand(OpNo) == Op)
792 return const_cast<ConstantExpr*>(this);
794 Constant *Op0, *Op1, *Op2;
795 switch (getOpcode()) {
796 case Instruction::Trunc:
797 case Instruction::ZExt:
798 case Instruction::SExt:
799 case Instruction::FPTrunc:
800 case Instruction::FPExt:
801 case Instruction::UIToFP:
802 case Instruction::SIToFP:
803 case Instruction::FPToUI:
804 case Instruction::FPToSI:
805 case Instruction::PtrToInt:
806 case Instruction::IntToPtr:
807 case Instruction::BitCast:
808 return ConstantExpr::getCast(getOpcode(), Op, getType());
809 case Instruction::Select:
810 Op0 = (OpNo == 0) ? Op : getOperand(0);
811 Op1 = (OpNo == 1) ? Op : getOperand(1);
812 Op2 = (OpNo == 2) ? Op : getOperand(2);
813 return ConstantExpr::getSelect(Op0, Op1, Op2);
814 case Instruction::InsertElement:
815 Op0 = (OpNo == 0) ? Op : getOperand(0);
816 Op1 = (OpNo == 1) ? Op : getOperand(1);
817 Op2 = (OpNo == 2) ? Op : getOperand(2);
818 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
819 case Instruction::ExtractElement:
820 Op0 = (OpNo == 0) ? Op : getOperand(0);
821 Op1 = (OpNo == 1) ? Op : getOperand(1);
822 return ConstantExpr::getExtractElement(Op0, Op1);
823 case Instruction::ShuffleVector:
824 Op0 = (OpNo == 0) ? Op : getOperand(0);
825 Op1 = (OpNo == 1) ? Op : getOperand(1);
826 Op2 = (OpNo == 2) ? Op : getOperand(2);
827 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
828 case Instruction::GetElementPtr: {
829 SmallVector<Constant*, 8> Ops;
830 Ops.resize(getNumOperands()-1);
831 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
832 Ops[i-1] = getOperand(i);
834 return cast<GEPOperator>(this)->isInBounds() ?
835 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
836 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
838 return cast<GEPOperator>(this)->isInBounds() ?
839 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0],Ops.size()):
840 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
843 assert(getNumOperands() == 2 && "Must be binary operator?");
844 Op0 = (OpNo == 0) ? Op : getOperand(0);
845 Op1 = (OpNo == 1) ? Op : getOperand(1);
846 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassOptionalData);
850 /// getWithOperands - This returns the current constant expression with the
851 /// operands replaced with the specified values. The specified array must
852 /// have the same number of operands as our current one.
853 Constant *ConstantExpr::
854 getWithOperands(ArrayRef<Constant*> Ops, const Type *Ty) const {
855 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
856 bool AnyChange = Ty != getType();
857 for (unsigned i = 0; i != Ops.size(); ++i)
858 AnyChange |= Ops[i] != getOperand(i);
860 if (!AnyChange) // No operands changed, return self.
861 return const_cast<ConstantExpr*>(this);
863 switch (getOpcode()) {
864 case Instruction::Trunc:
865 case Instruction::ZExt:
866 case Instruction::SExt:
867 case Instruction::FPTrunc:
868 case Instruction::FPExt:
869 case Instruction::UIToFP:
870 case Instruction::SIToFP:
871 case Instruction::FPToUI:
872 case Instruction::FPToSI:
873 case Instruction::PtrToInt:
874 case Instruction::IntToPtr:
875 case Instruction::BitCast:
876 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
877 case Instruction::Select:
878 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
879 case Instruction::InsertElement:
880 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
881 case Instruction::ExtractElement:
882 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
883 case Instruction::ShuffleVector:
884 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
885 case Instruction::GetElementPtr:
886 return cast<GEPOperator>(this)->isInBounds() ?
887 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], Ops.size()-1) :
888 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], Ops.size()-1);
889 case Instruction::ICmp:
890 case Instruction::FCmp:
891 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
893 assert(getNumOperands() == 2 && "Must be binary operator?");
894 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
899 //===----------------------------------------------------------------------===//
900 // isValueValidForType implementations
902 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
903 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
904 if (Ty == Type::getInt1Ty(Ty->getContext()))
905 return Val == 0 || Val == 1;
907 return true; // always true, has to fit in largest type
908 uint64_t Max = (1ll << NumBits) - 1;
912 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
913 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
914 if (Ty == Type::getInt1Ty(Ty->getContext()))
915 return Val == 0 || Val == 1 || Val == -1;
917 return true; // always true, has to fit in largest type
918 int64_t Min = -(1ll << (NumBits-1));
919 int64_t Max = (1ll << (NumBits-1)) - 1;
920 return (Val >= Min && Val <= Max);
923 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
924 // convert modifies in place, so make a copy.
925 APFloat Val2 = APFloat(Val);
927 switch (Ty->getTypeID()) {
929 return false; // These can't be represented as floating point!
931 // FIXME rounding mode needs to be more flexible
932 case Type::FloatTyID: {
933 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
935 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
938 case Type::DoubleTyID: {
939 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
940 &Val2.getSemantics() == &APFloat::IEEEdouble)
942 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
945 case Type::X86_FP80TyID:
946 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
947 &Val2.getSemantics() == &APFloat::IEEEdouble ||
948 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
949 case Type::FP128TyID:
950 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
951 &Val2.getSemantics() == &APFloat::IEEEdouble ||
952 &Val2.getSemantics() == &APFloat::IEEEquad;
953 case Type::PPC_FP128TyID:
954 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
955 &Val2.getSemantics() == &APFloat::IEEEdouble ||
956 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
960 //===----------------------------------------------------------------------===//
961 // Factory Function Implementation
963 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
964 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
965 "Cannot create an aggregate zero of non-aggregate type!");
967 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
968 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
971 /// destroyConstant - Remove the constant from the constant table...
973 void ConstantAggregateZero::destroyConstant() {
974 getType()->getContext().pImpl->AggZeroConstants.remove(this);
975 destroyConstantImpl();
978 /// destroyConstant - Remove the constant from the constant table...
980 void ConstantArray::destroyConstant() {
981 getType()->getContext().pImpl->ArrayConstants.remove(this);
982 destroyConstantImpl();
985 /// isString - This method returns true if the array is an array of i8, and
986 /// if the elements of the array are all ConstantInt's.
987 bool ConstantArray::isString() const {
988 // Check the element type for i8...
989 if (!getType()->getElementType()->isIntegerTy(8))
991 // Check the elements to make sure they are all integers, not constant
993 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
994 if (!isa<ConstantInt>(getOperand(i)))
999 /// isCString - This method returns true if the array is a string (see
1000 /// isString) and it ends in a null byte \\0 and does not contains any other
1001 /// null bytes except its terminator.
1002 bool ConstantArray::isCString() const {
1003 // Check the element type for i8...
1004 if (!getType()->getElementType()->isIntegerTy(8))
1007 // Last element must be a null.
1008 if (!getOperand(getNumOperands()-1)->isNullValue())
1010 // Other elements must be non-null integers.
1011 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
1012 if (!isa<ConstantInt>(getOperand(i)))
1014 if (getOperand(i)->isNullValue())
1021 /// convertToString - Helper function for getAsString() and getAsCString().
1022 static std::string convertToString(const User *U, unsigned len)
1025 Result.reserve(len);
1026 for (unsigned i = 0; i != len; ++i)
1027 Result.push_back((char)cast<ConstantInt>(U->getOperand(i))->getZExtValue());
1031 /// getAsString - If this array is isString(), then this method converts the
1032 /// array to an std::string and returns it. Otherwise, it asserts out.
1034 std::string ConstantArray::getAsString() const {
1035 assert(isString() && "Not a string!");
1036 return convertToString(this, getNumOperands());
1040 /// getAsCString - If this array is isCString(), then this method converts the
1041 /// array (without the trailing null byte) to an std::string and returns it.
1042 /// Otherwise, it asserts out.
1044 std::string ConstantArray::getAsCString() const {
1045 assert(isCString() && "Not a string!");
1046 return convertToString(this, getNumOperands() - 1);
1050 //---- ConstantStruct::get() implementation...
1057 // destroyConstant - Remove the constant from the constant table...
1059 void ConstantStruct::destroyConstant() {
1060 getType()->getContext().pImpl->StructConstants.remove(this);
1061 destroyConstantImpl();
1064 // destroyConstant - Remove the constant from the constant table...
1066 void ConstantVector::destroyConstant() {
1067 getType()->getContext().pImpl->VectorConstants.remove(this);
1068 destroyConstantImpl();
1071 /// This function will return true iff every element in this vector constant
1072 /// is set to all ones.
1073 /// @returns true iff this constant's emements are all set to all ones.
1074 /// @brief Determine if the value is all ones.
1075 bool ConstantVector::isAllOnesValue() const {
1076 // Check out first element.
1077 const Constant *Elt = getOperand(0);
1078 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1079 if (!CI || !CI->isAllOnesValue()) return false;
1080 // Then make sure all remaining elements point to the same value.
1081 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1082 if (getOperand(I) != Elt) return false;
1087 /// getSplatValue - If this is a splat constant, where all of the
1088 /// elements have the same value, return that value. Otherwise return null.
1089 Constant *ConstantVector::getSplatValue() const {
1090 // Check out first element.
1091 Constant *Elt = getOperand(0);
1092 // Then make sure all remaining elements point to the same value.
1093 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1094 if (getOperand(I) != Elt) return 0;
1098 //---- ConstantPointerNull::get() implementation.
1101 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1102 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1105 // destroyConstant - Remove the constant from the constant table...
1107 void ConstantPointerNull::destroyConstant() {
1108 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1109 destroyConstantImpl();
1113 //---- UndefValue::get() implementation.
1116 UndefValue *UndefValue::get(const Type *Ty) {
1117 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1120 // destroyConstant - Remove the constant from the constant table.
1122 void UndefValue::destroyConstant() {
1123 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1124 destroyConstantImpl();
1127 //---- BlockAddress::get() implementation.
1130 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1131 assert(BB->getParent() != 0 && "Block must have a parent");
1132 return get(BB->getParent(), BB);
1135 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1137 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1139 BA = new BlockAddress(F, BB);
1141 assert(BA->getFunction() == F && "Basic block moved between functions");
1145 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1146 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1150 BB->AdjustBlockAddressRefCount(1);
1154 // destroyConstant - Remove the constant from the constant table.
1156 void BlockAddress::destroyConstant() {
1157 getFunction()->getType()->getContext().pImpl
1158 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1159 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1160 destroyConstantImpl();
1163 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1164 // This could be replacing either the Basic Block or the Function. In either
1165 // case, we have to remove the map entry.
1166 Function *NewF = getFunction();
1167 BasicBlock *NewBB = getBasicBlock();
1170 NewF = cast<Function>(To);
1172 NewBB = cast<BasicBlock>(To);
1174 // See if the 'new' entry already exists, if not, just update this in place
1175 // and return early.
1176 BlockAddress *&NewBA =
1177 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1179 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1181 // Remove the old entry, this can't cause the map to rehash (just a
1182 // tombstone will get added).
1183 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1186 setOperand(0, NewF);
1187 setOperand(1, NewBB);
1188 getBasicBlock()->AdjustBlockAddressRefCount(1);
1192 // Otherwise, I do need to replace this with an existing value.
1193 assert(NewBA != this && "I didn't contain From!");
1195 // Everyone using this now uses the replacement.
1196 uncheckedReplaceAllUsesWith(NewBA);
1201 //---- ConstantExpr::get() implementations.
1204 /// This is a utility function to handle folding of casts and lookup of the
1205 /// cast in the ExprConstants map. It is used by the various get* methods below.
1206 static inline Constant *getFoldedCast(
1207 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1208 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1209 // Fold a few common cases
1210 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1213 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1215 // Look up the constant in the table first to ensure uniqueness
1216 std::vector<Constant*> argVec(1, C);
1217 ExprMapKeyType Key(opc, argVec);
1219 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1222 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1223 Instruction::CastOps opc = Instruction::CastOps(oc);
1224 assert(Instruction::isCast(opc) && "opcode out of range");
1225 assert(C && Ty && "Null arguments to getCast");
1226 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1230 llvm_unreachable("Invalid cast opcode");
1232 case Instruction::Trunc: return getTrunc(C, Ty);
1233 case Instruction::ZExt: return getZExt(C, Ty);
1234 case Instruction::SExt: return getSExt(C, Ty);
1235 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1236 case Instruction::FPExt: return getFPExtend(C, Ty);
1237 case Instruction::UIToFP: return getUIToFP(C, Ty);
1238 case Instruction::SIToFP: return getSIToFP(C, Ty);
1239 case Instruction::FPToUI: return getFPToUI(C, Ty);
1240 case Instruction::FPToSI: return getFPToSI(C, Ty);
1241 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1242 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1243 case Instruction::BitCast: return getBitCast(C, Ty);
1248 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1249 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1250 return getBitCast(C, Ty);
1251 return getZExt(C, Ty);
1254 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1255 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1256 return getBitCast(C, Ty);
1257 return getSExt(C, Ty);
1260 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1261 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1262 return getBitCast(C, Ty);
1263 return getTrunc(C, Ty);
1266 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1267 assert(S->getType()->isPointerTy() && "Invalid cast");
1268 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1270 if (Ty->isIntegerTy())
1271 return getPtrToInt(S, Ty);
1272 return getBitCast(S, Ty);
1275 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1277 assert(C->getType()->isIntOrIntVectorTy() &&
1278 Ty->isIntOrIntVectorTy() && "Invalid cast");
1279 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1280 unsigned DstBits = Ty->getScalarSizeInBits();
1281 Instruction::CastOps opcode =
1282 (SrcBits == DstBits ? Instruction::BitCast :
1283 (SrcBits > DstBits ? Instruction::Trunc :
1284 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1285 return getCast(opcode, C, Ty);
1288 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1289 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1291 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1292 unsigned DstBits = Ty->getScalarSizeInBits();
1293 if (SrcBits == DstBits)
1294 return C; // Avoid a useless cast
1295 Instruction::CastOps opcode =
1296 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1297 return getCast(opcode, C, Ty);
1300 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1302 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1303 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1305 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1306 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1307 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1308 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1309 "SrcTy must be larger than DestTy for Trunc!");
1311 return getFoldedCast(Instruction::Trunc, C, Ty);
1314 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1316 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1317 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1319 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1320 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1321 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1322 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1323 "SrcTy must be smaller than DestTy for SExt!");
1325 return getFoldedCast(Instruction::SExt, C, Ty);
1328 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1330 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1331 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1333 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1334 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1335 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1336 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1337 "SrcTy must be smaller than DestTy for ZExt!");
1339 return getFoldedCast(Instruction::ZExt, C, Ty);
1342 Constant *ConstantExpr::getFPTrunc(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()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1349 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1350 "This is an illegal floating point truncation!");
1351 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1354 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1356 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1357 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1359 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1360 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1361 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1362 "This is an illegal floating point extension!");
1363 return getFoldedCast(Instruction::FPExt, C, Ty);
1366 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1368 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1369 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1371 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1372 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1373 "This is an illegal uint to floating point cast!");
1374 return getFoldedCast(Instruction::UIToFP, C, Ty);
1377 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1379 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1380 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1382 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1383 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1384 "This is an illegal sint to floating point cast!");
1385 return getFoldedCast(Instruction::SIToFP, C, Ty);
1388 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1390 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1391 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1393 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1394 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1395 "This is an illegal floating point to uint cast!");
1396 return getFoldedCast(Instruction::FPToUI, C, Ty);
1399 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1401 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1402 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1404 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1405 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1406 "This is an illegal floating point to sint cast!");
1407 return getFoldedCast(Instruction::FPToSI, C, Ty);
1410 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1411 assert(C->getType()->isPointerTy() && "PtrToInt source must be pointer");
1412 assert(DstTy->isIntegerTy() && "PtrToInt destination must be integral");
1413 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1416 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1417 assert(C->getType()->isIntegerTy() && "IntToPtr source must be integral");
1418 assert(DstTy->isPointerTy() && "IntToPtr destination must be a pointer");
1419 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1422 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1423 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1424 "Invalid constantexpr bitcast!");
1426 // It is common to ask for a bitcast of a value to its own type, handle this
1428 if (C->getType() == DstTy) return C;
1430 return getFoldedCast(Instruction::BitCast, C, DstTy);
1433 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1435 // Check the operands for consistency first.
1436 assert(Opcode >= Instruction::BinaryOpsBegin &&
1437 Opcode < Instruction::BinaryOpsEnd &&
1438 "Invalid opcode in binary constant expression");
1439 assert(C1->getType() == C2->getType() &&
1440 "Operand types in binary constant expression should match");
1444 case Instruction::Add:
1445 case Instruction::Sub:
1446 case Instruction::Mul:
1447 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1448 assert(C1->getType()->isIntOrIntVectorTy() &&
1449 "Tried to create an integer operation on a non-integer type!");
1451 case Instruction::FAdd:
1452 case Instruction::FSub:
1453 case Instruction::FMul:
1454 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1455 assert(C1->getType()->isFPOrFPVectorTy() &&
1456 "Tried to create a floating-point operation on a "
1457 "non-floating-point type!");
1459 case Instruction::UDiv:
1460 case Instruction::SDiv:
1461 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1462 assert(C1->getType()->isIntOrIntVectorTy() &&
1463 "Tried to create an arithmetic operation on a non-arithmetic type!");
1465 case Instruction::FDiv:
1466 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1467 assert(C1->getType()->isFPOrFPVectorTy() &&
1468 "Tried to create an arithmetic operation on a non-arithmetic type!");
1470 case Instruction::URem:
1471 case Instruction::SRem:
1472 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1473 assert(C1->getType()->isIntOrIntVectorTy() &&
1474 "Tried to create an arithmetic operation on a non-arithmetic type!");
1476 case Instruction::FRem:
1477 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1478 assert(C1->getType()->isFPOrFPVectorTy() &&
1479 "Tried to create an arithmetic operation on a non-arithmetic type!");
1481 case Instruction::And:
1482 case Instruction::Or:
1483 case Instruction::Xor:
1484 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1485 assert(C1->getType()->isIntOrIntVectorTy() &&
1486 "Tried to create a logical operation on a non-integral type!");
1488 case Instruction::Shl:
1489 case Instruction::LShr:
1490 case Instruction::AShr:
1491 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1492 assert(C1->getType()->isIntOrIntVectorTy() &&
1493 "Tried to create a shift operation on a non-integer type!");
1500 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1501 return FC; // Fold a few common cases.
1503 std::vector<Constant*> argVec(1, C1);
1504 argVec.push_back(C2);
1505 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1507 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1508 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1511 Constant *ConstantExpr::getSizeOf(const Type* Ty) {
1512 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1513 // Note that a non-inbounds gep is used, as null isn't within any object.
1514 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1515 Constant *GEP = getGetElementPtr(
1516 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1517 return getPtrToInt(GEP,
1518 Type::getInt64Ty(Ty->getContext()));
1521 Constant *ConstantExpr::getAlignOf(const Type* Ty) {
1522 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1523 // Note that a non-inbounds gep is used, as null isn't within any object.
1524 const Type *AligningTy =
1525 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1526 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1527 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1528 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1529 Constant *Indices[2] = { Zero, One };
1530 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1531 return getPtrToInt(GEP,
1532 Type::getInt64Ty(Ty->getContext()));
1535 Constant *ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1536 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1540 Constant *ConstantExpr::getOffsetOf(const Type* Ty, Constant *FieldNo) {
1541 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1542 // Note that a non-inbounds gep is used, as null isn't within any object.
1543 Constant *GEPIdx[] = {
1544 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1547 Constant *GEP = getGetElementPtr(
1548 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx, 2);
1549 return getPtrToInt(GEP,
1550 Type::getInt64Ty(Ty->getContext()));
1553 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1554 Constant *C1, Constant *C2) {
1555 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1557 switch (Predicate) {
1558 default: llvm_unreachable("Invalid CmpInst predicate");
1559 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1560 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1561 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1562 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1563 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1564 case CmpInst::FCMP_TRUE:
1565 return getFCmp(Predicate, C1, C2);
1567 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1568 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1569 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1570 case CmpInst::ICMP_SLE:
1571 return getICmp(Predicate, C1, C2);
1575 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1576 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1578 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1579 return SC; // Fold common cases
1581 std::vector<Constant*> argVec(3, C);
1584 ExprMapKeyType Key(Instruction::Select, argVec);
1586 LLVMContextImpl *pImpl = C->getContext().pImpl;
1587 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1590 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1591 unsigned NumIdx, bool InBounds) {
1592 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs, NumIdx))
1593 return FC; // Fold a few common cases.
1595 // Get the result type of the getelementptr!
1597 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1598 assert(Ty && "GEP indices invalid!");
1599 unsigned AS = cast<PointerType>(C->getType())->getAddressSpace();
1600 Type *ReqTy = Ty->getPointerTo(AS);
1602 assert(C->getType()->isPointerTy() &&
1603 "Non-pointer type for constant GetElementPtr expression");
1604 // Look up the constant in the table first to ensure uniqueness
1605 std::vector<Constant*> ArgVec;
1606 ArgVec.reserve(NumIdx+1);
1607 ArgVec.push_back(C);
1608 for (unsigned i = 0; i != NumIdx; ++i)
1609 ArgVec.push_back(cast<Constant>(Idxs[i]));
1610 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1611 InBounds ? GEPOperator::IsInBounds : 0);
1613 LLVMContextImpl *pImpl = C->getContext().pImpl;
1614 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1618 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1619 assert(LHS->getType() == RHS->getType());
1620 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1621 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1623 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1624 return FC; // Fold a few common cases...
1626 // Look up the constant in the table first to ensure uniqueness
1627 std::vector<Constant*> ArgVec;
1628 ArgVec.push_back(LHS);
1629 ArgVec.push_back(RHS);
1630 // Get the key type with both the opcode and predicate
1631 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1633 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1634 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1635 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1637 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1638 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1642 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1643 assert(LHS->getType() == RHS->getType());
1644 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1646 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1647 return FC; // Fold a few common cases...
1649 // Look up the constant in the table first to ensure uniqueness
1650 std::vector<Constant*> ArgVec;
1651 ArgVec.push_back(LHS);
1652 ArgVec.push_back(RHS);
1653 // Get the key type with both the opcode and predicate
1654 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1656 const Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1657 if (const VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1658 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1660 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1661 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1664 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1665 assert(Val->getType()->isVectorTy() &&
1666 "Tried to create extractelement operation on non-vector type!");
1667 assert(Idx->getType()->isIntegerTy(32) &&
1668 "Extractelement index must be i32 type!");
1670 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1671 return FC; // Fold a few common cases.
1673 // Look up the constant in the table first to ensure uniqueness
1674 std::vector<Constant*> ArgVec(1, Val);
1675 ArgVec.push_back(Idx);
1676 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1678 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1679 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
1680 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1683 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1685 assert(Val->getType()->isVectorTy() &&
1686 "Tried to create insertelement operation on non-vector type!");
1687 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1688 && "Insertelement types must match!");
1689 assert(Idx->getType()->isIntegerTy(32) &&
1690 "Insertelement index must be i32 type!");
1692 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1693 return FC; // Fold a few common cases.
1694 // Look up the constant in the table first to ensure uniqueness
1695 std::vector<Constant*> ArgVec(1, Val);
1696 ArgVec.push_back(Elt);
1697 ArgVec.push_back(Idx);
1698 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1700 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1701 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1704 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1706 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1707 "Invalid shuffle vector constant expr operands!");
1709 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1710 return FC; // Fold a few common cases.
1712 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1713 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1714 const Type *ShufTy = VectorType::get(EltTy, NElts);
1716 // Look up the constant in the table first to ensure uniqueness
1717 std::vector<Constant*> ArgVec(1, V1);
1718 ArgVec.push_back(V2);
1719 ArgVec.push_back(Mask);
1720 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1722 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1723 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1726 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1727 ArrayRef<unsigned> Idxs) {
1728 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1729 Idxs) == Val->getType() &&
1730 "insertvalue indices invalid!");
1731 assert(Agg->getType()->isFirstClassType() &&
1732 "Non-first-class type for constant insertvalue expression");
1733 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1734 assert(FC && "insertvalue constant expr couldn't be folded!");
1738 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1739 ArrayRef<unsigned> Idxs) {
1740 assert(Agg->getType()->isFirstClassType() &&
1741 "Tried to create extractelement operation on non-first-class type!");
1743 const Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1745 assert(ReqTy && "extractvalue indices invalid!");
1747 assert(Agg->getType()->isFirstClassType() &&
1748 "Non-first-class type for constant extractvalue expression");
1749 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1750 assert(FC && "ExtractValue constant expr couldn't be folded!");
1754 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1755 assert(C->getType()->isIntOrIntVectorTy() &&
1756 "Cannot NEG a nonintegral value!");
1757 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1761 Constant *ConstantExpr::getFNeg(Constant *C) {
1762 assert(C->getType()->isFPOrFPVectorTy() &&
1763 "Cannot FNEG a non-floating-point value!");
1764 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1767 Constant *ConstantExpr::getNot(Constant *C) {
1768 assert(C->getType()->isIntOrIntVectorTy() &&
1769 "Cannot NOT a nonintegral value!");
1770 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1773 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1774 bool HasNUW, bool HasNSW) {
1775 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1776 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1777 return get(Instruction::Add, C1, C2, Flags);
1780 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
1781 return get(Instruction::FAdd, C1, C2);
1784 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
1785 bool HasNUW, bool HasNSW) {
1786 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1787 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1788 return get(Instruction::Sub, C1, C2, Flags);
1791 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
1792 return get(Instruction::FSub, C1, C2);
1795 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
1796 bool HasNUW, bool HasNSW) {
1797 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1798 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1799 return get(Instruction::Mul, C1, C2, Flags);
1802 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
1803 return get(Instruction::FMul, C1, C2);
1806 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
1807 return get(Instruction::UDiv, C1, C2,
1808 isExact ? PossiblyExactOperator::IsExact : 0);
1811 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
1812 return get(Instruction::SDiv, C1, C2,
1813 isExact ? PossiblyExactOperator::IsExact : 0);
1816 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
1817 return get(Instruction::FDiv, C1, C2);
1820 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
1821 return get(Instruction::URem, C1, C2);
1824 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
1825 return get(Instruction::SRem, C1, C2);
1828 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
1829 return get(Instruction::FRem, C1, C2);
1832 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
1833 return get(Instruction::And, C1, C2);
1836 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
1837 return get(Instruction::Or, C1, C2);
1840 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
1841 return get(Instruction::Xor, C1, C2);
1844 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
1845 bool HasNUW, bool HasNSW) {
1846 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1847 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1848 return get(Instruction::Shl, C1, C2, Flags);
1851 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
1852 return get(Instruction::LShr, C1, C2,
1853 isExact ? PossiblyExactOperator::IsExact : 0);
1856 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
1857 return get(Instruction::AShr, C1, C2,
1858 isExact ? PossiblyExactOperator::IsExact : 0);
1861 // destroyConstant - Remove the constant from the constant table...
1863 void ConstantExpr::destroyConstant() {
1864 getType()->getContext().pImpl->ExprConstants.remove(this);
1865 destroyConstantImpl();
1868 const char *ConstantExpr::getOpcodeName() const {
1869 return Instruction::getOpcodeName(getOpcode());
1874 GetElementPtrConstantExpr::
1875 GetElementPtrConstantExpr(Constant *C, const std::vector<Constant*> &IdxList,
1877 : ConstantExpr(DestTy, Instruction::GetElementPtr,
1878 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
1879 - (IdxList.size()+1), IdxList.size()+1) {
1881 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
1882 OperandList[i+1] = IdxList[i];
1886 //===----------------------------------------------------------------------===//
1887 // replaceUsesOfWithOnConstant implementations
1889 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1890 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1893 /// Note that we intentionally replace all uses of From with To here. Consider
1894 /// a large array that uses 'From' 1000 times. By handling this case all here,
1895 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1896 /// single invocation handles all 1000 uses. Handling them one at a time would
1897 /// work, but would be really slow because it would have to unique each updated
1900 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1902 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1903 Constant *ToC = cast<Constant>(To);
1905 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1907 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1908 Lookup.first.first = cast<ArrayType>(getType());
1909 Lookup.second = this;
1911 std::vector<Constant*> &Values = Lookup.first.second;
1912 Values.reserve(getNumOperands()); // Build replacement array.
1914 // Fill values with the modified operands of the constant array. Also,
1915 // compute whether this turns into an all-zeros array.
1916 bool isAllZeros = false;
1917 unsigned NumUpdated = 0;
1918 if (!ToC->isNullValue()) {
1919 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1920 Constant *Val = cast<Constant>(O->get());
1925 Values.push_back(Val);
1929 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1930 Constant *Val = cast<Constant>(O->get());
1935 Values.push_back(Val);
1936 if (isAllZeros) isAllZeros = Val->isNullValue();
1940 Constant *Replacement = 0;
1942 Replacement = ConstantAggregateZero::get(getType());
1944 // Check to see if we have this array type already.
1946 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1947 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1950 Replacement = I->second;
1952 // Okay, the new shape doesn't exist in the system yet. Instead of
1953 // creating a new constant array, inserting it, replaceallusesof'ing the
1954 // old with the new, then deleting the old... just update the current one
1956 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1958 // Update to the new value. Optimize for the case when we have a single
1959 // operand that we're changing, but handle bulk updates efficiently.
1960 if (NumUpdated == 1) {
1961 unsigned OperandToUpdate = U - OperandList;
1962 assert(getOperand(OperandToUpdate) == From &&
1963 "ReplaceAllUsesWith broken!");
1964 setOperand(OperandToUpdate, ToC);
1966 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1967 if (getOperand(i) == From)
1974 // Otherwise, I do need to replace this with an existing value.
1975 assert(Replacement != this && "I didn't contain From!");
1977 // Everyone using this now uses the replacement.
1978 uncheckedReplaceAllUsesWith(Replacement);
1980 // Delete the old constant!
1984 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
1986 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1987 Constant *ToC = cast<Constant>(To);
1989 unsigned OperandToUpdate = U-OperandList;
1990 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
1992 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
1993 Lookup.first.first = cast<StructType>(getType());
1994 Lookup.second = this;
1995 std::vector<Constant*> &Values = Lookup.first.second;
1996 Values.reserve(getNumOperands()); // Build replacement struct.
1999 // Fill values with the modified operands of the constant struct. Also,
2000 // compute whether this turns into an all-zeros struct.
2001 bool isAllZeros = false;
2002 if (!ToC->isNullValue()) {
2003 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2004 Values.push_back(cast<Constant>(O->get()));
2007 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2008 Constant *Val = cast<Constant>(O->get());
2009 Values.push_back(Val);
2010 if (isAllZeros) isAllZeros = Val->isNullValue();
2013 Values[OperandToUpdate] = ToC;
2015 LLVMContextImpl *pImpl = getContext().pImpl;
2017 Constant *Replacement = 0;
2019 Replacement = ConstantAggregateZero::get(getType());
2021 // Check to see if we have this struct type already.
2023 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2024 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2027 Replacement = I->second;
2029 // Okay, the new shape doesn't exist in the system yet. Instead of
2030 // creating a new constant struct, inserting it, replaceallusesof'ing the
2031 // old with the new, then deleting the old... just update the current one
2033 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2035 // Update to the new value.
2036 setOperand(OperandToUpdate, ToC);
2041 assert(Replacement != this && "I didn't contain From!");
2043 // Everyone using this now uses the replacement.
2044 uncheckedReplaceAllUsesWith(Replacement);
2046 // Delete the old constant!
2050 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2052 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2054 std::vector<Constant*> Values;
2055 Values.reserve(getNumOperands()); // Build replacement array...
2056 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2057 Constant *Val = getOperand(i);
2058 if (Val == From) Val = cast<Constant>(To);
2059 Values.push_back(Val);
2062 Constant *Replacement = get(Values);
2063 assert(Replacement != this && "I didn't contain From!");
2065 // Everyone using this now uses the replacement.
2066 uncheckedReplaceAllUsesWith(Replacement);
2068 // Delete the old constant!
2072 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2074 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2075 Constant *To = cast<Constant>(ToV);
2077 Constant *Replacement = 0;
2078 if (getOpcode() == Instruction::GetElementPtr) {
2079 SmallVector<Constant*, 8> Indices;
2080 Constant *Pointer = getOperand(0);
2081 Indices.reserve(getNumOperands()-1);
2082 if (Pointer == From) Pointer = To;
2084 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2085 Constant *Val = getOperand(i);
2086 if (Val == From) Val = To;
2087 Indices.push_back(Val);
2089 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2090 &Indices[0], Indices.size(),
2091 cast<GEPOperator>(this)->isInBounds());
2092 } else if (getOpcode() == Instruction::ExtractValue) {
2093 Constant *Agg = getOperand(0);
2094 if (Agg == From) Agg = To;
2096 ArrayRef<unsigned> Indices = getIndices();
2097 Replacement = ConstantExpr::getExtractValue(Agg, Indices);
2098 } else if (getOpcode() == Instruction::InsertValue) {
2099 Constant *Agg = getOperand(0);
2100 Constant *Val = getOperand(1);
2101 if (Agg == From) Agg = To;
2102 if (Val == From) Val = To;
2104 ArrayRef<unsigned> Indices = getIndices();
2105 Replacement = ConstantExpr::getInsertValue(Agg, Val, Indices);
2106 } else if (isCast()) {
2107 assert(getOperand(0) == From && "Cast only has one use!");
2108 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2109 } else if (getOpcode() == Instruction::Select) {
2110 Constant *C1 = getOperand(0);
2111 Constant *C2 = getOperand(1);
2112 Constant *C3 = getOperand(2);
2113 if (C1 == From) C1 = To;
2114 if (C2 == From) C2 = To;
2115 if (C3 == From) C3 = To;
2116 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2117 } else if (getOpcode() == Instruction::ExtractElement) {
2118 Constant *C1 = getOperand(0);
2119 Constant *C2 = getOperand(1);
2120 if (C1 == From) C1 = To;
2121 if (C2 == From) C2 = To;
2122 Replacement = ConstantExpr::getExtractElement(C1, C2);
2123 } else if (getOpcode() == Instruction::InsertElement) {
2124 Constant *C1 = getOperand(0);
2125 Constant *C2 = getOperand(1);
2126 Constant *C3 = getOperand(1);
2127 if (C1 == From) C1 = To;
2128 if (C2 == From) C2 = To;
2129 if (C3 == From) C3 = To;
2130 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2131 } else if (getOpcode() == Instruction::ShuffleVector) {
2132 Constant *C1 = getOperand(0);
2133 Constant *C2 = getOperand(1);
2134 Constant *C3 = getOperand(2);
2135 if (C1 == From) C1 = To;
2136 if (C2 == From) C2 = To;
2137 if (C3 == From) C3 = To;
2138 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2139 } else if (isCompare()) {
2140 Constant *C1 = getOperand(0);
2141 Constant *C2 = getOperand(1);
2142 if (C1 == From) C1 = To;
2143 if (C2 == From) C2 = To;
2144 if (getOpcode() == Instruction::ICmp)
2145 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2147 assert(getOpcode() == Instruction::FCmp);
2148 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2150 } else if (getNumOperands() == 2) {
2151 Constant *C1 = getOperand(0);
2152 Constant *C2 = getOperand(1);
2153 if (C1 == From) C1 = To;
2154 if (C2 == From) C2 = To;
2155 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassOptionalData);
2157 llvm_unreachable("Unknown ConstantExpr type!");
2161 assert(Replacement != this && "I didn't contain From!");
2163 // Everyone using this now uses the replacement.
2164 uncheckedReplaceAllUsesWith(Replacement);
2166 // Delete the old constant!