1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Constant* classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Constants.h"
15 #include "LLVMContextImpl.h"
16 #include "ConstantFold.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalValue.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/System/Mutex.h"
33 #include "llvm/System/RWMutex.h"
34 #include "llvm/System/Threading.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/SmallVector.h"
41 //===----------------------------------------------------------------------===//
43 //===----------------------------------------------------------------------===//
45 // Constructor to create a '0' constant of arbitrary type...
46 static const uint64_t zero[2] = {0, 0};
47 Constant *Constant::getNullValue(const Type *Ty) {
48 switch (Ty->getTypeID()) {
49 case Type::IntegerTyID:
50 return ConstantInt::get(Ty, 0);
52 return ConstantFP::get(Ty->getContext(), APFloat(APInt(32, 0)));
53 case Type::DoubleTyID:
54 return ConstantFP::get(Ty->getContext(), APFloat(APInt(64, 0)));
55 case Type::X86_FP80TyID:
56 return ConstantFP::get(Ty->getContext(), APFloat(APInt(80, 2, zero)));
58 return ConstantFP::get(Ty->getContext(),
59 APFloat(APInt(128, 2, zero), true));
60 case Type::PPC_FP128TyID:
61 return ConstantFP::get(Ty->getContext(), APFloat(APInt(128, 2, zero)));
62 case Type::PointerTyID:
63 return ConstantPointerNull::get(cast<PointerType>(Ty));
64 case Type::StructTyID:
66 case Type::VectorTyID:
67 return ConstantAggregateZero::get(Ty);
69 // Function, Label, or Opaque type?
70 assert(!"Cannot create a null constant of that type!");
75 Constant* Constant::getIntegerValue(const Type *Ty, const APInt &V) {
76 const Type *ScalarTy = Ty->getScalarType();
78 // Create the base integer constant.
79 Constant *C = ConstantInt::get(Ty->getContext(), V);
81 // Convert an integer to a pointer, if necessary.
82 if (const PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
83 C = ConstantExpr::getIntToPtr(C, PTy);
85 // Broadcast a scalar to a vector, if necessary.
86 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
87 C = ConstantVector::get(std::vector<Constant *>(VTy->getNumElements(), C));
92 Constant* Constant::getAllOnesValue(const Type *Ty) {
93 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty))
94 return ConstantInt::get(Ty->getContext(),
95 APInt::getAllOnesValue(ITy->getBitWidth()));
97 std::vector<Constant*> Elts;
98 const VectorType *VTy = cast<VectorType>(Ty);
99 Elts.resize(VTy->getNumElements(), getAllOnesValue(VTy->getElementType()));
100 assert(Elts[0] && "Not a vector integer type!");
101 return cast<ConstantVector>(ConstantVector::get(Elts));
104 void Constant::destroyConstantImpl() {
105 // When a Constant is destroyed, there may be lingering
106 // references to the constant by other constants in the constant pool. These
107 // constants are implicitly dependent on the module that is being deleted,
108 // but they don't know that. Because we only find out when the CPV is
109 // deleted, we must now notify all of our users (that should only be
110 // Constants) that they are, in fact, invalid now and should be deleted.
112 while (!use_empty()) {
113 Value *V = use_back();
114 #ifndef NDEBUG // Only in -g mode...
115 if (!isa<Constant>(V)) {
116 errs() << "While deleting: " << *this
117 << "\n\nUse still stuck around after Def is destroyed: "
121 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
122 Constant *CV = cast<Constant>(V);
123 CV->destroyConstant();
125 // The constant should remove itself from our use list...
126 assert((use_empty() || use_back() != V) && "Constant not removed!");
129 // Value has no outstanding references it is safe to delete it now...
133 /// canTrap - Return true if evaluation of this constant could trap. This is
134 /// true for things like constant expressions that could divide by zero.
135 bool Constant::canTrap() const {
136 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
137 // The only thing that could possibly trap are constant exprs.
138 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
139 if (!CE) return false;
141 // ConstantExpr traps if any operands can trap.
142 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
143 if (CE->getOperand(i)->canTrap())
146 // Otherwise, only specific operations can trap.
147 switch (CE->getOpcode()) {
150 case Instruction::UDiv:
151 case Instruction::SDiv:
152 case Instruction::FDiv:
153 case Instruction::URem:
154 case Instruction::SRem:
155 case Instruction::FRem:
156 // Div and rem can trap if the RHS is not known to be non-zero.
157 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
163 /// isConstantUsed - Return true if the constant has users other than constant
164 /// exprs and other dangling things.
165 bool Constant::isConstantUsed() const {
166 for (use_const_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
167 const Constant *UC = dyn_cast<Constant>(*UI);
168 if (UC == 0 || isa<GlobalValue>(UC))
171 if (UC->isConstantUsed())
179 /// getRelocationInfo - This method classifies the entry according to
180 /// whether or not it may generate a relocation entry. This must be
181 /// conservative, so if it might codegen to a relocatable entry, it should say
182 /// so. The return values are:
184 /// NoRelocation: This constant pool entry is guaranteed to never have a
185 /// relocation applied to it (because it holds a simple constant like
187 /// LocalRelocation: This entry has relocations, but the entries are
188 /// guaranteed to be resolvable by the static linker, so the dynamic
189 /// linker will never see them.
190 /// GlobalRelocations: This entry may have arbitrary relocations.
192 /// FIXME: This really should not be in VMCore.
193 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
194 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
195 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
196 return LocalRelocation; // Local to this file/library.
197 return GlobalRelocations; // Global reference.
200 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
201 return BA->getFunction()->getRelocationInfo();
203 PossibleRelocationsTy Result = NoRelocation;
204 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
205 Result = std::max(Result,
206 cast<Constant>(getOperand(i))->getRelocationInfo());
212 /// getVectorElements - This method, which is only valid on constant of vector
213 /// type, returns the elements of the vector in the specified smallvector.
214 /// This handles breaking down a vector undef into undef elements, etc. For
215 /// constant exprs and other cases we can't handle, we return an empty vector.
216 void Constant::getVectorElements(LLVMContext &Context,
217 SmallVectorImpl<Constant*> &Elts) const {
218 assert(isa<VectorType>(getType()) && "Not a vector constant!");
220 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this)) {
221 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i)
222 Elts.push_back(CV->getOperand(i));
226 const VectorType *VT = cast<VectorType>(getType());
227 if (isa<ConstantAggregateZero>(this)) {
228 Elts.assign(VT->getNumElements(),
229 Constant::getNullValue(VT->getElementType()));
233 if (isa<UndefValue>(this)) {
234 Elts.assign(VT->getNumElements(), UndefValue::get(VT->getElementType()));
238 // Unknown type, must be constant expr etc.
243 //===----------------------------------------------------------------------===//
245 //===----------------------------------------------------------------------===//
247 ConstantInt::ConstantInt(const IntegerType *Ty, const APInt& V)
248 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
249 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
252 ConstantInt* ConstantInt::getTrue(LLVMContext &Context) {
253 LLVMContextImpl *pImpl = Context.pImpl;
254 if (pImpl->TheTrueVal)
255 return pImpl->TheTrueVal;
257 return (pImpl->TheTrueVal =
258 ConstantInt::get(IntegerType::get(Context, 1), 1));
261 ConstantInt* ConstantInt::getFalse(LLVMContext &Context) {
262 LLVMContextImpl *pImpl = Context.pImpl;
263 if (pImpl->TheFalseVal)
264 return pImpl->TheFalseVal;
266 return (pImpl->TheFalseVal =
267 ConstantInt::get(IntegerType::get(Context, 1), 0));
271 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
272 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
273 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
274 // compare APInt's of different widths, which would violate an APInt class
275 // invariant which generates an assertion.
276 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt& V) {
277 // Get the corresponding integer type for the bit width of the value.
278 const IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
279 // get an existing value or the insertion position
280 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
281 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
282 if (!Slot) Slot = new ConstantInt(ITy, V);
286 Constant* ConstantInt::get(const Type* Ty, uint64_t V, bool isSigned) {
287 Constant *C = get(cast<IntegerType>(Ty->getScalarType()),
290 // For vectors, broadcast the value.
291 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
292 return ConstantVector::get(
293 std::vector<Constant *>(VTy->getNumElements(), C));
298 ConstantInt* ConstantInt::get(const IntegerType* Ty, uint64_t V,
300 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
303 ConstantInt* ConstantInt::getSigned(const IntegerType* Ty, int64_t V) {
304 return get(Ty, V, true);
307 Constant *ConstantInt::getSigned(const Type *Ty, int64_t V) {
308 return get(Ty, V, true);
311 Constant* ConstantInt::get(const Type* Ty, const APInt& V) {
312 ConstantInt *C = get(Ty->getContext(), V);
313 assert(C->getType() == Ty->getScalarType() &&
314 "ConstantInt type doesn't match the type implied by its value!");
316 // For vectors, broadcast the value.
317 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
318 return ConstantVector::get(
319 std::vector<Constant *>(VTy->getNumElements(), C));
324 ConstantInt* ConstantInt::get(const IntegerType* Ty, const StringRef& Str,
326 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
329 //===----------------------------------------------------------------------===//
331 //===----------------------------------------------------------------------===//
333 static const fltSemantics *TypeToFloatSemantics(const Type *Ty) {
335 return &APFloat::IEEEsingle;
336 if (Ty->isDoubleTy())
337 return &APFloat::IEEEdouble;
338 if (Ty->isX86_FP80Ty())
339 return &APFloat::x87DoubleExtended;
340 else if (Ty->isFP128Ty())
341 return &APFloat::IEEEquad;
343 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
344 return &APFloat::PPCDoubleDouble;
347 /// get() - This returns a constant fp for the specified value in the
348 /// specified type. This should only be used for simple constant values like
349 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
350 Constant* ConstantFP::get(const Type* Ty, double V) {
351 LLVMContext &Context = Ty->getContext();
355 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
356 APFloat::rmNearestTiesToEven, &ignored);
357 Constant *C = get(Context, FV);
359 // For vectors, broadcast the value.
360 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
361 return ConstantVector::get(
362 std::vector<Constant *>(VTy->getNumElements(), C));
368 Constant* ConstantFP::get(const Type* Ty, const StringRef& Str) {
369 LLVMContext &Context = Ty->getContext();
371 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
372 Constant *C = get(Context, FV);
374 // For vectors, broadcast the value.
375 if (const VectorType *VTy = dyn_cast<VectorType>(Ty))
376 return ConstantVector::get(
377 std::vector<Constant *>(VTy->getNumElements(), C));
383 ConstantFP* ConstantFP::getNegativeZero(const Type* Ty) {
384 LLVMContext &Context = Ty->getContext();
385 APFloat apf = cast <ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
387 return get(Context, apf);
391 Constant* ConstantFP::getZeroValueForNegation(const Type* Ty) {
392 if (const VectorType *PTy = dyn_cast<VectorType>(Ty))
393 if (PTy->getElementType()->isFloatingPoint()) {
394 std::vector<Constant*> zeros(PTy->getNumElements(),
395 getNegativeZero(PTy->getElementType()));
396 return ConstantVector::get(PTy, zeros);
399 if (Ty->isFloatingPoint())
400 return getNegativeZero(Ty);
402 return Constant::getNullValue(Ty);
406 // ConstantFP accessors.
407 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
408 DenseMapAPFloatKeyInfo::KeyTy Key(V);
410 LLVMContextImpl* pImpl = Context.pImpl;
412 ConstantFP *&Slot = pImpl->FPConstants[Key];
416 if (&V.getSemantics() == &APFloat::IEEEsingle)
417 Ty = Type::getFloatTy(Context);
418 else if (&V.getSemantics() == &APFloat::IEEEdouble)
419 Ty = Type::getDoubleTy(Context);
420 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
421 Ty = Type::getX86_FP80Ty(Context);
422 else if (&V.getSemantics() == &APFloat::IEEEquad)
423 Ty = Type::getFP128Ty(Context);
425 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
426 "Unknown FP format");
427 Ty = Type::getPPC_FP128Ty(Context);
429 Slot = new ConstantFP(Ty, V);
435 ConstantFP *ConstantFP::getInfinity(const Type *Ty, bool Negative) {
436 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
437 return ConstantFP::get(Ty->getContext(),
438 APFloat::getInf(Semantics, Negative));
441 ConstantFP::ConstantFP(const Type *Ty, const APFloat& V)
442 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
443 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
447 bool ConstantFP::isNullValue() const {
448 return Val.isZero() && !Val.isNegative();
451 bool ConstantFP::isExactlyValue(const APFloat& V) const {
452 return Val.bitwiseIsEqual(V);
455 //===----------------------------------------------------------------------===//
456 // ConstantXXX Classes
457 //===----------------------------------------------------------------------===//
460 ConstantArray::ConstantArray(const ArrayType *T,
461 const std::vector<Constant*> &V)
462 : Constant(T, ConstantArrayVal,
463 OperandTraits<ConstantArray>::op_end(this) - V.size(),
465 assert(V.size() == T->getNumElements() &&
466 "Invalid initializer vector for constant array");
467 Use *OL = OperandList;
468 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
471 assert(C->getType() == T->getElementType() &&
472 "Initializer for array element doesn't match array element type!");
477 Constant *ConstantArray::get(const ArrayType *Ty,
478 const std::vector<Constant*> &V) {
479 for (unsigned i = 0, e = V.size(); i != e; ++i) {
480 assert(V[i]->getType() == Ty->getElementType() &&
481 "Wrong type in array element initializer");
483 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
484 // If this is an all-zero array, return a ConstantAggregateZero object
487 if (!C->isNullValue()) {
488 // Implicitly locked.
489 return pImpl->ArrayConstants.getOrCreate(Ty, V);
491 for (unsigned i = 1, e = V.size(); i != e; ++i)
493 // Implicitly locked.
494 return pImpl->ArrayConstants.getOrCreate(Ty, V);
498 return ConstantAggregateZero::get(Ty);
502 Constant* ConstantArray::get(const ArrayType* T, Constant* const* Vals,
504 // FIXME: make this the primary ctor method.
505 return get(T, std::vector<Constant*>(Vals, Vals+NumVals));
508 /// ConstantArray::get(const string&) - Return an array that is initialized to
509 /// contain the specified string. If length is zero then a null terminator is
510 /// added to the specified string so that it may be used in a natural way.
511 /// Otherwise, the length parameter specifies how much of the string to use
512 /// and it won't be null terminated.
514 Constant* ConstantArray::get(LLVMContext &Context, const StringRef &Str,
516 std::vector<Constant*> ElementVals;
517 for (unsigned i = 0; i < Str.size(); ++i)
518 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), Str[i]));
520 // Add a null terminator to the string...
522 ElementVals.push_back(ConstantInt::get(Type::getInt8Ty(Context), 0));
525 ArrayType *ATy = ArrayType::get(Type::getInt8Ty(Context), ElementVals.size());
526 return get(ATy, ElementVals);
531 ConstantStruct::ConstantStruct(const StructType *T,
532 const std::vector<Constant*> &V)
533 : Constant(T, ConstantStructVal,
534 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
536 assert(V.size() == T->getNumElements() &&
537 "Invalid initializer vector for constant structure");
538 Use *OL = OperandList;
539 for (std::vector<Constant*>::const_iterator I = V.begin(), E = V.end();
542 assert(C->getType() == T->getElementType(I-V.begin()) &&
543 "Initializer for struct element doesn't match struct element type!");
548 // ConstantStruct accessors.
549 Constant* ConstantStruct::get(const StructType* T,
550 const std::vector<Constant*>& V) {
551 LLVMContextImpl* pImpl = T->getContext().pImpl;
553 // Create a ConstantAggregateZero value if all elements are zeros...
554 for (unsigned i = 0, e = V.size(); i != e; ++i)
555 if (!V[i]->isNullValue())
556 // Implicitly locked.
557 return pImpl->StructConstants.getOrCreate(T, V);
559 return ConstantAggregateZero::get(T);
562 Constant* ConstantStruct::get(LLVMContext &Context,
563 const std::vector<Constant*>& V, bool packed) {
564 std::vector<const Type*> StructEls;
565 StructEls.reserve(V.size());
566 for (unsigned i = 0, e = V.size(); i != e; ++i)
567 StructEls.push_back(V[i]->getType());
568 return get(StructType::get(Context, StructEls, packed), V);
571 Constant* ConstantStruct::get(LLVMContext &Context,
572 Constant* const *Vals, unsigned NumVals,
574 // FIXME: make this the primary ctor method.
575 return get(Context, std::vector<Constant*>(Vals, Vals+NumVals), Packed);
578 ConstantVector::ConstantVector(const VectorType *T,
579 const std::vector<Constant*> &V)
580 : Constant(T, ConstantVectorVal,
581 OperandTraits<ConstantVector>::op_end(this) - V.size(),
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 vector element doesn't match vector element type!");
593 // ConstantVector accessors.
594 Constant* ConstantVector::get(const VectorType* T,
595 const std::vector<Constant*>& V) {
596 assert(!V.empty() && "Vectors can't be empty");
597 LLVMContext &Context = T->getContext();
598 LLVMContextImpl *pImpl = Context.pImpl;
600 // If this is an all-undef or alll-zero vector, return a
601 // ConstantAggregateZero or UndefValue.
603 bool isZero = C->isNullValue();
604 bool isUndef = isa<UndefValue>(C);
606 if (isZero || isUndef) {
607 for (unsigned i = 1, e = V.size(); i != e; ++i)
609 isZero = isUndef = false;
615 return ConstantAggregateZero::get(T);
617 return UndefValue::get(T);
619 // Implicitly locked.
620 return pImpl->VectorConstants.getOrCreate(T, V);
623 Constant* ConstantVector::get(const std::vector<Constant*>& V) {
624 assert(!V.empty() && "Cannot infer type if V is empty");
625 return get(VectorType::get(V.front()->getType(),V.size()), V);
628 Constant* ConstantVector::get(Constant* const* Vals, unsigned NumVals) {
629 // FIXME: make this the primary ctor method.
630 return get(std::vector<Constant*>(Vals, Vals+NumVals));
633 Constant* ConstantExpr::getNSWAdd(Constant* C1, Constant* C2) {
634 return getTy(C1->getType(), Instruction::Add, C1, C2,
635 OverflowingBinaryOperator::NoSignedWrap);
638 Constant* ConstantExpr::getNSWSub(Constant* C1, Constant* C2) {
639 return getTy(C1->getType(), Instruction::Sub, C1, C2,
640 OverflowingBinaryOperator::NoSignedWrap);
643 Constant* ConstantExpr::getExactSDiv(Constant* C1, Constant* C2) {
644 return getTy(C1->getType(), Instruction::SDiv, C1, C2,
645 SDivOperator::IsExact);
648 // Utility function for determining if a ConstantExpr is a CastOp or not. This
649 // can't be inline because we don't want to #include Instruction.h into
651 bool ConstantExpr::isCast() const {
652 return Instruction::isCast(getOpcode());
655 bool ConstantExpr::isCompare() const {
656 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
659 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
660 if (getOpcode() != Instruction::GetElementPtr) return false;
662 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
663 User::const_op_iterator OI = next(this->op_begin());
665 // Skip the first index, as it has no static limit.
669 // The remaining indices must be compile-time known integers within the
670 // bounds of the corresponding notional static array types.
671 for (; GEPI != E; ++GEPI, ++OI) {
672 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
673 if (!CI) return false;
674 if (const ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
675 if (CI->getValue().getActiveBits() > 64 ||
676 CI->getZExtValue() >= ATy->getNumElements())
680 // All the indices checked out.
684 bool ConstantExpr::hasIndices() const {
685 return getOpcode() == Instruction::ExtractValue ||
686 getOpcode() == Instruction::InsertValue;
689 const SmallVector<unsigned, 4> &ConstantExpr::getIndices() const {
690 if (const ExtractValueConstantExpr *EVCE =
691 dyn_cast<ExtractValueConstantExpr>(this))
692 return EVCE->Indices;
694 return cast<InsertValueConstantExpr>(this)->Indices;
697 unsigned ConstantExpr::getPredicate() const {
698 assert(getOpcode() == Instruction::FCmp ||
699 getOpcode() == Instruction::ICmp);
700 return ((const CompareConstantExpr*)this)->predicate;
703 /// getWithOperandReplaced - Return a constant expression identical to this
704 /// one, but with the specified operand set to the specified value.
706 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
707 assert(OpNo < getNumOperands() && "Operand num is out of range!");
708 assert(Op->getType() == getOperand(OpNo)->getType() &&
709 "Replacing operand with value of different type!");
710 if (getOperand(OpNo) == Op)
711 return const_cast<ConstantExpr*>(this);
713 Constant *Op0, *Op1, *Op2;
714 switch (getOpcode()) {
715 case Instruction::Trunc:
716 case Instruction::ZExt:
717 case Instruction::SExt:
718 case Instruction::FPTrunc:
719 case Instruction::FPExt:
720 case Instruction::UIToFP:
721 case Instruction::SIToFP:
722 case Instruction::FPToUI:
723 case Instruction::FPToSI:
724 case Instruction::PtrToInt:
725 case Instruction::IntToPtr:
726 case Instruction::BitCast:
727 return ConstantExpr::getCast(getOpcode(), Op, getType());
728 case Instruction::Select:
729 Op0 = (OpNo == 0) ? Op : getOperand(0);
730 Op1 = (OpNo == 1) ? Op : getOperand(1);
731 Op2 = (OpNo == 2) ? Op : getOperand(2);
732 return ConstantExpr::getSelect(Op0, Op1, Op2);
733 case Instruction::InsertElement:
734 Op0 = (OpNo == 0) ? Op : getOperand(0);
735 Op1 = (OpNo == 1) ? Op : getOperand(1);
736 Op2 = (OpNo == 2) ? Op : getOperand(2);
737 return ConstantExpr::getInsertElement(Op0, Op1, Op2);
738 case Instruction::ExtractElement:
739 Op0 = (OpNo == 0) ? Op : getOperand(0);
740 Op1 = (OpNo == 1) ? Op : getOperand(1);
741 return ConstantExpr::getExtractElement(Op0, Op1);
742 case Instruction::ShuffleVector:
743 Op0 = (OpNo == 0) ? Op : getOperand(0);
744 Op1 = (OpNo == 1) ? Op : getOperand(1);
745 Op2 = (OpNo == 2) ? Op : getOperand(2);
746 return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
747 case Instruction::GetElementPtr: {
748 SmallVector<Constant*, 8> Ops;
749 Ops.resize(getNumOperands()-1);
750 for (unsigned i = 1, e = getNumOperands(); i != e; ++i)
751 Ops[i-1] = getOperand(i);
753 return cast<GEPOperator>(this)->isInBounds() ?
754 ConstantExpr::getInBoundsGetElementPtr(Op, &Ops[0], Ops.size()) :
755 ConstantExpr::getGetElementPtr(Op, &Ops[0], Ops.size());
757 return cast<GEPOperator>(this)->isInBounds() ?
758 ConstantExpr::getInBoundsGetElementPtr(getOperand(0), &Ops[0], Ops.size()) :
759 ConstantExpr::getGetElementPtr(getOperand(0), &Ops[0], Ops.size());
762 assert(getNumOperands() == 2 && "Must be binary operator?");
763 Op0 = (OpNo == 0) ? Op : getOperand(0);
764 Op1 = (OpNo == 1) ? Op : getOperand(1);
765 return ConstantExpr::get(getOpcode(), Op0, Op1, SubclassData);
769 /// getWithOperands - This returns the current constant expression with the
770 /// operands replaced with the specified values. The specified operands must
771 /// match count and type with the existing ones.
772 Constant *ConstantExpr::
773 getWithOperands(Constant* const *Ops, unsigned NumOps) const {
774 assert(NumOps == getNumOperands() && "Operand count mismatch!");
775 bool AnyChange = false;
776 for (unsigned i = 0; i != NumOps; ++i) {
777 assert(Ops[i]->getType() == getOperand(i)->getType() &&
778 "Operand type mismatch!");
779 AnyChange |= Ops[i] != getOperand(i);
781 if (!AnyChange) // No operands changed, return self.
782 return const_cast<ConstantExpr*>(this);
784 switch (getOpcode()) {
785 case Instruction::Trunc:
786 case Instruction::ZExt:
787 case Instruction::SExt:
788 case Instruction::FPTrunc:
789 case Instruction::FPExt:
790 case Instruction::UIToFP:
791 case Instruction::SIToFP:
792 case Instruction::FPToUI:
793 case Instruction::FPToSI:
794 case Instruction::PtrToInt:
795 case Instruction::IntToPtr:
796 case Instruction::BitCast:
797 return ConstantExpr::getCast(getOpcode(), Ops[0], getType());
798 case Instruction::Select:
799 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
800 case Instruction::InsertElement:
801 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
802 case Instruction::ExtractElement:
803 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
804 case Instruction::ShuffleVector:
805 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
806 case Instruction::GetElementPtr:
807 return cast<GEPOperator>(this)->isInBounds() ?
808 ConstantExpr::getInBoundsGetElementPtr(Ops[0], &Ops[1], NumOps-1) :
809 ConstantExpr::getGetElementPtr(Ops[0], &Ops[1], NumOps-1);
810 case Instruction::ICmp:
811 case Instruction::FCmp:
812 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
814 assert(getNumOperands() == 2 && "Must be binary operator?");
815 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassData);
820 //===----------------------------------------------------------------------===//
821 // isValueValidForType implementations
823 bool ConstantInt::isValueValidForType(const Type *Ty, uint64_t Val) {
824 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
825 if (Ty == Type::getInt1Ty(Ty->getContext()))
826 return Val == 0 || Val == 1;
828 return true; // always true, has to fit in largest type
829 uint64_t Max = (1ll << NumBits) - 1;
833 bool ConstantInt::isValueValidForType(const Type *Ty, int64_t Val) {
834 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth(); // assert okay
835 if (Ty == Type::getInt1Ty(Ty->getContext()))
836 return Val == 0 || Val == 1 || Val == -1;
838 return true; // always true, has to fit in largest type
839 int64_t Min = -(1ll << (NumBits-1));
840 int64_t Max = (1ll << (NumBits-1)) - 1;
841 return (Val >= Min && Val <= Max);
844 bool ConstantFP::isValueValidForType(const Type *Ty, const APFloat& Val) {
845 // convert modifies in place, so make a copy.
846 APFloat Val2 = APFloat(Val);
848 switch (Ty->getTypeID()) {
850 return false; // These can't be represented as floating point!
852 // FIXME rounding mode needs to be more flexible
853 case Type::FloatTyID: {
854 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
856 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
859 case Type::DoubleTyID: {
860 if (&Val2.getSemantics() == &APFloat::IEEEsingle ||
861 &Val2.getSemantics() == &APFloat::IEEEdouble)
863 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
866 case Type::X86_FP80TyID:
867 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
868 &Val2.getSemantics() == &APFloat::IEEEdouble ||
869 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
870 case Type::FP128TyID:
871 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
872 &Val2.getSemantics() == &APFloat::IEEEdouble ||
873 &Val2.getSemantics() == &APFloat::IEEEquad;
874 case Type::PPC_FP128TyID:
875 return &Val2.getSemantics() == &APFloat::IEEEsingle ||
876 &Val2.getSemantics() == &APFloat::IEEEdouble ||
877 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
881 //===----------------------------------------------------------------------===//
882 // Factory Function Implementation
884 ConstantAggregateZero* ConstantAggregateZero::get(const Type* Ty) {
885 assert((isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) &&
886 "Cannot create an aggregate zero of non-aggregate type!");
888 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
889 // Implicitly locked.
890 return pImpl->AggZeroConstants.getOrCreate(Ty, 0);
893 /// destroyConstant - Remove the constant from the constant table...
895 void ConstantAggregateZero::destroyConstant() {
896 // Implicitly locked.
897 getType()->getContext().pImpl->AggZeroConstants.remove(this);
898 destroyConstantImpl();
901 /// destroyConstant - Remove the constant from the constant table...
903 void ConstantArray::destroyConstant() {
904 // Implicitly locked.
905 getType()->getContext().pImpl->ArrayConstants.remove(this);
906 destroyConstantImpl();
909 /// isString - This method returns true if the array is an array of i8, and
910 /// if the elements of the array are all ConstantInt's.
911 bool ConstantArray::isString() const {
912 // Check the element type for i8...
913 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
915 // Check the elements to make sure they are all integers, not constant
917 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
918 if (!isa<ConstantInt>(getOperand(i)))
923 /// isCString - This method returns true if the array is a string (see
924 /// isString) and it ends in a null byte \\0 and does not contains any other
925 /// null bytes except its terminator.
926 bool ConstantArray::isCString() const {
927 // Check the element type for i8...
928 if (getType()->getElementType() != Type::getInt8Ty(getContext()))
931 // Last element must be a null.
932 if (!getOperand(getNumOperands()-1)->isNullValue())
934 // Other elements must be non-null integers.
935 for (unsigned i = 0, e = getNumOperands()-1; i != e; ++i) {
936 if (!isa<ConstantInt>(getOperand(i)))
938 if (getOperand(i)->isNullValue())
945 /// getAsString - If the sub-element type of this array is i8
946 /// then this method converts the array to an std::string and returns it.
947 /// Otherwise, it asserts out.
949 std::string ConstantArray::getAsString() const {
950 assert(isString() && "Not a string!");
952 Result.reserve(getNumOperands());
953 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
954 Result.push_back((char)cast<ConstantInt>(getOperand(i))->getZExtValue());
959 //---- ConstantStruct::get() implementation...
966 // destroyConstant - Remove the constant from the constant table...
968 void ConstantStruct::destroyConstant() {
969 // Implicitly locked.
970 getType()->getContext().pImpl->StructConstants.remove(this);
971 destroyConstantImpl();
974 // destroyConstant - Remove the constant from the constant table...
976 void ConstantVector::destroyConstant() {
977 // Implicitly locked.
978 getType()->getContext().pImpl->VectorConstants.remove(this);
979 destroyConstantImpl();
982 /// This function will return true iff every element in this vector constant
983 /// is set to all ones.
984 /// @returns true iff this constant's emements are all set to all ones.
985 /// @brief Determine if the value is all ones.
986 bool ConstantVector::isAllOnesValue() const {
987 // Check out first element.
988 const Constant *Elt = getOperand(0);
989 const ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
990 if (!CI || !CI->isAllOnesValue()) return false;
991 // Then make sure all remaining elements point to the same value.
992 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
993 if (getOperand(I) != Elt) return false;
998 /// getSplatValue - If this is a splat constant, where all of the
999 /// elements have the same value, return that value. Otherwise return null.
1000 Constant *ConstantVector::getSplatValue() {
1001 // Check out first element.
1002 Constant *Elt = getOperand(0);
1003 // Then make sure all remaining elements point to the same value.
1004 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1005 if (getOperand(I) != Elt) return 0;
1009 //---- ConstantPointerNull::get() implementation.
1012 ConstantPointerNull *ConstantPointerNull::get(const PointerType *Ty) {
1013 // Implicitly locked.
1014 return Ty->getContext().pImpl->NullPtrConstants.getOrCreate(Ty, 0);
1017 // destroyConstant - Remove the constant from the constant table...
1019 void ConstantPointerNull::destroyConstant() {
1020 // Implicitly locked.
1021 getType()->getContext().pImpl->NullPtrConstants.remove(this);
1022 destroyConstantImpl();
1026 //---- UndefValue::get() implementation.
1029 UndefValue *UndefValue::get(const Type *Ty) {
1030 return Ty->getContext().pImpl->UndefValueConstants.getOrCreate(Ty, 0);
1033 // destroyConstant - Remove the constant from the constant table.
1035 void UndefValue::destroyConstant() {
1036 getType()->getContext().pImpl->UndefValueConstants.remove(this);
1037 destroyConstantImpl();
1040 //---- BlockAddress::get() implementation.
1043 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1044 assert(BB->getParent() != 0 && "Block must have a parent");
1045 return get(BB->getParent(), BB);
1048 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1050 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1052 BA = new BlockAddress(F, BB);
1054 assert(BA->getFunction() == F && "Basic block moved between functions");
1058 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1059 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1063 BB->AdjustBlockAddressRefCount(1);
1067 // destroyConstant - Remove the constant from the constant table.
1069 void BlockAddress::destroyConstant() {
1070 getFunction()->getType()->getContext().pImpl
1071 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1072 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1073 destroyConstantImpl();
1076 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1077 // This could be replacing either the Basic Block or the Function. In either
1078 // case, we have to remove the map entry.
1079 Function *NewF = getFunction();
1080 BasicBlock *NewBB = getBasicBlock();
1083 NewF = cast<Function>(To);
1085 NewBB = cast<BasicBlock>(To);
1087 // See if the 'new' entry already exists, if not, just update this in place
1088 // and return early.
1089 BlockAddress *&NewBA =
1090 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1092 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1094 // Remove the old entry, this can't cause the map to rehash (just a
1095 // tombstone will get added).
1096 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1099 setOperand(0, NewF);
1100 setOperand(1, NewBB);
1101 getBasicBlock()->AdjustBlockAddressRefCount(1);
1105 // Otherwise, I do need to replace this with an existing value.
1106 assert(NewBA != this && "I didn't contain From!");
1108 // Everyone using this now uses the replacement.
1109 uncheckedReplaceAllUsesWith(NewBA);
1114 //---- ConstantExpr::get() implementations.
1117 /// This is a utility function to handle folding of casts and lookup of the
1118 /// cast in the ExprConstants map. It is used by the various get* methods below.
1119 static inline Constant *getFoldedCast(
1120 Instruction::CastOps opc, Constant *C, const Type *Ty) {
1121 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1122 // Fold a few common cases
1123 if (Constant *FC = ConstantFoldCastInstruction(Ty->getContext(), opc, C, Ty))
1126 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1128 // Look up the constant in the table first to ensure uniqueness
1129 std::vector<Constant*> argVec(1, C);
1130 ExprMapKeyType Key(opc, argVec);
1132 // Implicitly locked.
1133 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1136 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, const Type *Ty) {
1137 Instruction::CastOps opc = Instruction::CastOps(oc);
1138 assert(Instruction::isCast(opc) && "opcode out of range");
1139 assert(C && Ty && "Null arguments to getCast");
1140 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1144 llvm_unreachable("Invalid cast opcode");
1146 case Instruction::Trunc: return getTrunc(C, Ty);
1147 case Instruction::ZExt: return getZExt(C, Ty);
1148 case Instruction::SExt: return getSExt(C, Ty);
1149 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1150 case Instruction::FPExt: return getFPExtend(C, Ty);
1151 case Instruction::UIToFP: return getUIToFP(C, Ty);
1152 case Instruction::SIToFP: return getSIToFP(C, Ty);
1153 case Instruction::FPToUI: return getFPToUI(C, Ty);
1154 case Instruction::FPToSI: return getFPToSI(C, Ty);
1155 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1156 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1157 case Instruction::BitCast: return getBitCast(C, Ty);
1162 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, const Type *Ty) {
1163 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1164 return getCast(Instruction::BitCast, C, Ty);
1165 return getCast(Instruction::ZExt, C, Ty);
1168 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, const Type *Ty) {
1169 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1170 return getCast(Instruction::BitCast, C, Ty);
1171 return getCast(Instruction::SExt, C, Ty);
1174 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, const Type *Ty) {
1175 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1176 return getCast(Instruction::BitCast, C, Ty);
1177 return getCast(Instruction::Trunc, C, Ty);
1180 Constant *ConstantExpr::getPointerCast(Constant *S, const Type *Ty) {
1181 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1182 assert((Ty->isInteger() || isa<PointerType>(Ty)) && "Invalid cast");
1184 if (Ty->isInteger())
1185 return getCast(Instruction::PtrToInt, S, Ty);
1186 return getCast(Instruction::BitCast, S, Ty);
1189 Constant *ConstantExpr::getIntegerCast(Constant *C, const Type *Ty,
1191 assert(C->getType()->isIntOrIntVector() &&
1192 Ty->isIntOrIntVector() && "Invalid cast");
1193 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1194 unsigned DstBits = Ty->getScalarSizeInBits();
1195 Instruction::CastOps opcode =
1196 (SrcBits == DstBits ? Instruction::BitCast :
1197 (SrcBits > DstBits ? Instruction::Trunc :
1198 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1199 return getCast(opcode, C, Ty);
1202 Constant *ConstantExpr::getFPCast(Constant *C, const Type *Ty) {
1203 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1205 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1206 unsigned DstBits = Ty->getScalarSizeInBits();
1207 if (SrcBits == DstBits)
1208 return C; // Avoid a useless cast
1209 Instruction::CastOps opcode =
1210 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1211 return getCast(opcode, C, Ty);
1214 Constant *ConstantExpr::getTrunc(Constant *C, const Type *Ty) {
1216 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1217 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1219 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1220 assert(C->getType()->isIntOrIntVector() && "Trunc operand must be integer");
1221 assert(Ty->isIntOrIntVector() && "Trunc produces only integral");
1222 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1223 "SrcTy must be larger than DestTy for Trunc!");
1225 return getFoldedCast(Instruction::Trunc, C, Ty);
1228 Constant *ConstantExpr::getSExt(Constant *C, const Type *Ty) {
1230 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1231 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1233 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1234 assert(C->getType()->isIntOrIntVector() && "SExt operand must be integral");
1235 assert(Ty->isIntOrIntVector() && "SExt produces only integer");
1236 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1237 "SrcTy must be smaller than DestTy for SExt!");
1239 return getFoldedCast(Instruction::SExt, C, Ty);
1242 Constant *ConstantExpr::getZExt(Constant *C, const Type *Ty) {
1244 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1245 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1247 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1248 assert(C->getType()->isIntOrIntVector() && "ZEXt operand must be integral");
1249 assert(Ty->isIntOrIntVector() && "ZExt produces only integer");
1250 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1251 "SrcTy must be smaller than DestTy for ZExt!");
1253 return getFoldedCast(Instruction::ZExt, C, Ty);
1256 Constant *ConstantExpr::getFPTrunc(Constant *C, const Type *Ty) {
1258 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1259 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1261 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1262 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1263 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1264 "This is an illegal floating point truncation!");
1265 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1268 Constant *ConstantExpr::getFPExtend(Constant *C, const Type *Ty) {
1270 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1271 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1273 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1274 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
1275 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1276 "This is an illegal floating point extension!");
1277 return getFoldedCast(Instruction::FPExt, C, Ty);
1280 Constant *ConstantExpr::getUIToFP(Constant *C, const Type *Ty) {
1282 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1283 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1285 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1286 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1287 "This is an illegal uint to floating point cast!");
1288 return getFoldedCast(Instruction::UIToFP, C, Ty);
1291 Constant *ConstantExpr::getSIToFP(Constant *C, const Type *Ty) {
1293 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1294 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1296 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1297 assert(C->getType()->isIntOrIntVector() && Ty->isFPOrFPVector() &&
1298 "This is an illegal sint to floating point cast!");
1299 return getFoldedCast(Instruction::SIToFP, C, Ty);
1302 Constant *ConstantExpr::getFPToUI(Constant *C, const Type *Ty) {
1304 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1305 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1307 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1308 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1309 "This is an illegal floating point to uint cast!");
1310 return getFoldedCast(Instruction::FPToUI, C, Ty);
1313 Constant *ConstantExpr::getFPToSI(Constant *C, const Type *Ty) {
1315 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1316 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1318 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1319 assert(C->getType()->isFPOrFPVector() && Ty->isIntOrIntVector() &&
1320 "This is an illegal floating point to sint cast!");
1321 return getFoldedCast(Instruction::FPToSI, C, Ty);
1324 Constant *ConstantExpr::getPtrToInt(Constant *C, const Type *DstTy) {
1325 assert(isa<PointerType>(C->getType()) && "PtrToInt source must be pointer");
1326 assert(DstTy->isInteger() && "PtrToInt destination must be integral");
1327 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1330 Constant *ConstantExpr::getIntToPtr(Constant *C, const Type *DstTy) {
1331 assert(C->getType()->isInteger() && "IntToPtr source must be integral");
1332 assert(isa<PointerType>(DstTy) && "IntToPtr destination must be a pointer");
1333 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1336 Constant *ConstantExpr::getBitCast(Constant *C, const Type *DstTy) {
1337 // BitCast implies a no-op cast of type only. No bits change. However, you
1338 // can't cast pointers to anything but pointers.
1340 const Type *SrcTy = C->getType();
1341 assert((isa<PointerType>(SrcTy) == isa<PointerType>(DstTy)) &&
1342 "BitCast cannot cast pointer to non-pointer and vice versa");
1344 // Now we know we're not dealing with mismatched pointer casts (ptr->nonptr
1345 // or nonptr->ptr). For all the other types, the cast is okay if source and
1346 // destination bit widths are identical.
1347 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1348 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1350 assert(SrcBitSize == DstBitSize && "BitCast requires types of same width");
1352 // It is common to ask for a bitcast of a value to its own type, handle this
1354 if (C->getType() == DstTy) return C;
1356 return getFoldedCast(Instruction::BitCast, C, DstTy);
1359 Constant *ConstantExpr::getTy(const Type *ReqTy, unsigned Opcode,
1360 Constant *C1, Constant *C2,
1362 // Check the operands for consistency first
1363 assert(Opcode >= Instruction::BinaryOpsBegin &&
1364 Opcode < Instruction::BinaryOpsEnd &&
1365 "Invalid opcode in binary constant expression");
1366 assert(C1->getType() == C2->getType() &&
1367 "Operand types in binary constant expression should match");
1369 if (ReqTy == C1->getType() || ReqTy == Type::getInt1Ty(ReqTy->getContext()))
1370 if (Constant *FC = ConstantFoldBinaryInstruction(ReqTy->getContext(),
1372 return FC; // Fold a few common cases...
1374 std::vector<Constant*> argVec(1, C1); argVec.push_back(C2);
1375 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1377 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1379 // Implicitly locked.
1380 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1383 Constant *ConstantExpr::getCompareTy(unsigned short predicate,
1384 Constant *C1, Constant *C2) {
1385 switch (predicate) {
1386 default: llvm_unreachable("Invalid CmpInst predicate");
1387 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1388 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1389 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1390 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1391 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1392 case CmpInst::FCMP_TRUE:
1393 return getFCmp(predicate, C1, C2);
1395 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1396 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1397 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1398 case CmpInst::ICMP_SLE:
1399 return getICmp(predicate, C1, C2);
1403 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1405 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1406 if (C1->getType()->isFPOrFPVector()) {
1407 if (Opcode == Instruction::Add) Opcode = Instruction::FAdd;
1408 else if (Opcode == Instruction::Sub) Opcode = Instruction::FSub;
1409 else if (Opcode == Instruction::Mul) Opcode = Instruction::FMul;
1413 case Instruction::Add:
1414 case Instruction::Sub:
1415 case Instruction::Mul:
1416 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1417 assert(C1->getType()->isIntOrIntVector() &&
1418 "Tried to create an integer operation on a non-integer type!");
1420 case Instruction::FAdd:
1421 case Instruction::FSub:
1422 case Instruction::FMul:
1423 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1424 assert(C1->getType()->isFPOrFPVector() &&
1425 "Tried to create a floating-point operation on a "
1426 "non-floating-point type!");
1428 case Instruction::UDiv:
1429 case Instruction::SDiv:
1430 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1431 assert(C1->getType()->isIntOrIntVector() &&
1432 "Tried to create an arithmetic operation on a non-arithmetic type!");
1434 case Instruction::FDiv:
1435 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1436 assert(C1->getType()->isFPOrFPVector() &&
1437 "Tried to create an arithmetic operation on a non-arithmetic type!");
1439 case Instruction::URem:
1440 case Instruction::SRem:
1441 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1442 assert(C1->getType()->isIntOrIntVector() &&
1443 "Tried to create an arithmetic operation on a non-arithmetic type!");
1445 case Instruction::FRem:
1446 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1447 assert(C1->getType()->isFPOrFPVector() &&
1448 "Tried to create an arithmetic operation on a non-arithmetic type!");
1450 case Instruction::And:
1451 case Instruction::Or:
1452 case Instruction::Xor:
1453 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1454 assert(C1->getType()->isIntOrIntVector() &&
1455 "Tried to create a logical operation on a non-integral type!");
1457 case Instruction::Shl:
1458 case Instruction::LShr:
1459 case Instruction::AShr:
1460 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1461 assert(C1->getType()->isIntOrIntVector() &&
1462 "Tried to create a shift operation on a non-integer type!");
1469 return getTy(C1->getType(), Opcode, C1, C2, Flags);
1472 Constant* ConstantExpr::getSizeOf(const Type* Ty) {
1473 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1474 // Note that a non-inbounds gep is used, as null isn't within any object.
1475 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1476 Constant *GEP = getGetElementPtr(
1477 Constant::getNullValue(PointerType::getUnqual(Ty)), &GEPIdx, 1);
1478 return getCast(Instruction::PtrToInt, GEP,
1479 Type::getInt64Ty(Ty->getContext()));
1482 Constant* ConstantExpr::getAlignOf(const Type* Ty) {
1483 // alignof is implemented as: (i64) gep ({i8,Ty}*)null, 0, 1
1484 // Note that a non-inbounds gep is used, as null isn't within any object.
1485 const Type *AligningTy = StructType::get(Ty->getContext(),
1486 Type::getInt8Ty(Ty->getContext()), Ty, NULL);
1487 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1488 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 0);
1489 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1490 Constant *Indices[2] = { Zero, One };
1491 Constant *GEP = getGetElementPtr(NullPtr, Indices, 2);
1492 return getCast(Instruction::PtrToInt, GEP,
1493 Type::getInt32Ty(Ty->getContext()));
1496 Constant* ConstantExpr::getOffsetOf(const StructType* STy, unsigned FieldNo) {
1497 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1498 // Note that a non-inbounds gep is used, as null isn't within any object.
1499 Constant *GEPIdx[] = {
1500 ConstantInt::get(Type::getInt64Ty(STy->getContext()), 0),
1501 ConstantInt::get(Type::getInt32Ty(STy->getContext()), FieldNo)
1503 Constant *GEP = getGetElementPtr(
1504 Constant::getNullValue(PointerType::getUnqual(STy)), GEPIdx, 2);
1505 return getCast(Instruction::PtrToInt, GEP,
1506 Type::getInt64Ty(STy->getContext()));
1509 Constant *ConstantExpr::getCompare(unsigned short pred,
1510 Constant *C1, Constant *C2) {
1511 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1512 return getCompareTy(pred, C1, C2);
1515 Constant *ConstantExpr::getSelectTy(const Type *ReqTy, Constant *C,
1516 Constant *V1, Constant *V2) {
1517 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1519 if (ReqTy == V1->getType())
1520 if (Constant *SC = ConstantFoldSelectInstruction(
1521 ReqTy->getContext(), C, V1, V2))
1522 return SC; // Fold common cases
1524 std::vector<Constant*> argVec(3, C);
1527 ExprMapKeyType Key(Instruction::Select, argVec);
1529 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1531 // Implicitly locked.
1532 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1535 Constant *ConstantExpr::getGetElementPtrTy(const Type *ReqTy, Constant *C,
1538 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1540 cast<PointerType>(ReqTy)->getElementType() &&
1541 "GEP indices invalid!");
1543 if (Constant *FC = ConstantFoldGetElementPtr(
1544 ReqTy->getContext(), C, /*inBounds=*/false,
1545 (Constant**)Idxs, NumIdx))
1546 return FC; // Fold a few common cases...
1548 assert(isa<PointerType>(C->getType()) &&
1549 "Non-pointer type for constant GetElementPtr expression");
1550 // Look up the constant in the table first to ensure uniqueness
1551 std::vector<Constant*> ArgVec;
1552 ArgVec.reserve(NumIdx+1);
1553 ArgVec.push_back(C);
1554 for (unsigned i = 0; i != NumIdx; ++i)
1555 ArgVec.push_back(cast<Constant>(Idxs[i]));
1556 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec);
1558 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1560 // Implicitly locked.
1561 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1564 Constant *ConstantExpr::getInBoundsGetElementPtrTy(const Type *ReqTy,
1568 assert(GetElementPtrInst::getIndexedType(C->getType(), Idxs,
1570 cast<PointerType>(ReqTy)->getElementType() &&
1571 "GEP indices invalid!");
1573 if (Constant *FC = ConstantFoldGetElementPtr(
1574 ReqTy->getContext(), C, /*inBounds=*/true,
1575 (Constant**)Idxs, NumIdx))
1576 return FC; // Fold a few common cases...
1578 assert(isa<PointerType>(C->getType()) &&
1579 "Non-pointer type for constant GetElementPtr expression");
1580 // Look up the constant in the table first to ensure uniqueness
1581 std::vector<Constant*> ArgVec;
1582 ArgVec.reserve(NumIdx+1);
1583 ArgVec.push_back(C);
1584 for (unsigned i = 0; i != NumIdx; ++i)
1585 ArgVec.push_back(cast<Constant>(Idxs[i]));
1586 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1587 GEPOperator::IsInBounds);
1589 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1591 // Implicitly locked.
1592 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1595 Constant *ConstantExpr::getGetElementPtr(Constant *C, Value* const *Idxs,
1597 // Get the result type of the getelementptr!
1599 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1600 assert(Ty && "GEP indices invalid!");
1601 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1602 return getGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1605 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1608 // Get the result type of the getelementptr!
1610 GetElementPtrInst::getIndexedType(C->getType(), Idxs, Idxs+NumIdx);
1611 assert(Ty && "GEP indices invalid!");
1612 unsigned As = cast<PointerType>(C->getType())->getAddressSpace();
1613 return getInBoundsGetElementPtrTy(PointerType::get(Ty, As), C, Idxs, NumIdx);
1616 Constant *ConstantExpr::getGetElementPtr(Constant *C, Constant* const *Idxs,
1618 return getGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1621 Constant *ConstantExpr::getInBoundsGetElementPtr(Constant *C,
1622 Constant* const *Idxs,
1624 return getInBoundsGetElementPtr(C, (Value* const *)Idxs, NumIdx);
1628 ConstantExpr::getICmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1629 assert(LHS->getType() == RHS->getType());
1630 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1631 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1633 if (Constant *FC = ConstantFoldCompareInstruction(
1634 LHS->getContext(), pred, LHS, RHS))
1635 return FC; // Fold a few common cases...
1637 // Look up the constant in the table first to ensure uniqueness
1638 std::vector<Constant*> ArgVec;
1639 ArgVec.push_back(LHS);
1640 ArgVec.push_back(RHS);
1641 // Get the key type with both the opcode and predicate
1642 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1644 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1646 // Implicitly locked.
1648 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1652 ConstantExpr::getFCmp(unsigned short pred, Constant* LHS, Constant* RHS) {
1653 assert(LHS->getType() == RHS->getType());
1654 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1656 if (Constant *FC = ConstantFoldCompareInstruction(
1657 LHS->getContext(), pred, LHS, RHS))
1658 return FC; // Fold a few common cases...
1660 // Look up the constant in the table first to ensure uniqueness
1661 std::vector<Constant*> ArgVec;
1662 ArgVec.push_back(LHS);
1663 ArgVec.push_back(RHS);
1664 // Get the key type with both the opcode and predicate
1665 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1667 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1669 // Implicitly locked.
1671 pImpl->ExprConstants.getOrCreate(Type::getInt1Ty(LHS->getContext()), Key);
1674 Constant *ConstantExpr::getExtractElementTy(const Type *ReqTy, Constant *Val,
1676 if (Constant *FC = ConstantFoldExtractElementInstruction(
1677 ReqTy->getContext(), Val, Idx))
1678 return FC; // Fold a few common cases...
1679 // Look up the constant in the table first to ensure uniqueness
1680 std::vector<Constant*> ArgVec(1, Val);
1681 ArgVec.push_back(Idx);
1682 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1684 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1686 // Implicitly locked.
1687 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1690 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1691 assert(isa<VectorType>(Val->getType()) &&
1692 "Tried to create extractelement operation on non-vector type!");
1693 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1694 "Extractelement index must be i32 type!");
1695 return getExtractElementTy(cast<VectorType>(Val->getType())->getElementType(),
1699 Constant *ConstantExpr::getInsertElementTy(const Type *ReqTy, Constant *Val,
1700 Constant *Elt, Constant *Idx) {
1701 if (Constant *FC = ConstantFoldInsertElementInstruction(
1702 ReqTy->getContext(), Val, Elt, Idx))
1703 return FC; // Fold a few common cases...
1704 // Look up the constant in the table first to ensure uniqueness
1705 std::vector<Constant*> ArgVec(1, Val);
1706 ArgVec.push_back(Elt);
1707 ArgVec.push_back(Idx);
1708 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1710 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1712 // Implicitly locked.
1713 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1716 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1718 assert(isa<VectorType>(Val->getType()) &&
1719 "Tried to create insertelement operation on non-vector type!");
1720 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType()
1721 && "Insertelement types must match!");
1722 assert(Idx->getType() == Type::getInt32Ty(Val->getContext()) &&
1723 "Insertelement index must be i32 type!");
1724 return getInsertElementTy(Val->getType(), Val, Elt, Idx);
1727 Constant *ConstantExpr::getShuffleVectorTy(const Type *ReqTy, Constant *V1,
1728 Constant *V2, Constant *Mask) {
1729 if (Constant *FC = ConstantFoldShuffleVectorInstruction(
1730 ReqTy->getContext(), V1, V2, Mask))
1731 return FC; // Fold a few common cases...
1732 // Look up the constant in the table first to ensure uniqueness
1733 std::vector<Constant*> ArgVec(1, V1);
1734 ArgVec.push_back(V2);
1735 ArgVec.push_back(Mask);
1736 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1738 LLVMContextImpl *pImpl = ReqTy->getContext().pImpl;
1740 // Implicitly locked.
1741 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1744 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1746 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1747 "Invalid shuffle vector constant expr operands!");
1749 unsigned NElts = cast<VectorType>(Mask->getType())->getNumElements();
1750 const Type *EltTy = cast<VectorType>(V1->getType())->getElementType();
1751 const Type *ShufTy = VectorType::get(EltTy, NElts);
1752 return getShuffleVectorTy(ShufTy, V1, V2, Mask);
1755 Constant *ConstantExpr::getInsertValueTy(const Type *ReqTy, Constant *Agg,
1757 const unsigned *Idxs, unsigned NumIdx) {
1758 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1759 Idxs+NumIdx) == Val->getType() &&
1760 "insertvalue indices invalid!");
1761 assert(Agg->getType() == ReqTy &&
1762 "insertvalue type invalid!");
1763 assert(Agg->getType()->isFirstClassType() &&
1764 "Non-first-class type for constant InsertValue expression");
1765 Constant *FC = ConstantFoldInsertValueInstruction(
1766 ReqTy->getContext(), Agg, Val, Idxs, NumIdx);
1767 assert(FC && "InsertValue constant expr couldn't be folded!");
1771 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1772 const unsigned *IdxList, unsigned NumIdx) {
1773 assert(Agg->getType()->isFirstClassType() &&
1774 "Tried to create insertelement operation on non-first-class type!");
1776 const Type *ReqTy = Agg->getType();
1779 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1781 assert(ValTy == Val->getType() && "insertvalue indices invalid!");
1782 return getInsertValueTy(ReqTy, Agg, Val, IdxList, NumIdx);
1785 Constant *ConstantExpr::getExtractValueTy(const Type *ReqTy, Constant *Agg,
1786 const unsigned *Idxs, unsigned NumIdx) {
1787 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs,
1788 Idxs+NumIdx) == ReqTy &&
1789 "extractvalue indices invalid!");
1790 assert(Agg->getType()->isFirstClassType() &&
1791 "Non-first-class type for constant extractvalue expression");
1792 Constant *FC = ConstantFoldExtractValueInstruction(
1793 ReqTy->getContext(), Agg, Idxs, NumIdx);
1794 assert(FC && "ExtractValue constant expr couldn't be folded!");
1798 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1799 const unsigned *IdxList, unsigned NumIdx) {
1800 assert(Agg->getType()->isFirstClassType() &&
1801 "Tried to create extractelement operation on non-first-class type!");
1804 ExtractValueInst::getIndexedType(Agg->getType(), IdxList, IdxList+NumIdx);
1805 assert(ReqTy && "extractvalue indices invalid!");
1806 return getExtractValueTy(ReqTy, Agg, IdxList, NumIdx);
1809 Constant* ConstantExpr::getNeg(Constant* C) {
1810 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1811 if (C->getType()->isFPOrFPVector())
1813 assert(C->getType()->isIntOrIntVector() &&
1814 "Cannot NEG a nonintegral value!");
1815 return get(Instruction::Sub,
1816 ConstantFP::getZeroValueForNegation(C->getType()),
1820 Constant* ConstantExpr::getFNeg(Constant* C) {
1821 assert(C->getType()->isFPOrFPVector() &&
1822 "Cannot FNEG a non-floating-point value!");
1823 return get(Instruction::FSub,
1824 ConstantFP::getZeroValueForNegation(C->getType()),
1828 Constant* ConstantExpr::getNot(Constant* C) {
1829 assert(C->getType()->isIntOrIntVector() &&
1830 "Cannot NOT a nonintegral value!");
1831 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1834 Constant* ConstantExpr::getAdd(Constant* C1, Constant* C2) {
1835 return get(Instruction::Add, C1, C2);
1838 Constant* ConstantExpr::getFAdd(Constant* C1, Constant* C2) {
1839 return get(Instruction::FAdd, C1, C2);
1842 Constant* ConstantExpr::getSub(Constant* C1, Constant* C2) {
1843 return get(Instruction::Sub, C1, C2);
1846 Constant* ConstantExpr::getFSub(Constant* C1, Constant* C2) {
1847 return get(Instruction::FSub, C1, C2);
1850 Constant* ConstantExpr::getMul(Constant* C1, Constant* C2) {
1851 return get(Instruction::Mul, C1, C2);
1854 Constant* ConstantExpr::getFMul(Constant* C1, Constant* C2) {
1855 return get(Instruction::FMul, C1, C2);
1858 Constant* ConstantExpr::getUDiv(Constant* C1, Constant* C2) {
1859 return get(Instruction::UDiv, C1, C2);
1862 Constant* ConstantExpr::getSDiv(Constant* C1, Constant* C2) {
1863 return get(Instruction::SDiv, C1, C2);
1866 Constant* ConstantExpr::getFDiv(Constant* C1, Constant* C2) {
1867 return get(Instruction::FDiv, C1, C2);
1870 Constant* ConstantExpr::getURem(Constant* C1, Constant* C2) {
1871 return get(Instruction::URem, C1, C2);
1874 Constant* ConstantExpr::getSRem(Constant* C1, Constant* C2) {
1875 return get(Instruction::SRem, C1, C2);
1878 Constant* ConstantExpr::getFRem(Constant* C1, Constant* C2) {
1879 return get(Instruction::FRem, C1, C2);
1882 Constant* ConstantExpr::getAnd(Constant* C1, Constant* C2) {
1883 return get(Instruction::And, C1, C2);
1886 Constant* ConstantExpr::getOr(Constant* C1, Constant* C2) {
1887 return get(Instruction::Or, C1, C2);
1890 Constant* ConstantExpr::getXor(Constant* C1, Constant* C2) {
1891 return get(Instruction::Xor, C1, C2);
1894 Constant* ConstantExpr::getShl(Constant* C1, Constant* C2) {
1895 return get(Instruction::Shl, C1, C2);
1898 Constant* ConstantExpr::getLShr(Constant* C1, Constant* C2) {
1899 return get(Instruction::LShr, C1, C2);
1902 Constant* ConstantExpr::getAShr(Constant* C1, Constant* C2) {
1903 return get(Instruction::AShr, C1, C2);
1906 // destroyConstant - Remove the constant from the constant table...
1908 void ConstantExpr::destroyConstant() {
1909 // Implicitly locked.
1910 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
1911 pImpl->ExprConstants.remove(this);
1912 destroyConstantImpl();
1915 const char *ConstantExpr::getOpcodeName() const {
1916 return Instruction::getOpcodeName(getOpcode());
1919 //===----------------------------------------------------------------------===//
1920 // replaceUsesOfWithOnConstant implementations
1922 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
1923 /// 'From' to be uses of 'To'. This must update the uniquing data structures
1926 /// Note that we intentionally replace all uses of From with To here. Consider
1927 /// a large array that uses 'From' 1000 times. By handling this case all here,
1928 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
1929 /// single invocation handles all 1000 uses. Handling them one at a time would
1930 /// work, but would be really slow because it would have to unique each updated
1933 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
1935 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
1936 Constant *ToC = cast<Constant>(To);
1938 LLVMContext &Context = getType()->getContext();
1939 LLVMContextImpl *pImpl = Context.pImpl;
1941 std::pair<LLVMContextImpl::ArrayConstantsTy::MapKey, ConstantArray*> Lookup;
1942 Lookup.first.first = getType();
1943 Lookup.second = this;
1945 std::vector<Constant*> &Values = Lookup.first.second;
1946 Values.reserve(getNumOperands()); // Build replacement array.
1948 // Fill values with the modified operands of the constant array. Also,
1949 // compute whether this turns into an all-zeros array.
1950 bool isAllZeros = false;
1951 unsigned NumUpdated = 0;
1952 if (!ToC->isNullValue()) {
1953 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
1954 Constant *Val = cast<Constant>(O->get());
1959 Values.push_back(Val);
1963 for (Use *O = OperandList, *E = OperandList+getNumOperands();O != E; ++O) {
1964 Constant *Val = cast<Constant>(O->get());
1969 Values.push_back(Val);
1970 if (isAllZeros) isAllZeros = Val->isNullValue();
1974 Constant *Replacement = 0;
1976 Replacement = ConstantAggregateZero::get(getType());
1978 // Check to see if we have this array type already.
1980 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
1981 pImpl->ArrayConstants.InsertOrGetItem(Lookup, Exists);
1984 Replacement = I->second;
1986 // Okay, the new shape doesn't exist in the system yet. Instead of
1987 // creating a new constant array, inserting it, replaceallusesof'ing the
1988 // old with the new, then deleting the old... just update the current one
1990 pImpl->ArrayConstants.MoveConstantToNewSlot(this, I);
1992 // Update to the new value. Optimize for the case when we have a single
1993 // operand that we're changing, but handle bulk updates efficiently.
1994 if (NumUpdated == 1) {
1995 unsigned OperandToUpdate = U - OperandList;
1996 assert(getOperand(OperandToUpdate) == From &&
1997 "ReplaceAllUsesWith broken!");
1998 setOperand(OperandToUpdate, ToC);
2000 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2001 if (getOperand(i) == From)
2008 // Otherwise, I do need to replace this with an existing value.
2009 assert(Replacement != this && "I didn't contain From!");
2011 // Everyone using this now uses the replacement.
2012 uncheckedReplaceAllUsesWith(Replacement);
2014 // Delete the old constant!
2018 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2020 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2021 Constant *ToC = cast<Constant>(To);
2023 unsigned OperandToUpdate = U-OperandList;
2024 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2026 std::pair<LLVMContextImpl::StructConstantsTy::MapKey, ConstantStruct*> Lookup;
2027 Lookup.first.first = getType();
2028 Lookup.second = this;
2029 std::vector<Constant*> &Values = Lookup.first.second;
2030 Values.reserve(getNumOperands()); // Build replacement struct.
2033 // Fill values with the modified operands of the constant struct. Also,
2034 // compute whether this turns into an all-zeros struct.
2035 bool isAllZeros = false;
2036 if (!ToC->isNullValue()) {
2037 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2038 Values.push_back(cast<Constant>(O->get()));
2041 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2042 Constant *Val = cast<Constant>(O->get());
2043 Values.push_back(Val);
2044 if (isAllZeros) isAllZeros = Val->isNullValue();
2047 Values[OperandToUpdate] = ToC;
2049 LLVMContext &Context = getType()->getContext();
2050 LLVMContextImpl *pImpl = Context.pImpl;
2052 Constant *Replacement = 0;
2054 Replacement = ConstantAggregateZero::get(getType());
2056 // Check to see if we have this array type already.
2058 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2059 pImpl->StructConstants.InsertOrGetItem(Lookup, Exists);
2062 Replacement = I->second;
2064 // Okay, the new shape doesn't exist in the system yet. Instead of
2065 // creating a new constant struct, inserting it, replaceallusesof'ing the
2066 // old with the new, then deleting the old... just update the current one
2068 pImpl->StructConstants.MoveConstantToNewSlot(this, I);
2070 // Update to the new value.
2071 setOperand(OperandToUpdate, ToC);
2076 assert(Replacement != this && "I didn't contain From!");
2078 // Everyone using this now uses the replacement.
2079 uncheckedReplaceAllUsesWith(Replacement);
2081 // Delete the old constant!
2085 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2087 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2089 std::vector<Constant*> Values;
2090 Values.reserve(getNumOperands()); // Build replacement array...
2091 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2092 Constant *Val = getOperand(i);
2093 if (Val == From) Val = cast<Constant>(To);
2094 Values.push_back(Val);
2097 Constant *Replacement = get(getType(), Values);
2098 assert(Replacement != this && "I didn't contain From!");
2100 // Everyone using this now uses the replacement.
2101 uncheckedReplaceAllUsesWith(Replacement);
2103 // Delete the old constant!
2107 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2109 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2110 Constant *To = cast<Constant>(ToV);
2112 Constant *Replacement = 0;
2113 if (getOpcode() == Instruction::GetElementPtr) {
2114 SmallVector<Constant*, 8> Indices;
2115 Constant *Pointer = getOperand(0);
2116 Indices.reserve(getNumOperands()-1);
2117 if (Pointer == From) Pointer = To;
2119 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
2120 Constant *Val = getOperand(i);
2121 if (Val == From) Val = To;
2122 Indices.push_back(Val);
2124 Replacement = ConstantExpr::getGetElementPtr(Pointer,
2125 &Indices[0], Indices.size());
2126 } else if (getOpcode() == Instruction::ExtractValue) {
2127 Constant *Agg = getOperand(0);
2128 if (Agg == From) Agg = To;
2130 const SmallVector<unsigned, 4> &Indices = getIndices();
2131 Replacement = ConstantExpr::getExtractValue(Agg,
2132 &Indices[0], Indices.size());
2133 } else if (getOpcode() == Instruction::InsertValue) {
2134 Constant *Agg = getOperand(0);
2135 Constant *Val = getOperand(1);
2136 if (Agg == From) Agg = To;
2137 if (Val == From) Val = To;
2139 const SmallVector<unsigned, 4> &Indices = getIndices();
2140 Replacement = ConstantExpr::getInsertValue(Agg, Val,
2141 &Indices[0], Indices.size());
2142 } else if (isCast()) {
2143 assert(getOperand(0) == From && "Cast only has one use!");
2144 Replacement = ConstantExpr::getCast(getOpcode(), To, getType());
2145 } else if (getOpcode() == Instruction::Select) {
2146 Constant *C1 = getOperand(0);
2147 Constant *C2 = getOperand(1);
2148 Constant *C3 = getOperand(2);
2149 if (C1 == From) C1 = To;
2150 if (C2 == From) C2 = To;
2151 if (C3 == From) C3 = To;
2152 Replacement = ConstantExpr::getSelect(C1, C2, C3);
2153 } else if (getOpcode() == Instruction::ExtractElement) {
2154 Constant *C1 = getOperand(0);
2155 Constant *C2 = getOperand(1);
2156 if (C1 == From) C1 = To;
2157 if (C2 == From) C2 = To;
2158 Replacement = ConstantExpr::getExtractElement(C1, C2);
2159 } else if (getOpcode() == Instruction::InsertElement) {
2160 Constant *C1 = getOperand(0);
2161 Constant *C2 = getOperand(1);
2162 Constant *C3 = getOperand(1);
2163 if (C1 == From) C1 = To;
2164 if (C2 == From) C2 = To;
2165 if (C3 == From) C3 = To;
2166 Replacement = ConstantExpr::getInsertElement(C1, C2, C3);
2167 } else if (getOpcode() == Instruction::ShuffleVector) {
2168 Constant *C1 = getOperand(0);
2169 Constant *C2 = getOperand(1);
2170 Constant *C3 = getOperand(2);
2171 if (C1 == From) C1 = To;
2172 if (C2 == From) C2 = To;
2173 if (C3 == From) C3 = To;
2174 Replacement = ConstantExpr::getShuffleVector(C1, C2, C3);
2175 } else if (isCompare()) {
2176 Constant *C1 = getOperand(0);
2177 Constant *C2 = getOperand(1);
2178 if (C1 == From) C1 = To;
2179 if (C2 == From) C2 = To;
2180 if (getOpcode() == Instruction::ICmp)
2181 Replacement = ConstantExpr::getICmp(getPredicate(), C1, C2);
2183 assert(getOpcode() == Instruction::FCmp);
2184 Replacement = ConstantExpr::getFCmp(getPredicate(), C1, C2);
2186 } else if (getNumOperands() == 2) {
2187 Constant *C1 = getOperand(0);
2188 Constant *C2 = getOperand(1);
2189 if (C1 == From) C1 = To;
2190 if (C2 == From) C2 = To;
2191 Replacement = ConstantExpr::get(getOpcode(), C1, C2, SubclassData);
2193 llvm_unreachable("Unknown ConstantExpr type!");
2197 assert(Replacement != this && "I didn't contain From!");
2199 // Everyone using this now uses the replacement.
2200 uncheckedReplaceAllUsesWith(Replacement);
2202 // Delete the old constant!