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/IR/Constants.h"
15 #include "ConstantFold.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GlobalValue.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 void Constant::anchor() { }
45 bool Constant::isNegativeZeroValue() const {
46 // Floating point values have an explicit -0.0 value.
47 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
48 return CFP->isZero() && CFP->isNegative();
50 // Otherwise, just use +0.0.
54 bool Constant::isZeroValue() const {
55 // Floating point values have an explicit -0.0 value.
56 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 // Otherwise, just use +0.0.
63 bool Constant::isNullValue() const {
65 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
69 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
70 return CFP->isZero() && !CFP->isNegative();
72 // constant zero is zero for aggregates and cpnull is null for pointers.
73 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
76 bool Constant::isAllOnesValue() const {
77 // Check for -1 integers
78 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
79 return CI->isMinusOne();
81 // Check for FP which are bitcasted from -1 integers
82 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
83 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
85 // Check for constant vectors which are splats of -1 values.
86 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
87 if (Constant *Splat = CV->getSplatValue())
88 return Splat->isAllOnesValue();
90 // Check for constant vectors which are splats of -1 values.
91 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
92 if (Constant *Splat = CV->getSplatValue())
93 return Splat->isAllOnesValue();
98 // Constructor to create a '0' constant of arbitrary type...
99 Constant *Constant::getNullValue(Type *Ty) {
100 switch (Ty->getTypeID()) {
101 case Type::IntegerTyID:
102 return ConstantInt::get(Ty, 0);
104 return ConstantFP::get(Ty->getContext(),
105 APFloat::getZero(APFloat::IEEEhalf));
106 case Type::FloatTyID:
107 return ConstantFP::get(Ty->getContext(),
108 APFloat::getZero(APFloat::IEEEsingle));
109 case Type::DoubleTyID:
110 return ConstantFP::get(Ty->getContext(),
111 APFloat::getZero(APFloat::IEEEdouble));
112 case Type::X86_FP80TyID:
113 return ConstantFP::get(Ty->getContext(),
114 APFloat::getZero(APFloat::x87DoubleExtended));
115 case Type::FP128TyID:
116 return ConstantFP::get(Ty->getContext(),
117 APFloat::getZero(APFloat::IEEEquad));
118 case Type::PPC_FP128TyID:
119 return ConstantFP::get(Ty->getContext(),
120 APFloat(APInt::getNullValue(128)));
121 case Type::PointerTyID:
122 return ConstantPointerNull::get(cast<PointerType>(Ty));
123 case Type::StructTyID:
124 case Type::ArrayTyID:
125 case Type::VectorTyID:
126 return ConstantAggregateZero::get(Ty);
128 // Function, Label, or Opaque type?
129 llvm_unreachable("Cannot create a null constant of that type!");
133 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
134 Type *ScalarTy = Ty->getScalarType();
136 // Create the base integer constant.
137 Constant *C = ConstantInt::get(Ty->getContext(), V);
139 // Convert an integer to a pointer, if necessary.
140 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
141 C = ConstantExpr::getIntToPtr(C, PTy);
143 // Broadcast a scalar to a vector, if necessary.
144 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
145 C = ConstantVector::getSplat(VTy->getNumElements(), C);
150 Constant *Constant::getAllOnesValue(Type *Ty) {
151 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
152 return ConstantInt::get(Ty->getContext(),
153 APInt::getAllOnesValue(ITy->getBitWidth()));
155 if (Ty->isFloatingPointTy()) {
156 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
157 !Ty->isPPC_FP128Ty());
158 return ConstantFP::get(Ty->getContext(), FL);
161 VectorType *VTy = cast<VectorType>(Ty);
162 return ConstantVector::getSplat(VTy->getNumElements(),
163 getAllOnesValue(VTy->getElementType()));
166 /// getAggregateElement - For aggregates (struct/array/vector) return the
167 /// constant that corresponds to the specified element if possible, or null if
168 /// not. This can return null if the element index is a ConstantExpr, or if
169 /// 'this' is a constant expr.
170 Constant *Constant::getAggregateElement(unsigned Elt) const {
171 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
172 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : 0;
174 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
175 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : 0;
177 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
178 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : 0;
180 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
181 return CAZ->getElementValue(Elt);
183 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
184 return UV->getElementValue(Elt);
186 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
187 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt) : 0;
191 Constant *Constant::getAggregateElement(Constant *Elt) const {
192 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
193 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
194 return getAggregateElement(CI->getZExtValue());
199 void Constant::destroyConstantImpl() {
200 // When a Constant is destroyed, there may be lingering
201 // references to the constant by other constants in the constant pool. These
202 // constants are implicitly dependent on the module that is being deleted,
203 // but they don't know that. Because we only find out when the CPV is
204 // deleted, we must now notify all of our users (that should only be
205 // Constants) that they are, in fact, invalid now and should be deleted.
207 while (!use_empty()) {
208 Value *V = use_back();
209 #ifndef NDEBUG // Only in -g mode...
210 if (!isa<Constant>(V)) {
211 dbgs() << "While deleting: " << *this
212 << "\n\nUse still stuck around after Def is destroyed: "
216 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
217 cast<Constant>(V)->destroyConstant();
219 // The constant should remove itself from our use list...
220 assert((use_empty() || use_back() != V) && "Constant not removed!");
223 // Value has no outstanding references it is safe to delete it now...
227 /// canTrap - Return true if evaluation of this constant could trap. This is
228 /// true for things like constant expressions that could divide by zero.
229 bool Constant::canTrap() const {
230 assert(getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
231 // The only thing that could possibly trap are constant exprs.
232 const ConstantExpr *CE = dyn_cast<ConstantExpr>(this);
233 if (!CE) return false;
235 // ConstantExpr traps if any operands can trap.
236 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
237 if (CE->getOperand(i)->canTrap())
240 // Otherwise, only specific operations can trap.
241 switch (CE->getOpcode()) {
244 case Instruction::UDiv:
245 case Instruction::SDiv:
246 case Instruction::FDiv:
247 case Instruction::URem:
248 case Instruction::SRem:
249 case Instruction::FRem:
250 // Div and rem can trap if the RHS is not known to be non-zero.
251 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
257 /// isThreadDependent - Return true if the value can vary between threads.
258 bool Constant::isThreadDependent() const {
259 SmallPtrSet<const Constant*, 64> Visited;
260 SmallVector<const Constant*, 64> WorkList;
261 WorkList.push_back(this);
262 Visited.insert(this);
264 while (!WorkList.empty()) {
265 const Constant *C = WorkList.pop_back_val();
267 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
268 if (GV->isThreadLocal())
272 for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I) {
273 const Constant *D = dyn_cast<Constant>(C->getOperand(I));
276 if (Visited.insert(D))
277 WorkList.push_back(D);
284 /// isConstantUsed - Return true if the constant has users other than constant
285 /// exprs and other dangling things.
286 bool Constant::isConstantUsed() const {
287 for (const_use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
288 const Constant *UC = dyn_cast<Constant>(*UI);
289 if (UC == 0 || isa<GlobalValue>(UC))
292 if (UC->isConstantUsed())
300 /// getRelocationInfo - This method classifies the entry according to
301 /// whether or not it may generate a relocation entry. This must be
302 /// conservative, so if it might codegen to a relocatable entry, it should say
303 /// so. The return values are:
305 /// NoRelocation: This constant pool entry is guaranteed to never have a
306 /// relocation applied to it (because it holds a simple constant like
308 /// LocalRelocation: This entry has relocations, but the entries are
309 /// guaranteed to be resolvable by the static linker, so the dynamic
310 /// linker will never see them.
311 /// GlobalRelocations: This entry may have arbitrary relocations.
313 /// FIXME: This really should not be in IR.
314 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
315 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
316 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
317 return LocalRelocation; // Local to this file/library.
318 return GlobalRelocations; // Global reference.
321 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
322 return BA->getFunction()->getRelocationInfo();
324 // While raw uses of blockaddress need to be relocated, differences between
325 // two of them don't when they are for labels in the same function. This is a
326 // common idiom when creating a table for the indirect goto extension, so we
327 // handle it efficiently here.
328 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
329 if (CE->getOpcode() == Instruction::Sub) {
330 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
331 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
333 LHS->getOpcode() == Instruction::PtrToInt &&
334 RHS->getOpcode() == Instruction::PtrToInt &&
335 isa<BlockAddress>(LHS->getOperand(0)) &&
336 isa<BlockAddress>(RHS->getOperand(0)) &&
337 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
338 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
342 PossibleRelocationsTy Result = NoRelocation;
343 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
344 Result = std::max(Result,
345 cast<Constant>(getOperand(i))->getRelocationInfo());
350 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
351 /// it. This involves recursively eliminating any dead users of the
353 static bool removeDeadUsersOfConstant(const Constant *C) {
354 if (isa<GlobalValue>(C)) return false; // Cannot remove this
356 while (!C->use_empty()) {
357 const Constant *User = dyn_cast<Constant>(C->use_back());
358 if (!User) return false; // Non-constant usage;
359 if (!removeDeadUsersOfConstant(User))
360 return false; // Constant wasn't dead
363 const_cast<Constant*>(C)->destroyConstant();
368 /// removeDeadConstantUsers - If there are any dead constant users dangling
369 /// off of this constant, remove them. This method is useful for clients
370 /// that want to check to see if a global is unused, but don't want to deal
371 /// with potentially dead constants hanging off of the globals.
372 void Constant::removeDeadConstantUsers() const {
373 Value::const_use_iterator I = use_begin(), E = use_end();
374 Value::const_use_iterator LastNonDeadUser = E;
376 const Constant *User = dyn_cast<Constant>(*I);
383 if (!removeDeadUsersOfConstant(User)) {
384 // If the constant wasn't dead, remember that this was the last live use
385 // and move on to the next constant.
391 // If the constant was dead, then the iterator is invalidated.
392 if (LastNonDeadUser == E) {
404 //===----------------------------------------------------------------------===//
406 //===----------------------------------------------------------------------===//
408 void ConstantInt::anchor() { }
410 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
411 : Constant(Ty, ConstantIntVal, 0, 0), Val(V) {
412 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
415 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
416 LLVMContextImpl *pImpl = Context.pImpl;
417 if (!pImpl->TheTrueVal)
418 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
419 return pImpl->TheTrueVal;
422 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
423 LLVMContextImpl *pImpl = Context.pImpl;
424 if (!pImpl->TheFalseVal)
425 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
426 return pImpl->TheFalseVal;
429 Constant *ConstantInt::getTrue(Type *Ty) {
430 VectorType *VTy = dyn_cast<VectorType>(Ty);
432 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
433 return ConstantInt::getTrue(Ty->getContext());
435 assert(VTy->getElementType()->isIntegerTy(1) &&
436 "True must be vector of i1 or i1.");
437 return ConstantVector::getSplat(VTy->getNumElements(),
438 ConstantInt::getTrue(Ty->getContext()));
441 Constant *ConstantInt::getFalse(Type *Ty) {
442 VectorType *VTy = dyn_cast<VectorType>(Ty);
444 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
445 return ConstantInt::getFalse(Ty->getContext());
447 assert(VTy->getElementType()->isIntegerTy(1) &&
448 "False must be vector of i1 or i1.");
449 return ConstantVector::getSplat(VTy->getNumElements(),
450 ConstantInt::getFalse(Ty->getContext()));
454 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
455 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
456 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
457 // compare APInt's of different widths, which would violate an APInt class
458 // invariant which generates an assertion.
459 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
460 // Get the corresponding integer type for the bit width of the value.
461 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
462 // get an existing value or the insertion position
463 DenseMapAPIntKeyInfo::KeyTy Key(V, ITy);
464 ConstantInt *&Slot = Context.pImpl->IntConstants[Key];
465 if (!Slot) Slot = new ConstantInt(ITy, V);
469 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
470 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
472 // For vectors, broadcast the value.
473 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
474 return ConstantVector::getSplat(VTy->getNumElements(), C);
479 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
481 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
484 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
485 return get(Ty, V, true);
488 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
489 return get(Ty, V, true);
492 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
493 ConstantInt *C = get(Ty->getContext(), V);
494 assert(C->getType() == Ty->getScalarType() &&
495 "ConstantInt type doesn't match the type implied by its value!");
497 // For vectors, broadcast the value.
498 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
499 return ConstantVector::getSplat(VTy->getNumElements(), C);
504 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
506 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
509 //===----------------------------------------------------------------------===//
511 //===----------------------------------------------------------------------===//
513 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
515 return &APFloat::IEEEhalf;
517 return &APFloat::IEEEsingle;
518 if (Ty->isDoubleTy())
519 return &APFloat::IEEEdouble;
520 if (Ty->isX86_FP80Ty())
521 return &APFloat::x87DoubleExtended;
522 else if (Ty->isFP128Ty())
523 return &APFloat::IEEEquad;
525 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
526 return &APFloat::PPCDoubleDouble;
529 void ConstantFP::anchor() { }
531 /// get() - This returns a constant fp for the specified value in the
532 /// specified type. This should only be used for simple constant values like
533 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
534 Constant *ConstantFP::get(Type *Ty, double V) {
535 LLVMContext &Context = Ty->getContext();
539 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
540 APFloat::rmNearestTiesToEven, &ignored);
541 Constant *C = get(Context, FV);
543 // For vectors, broadcast the value.
544 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
545 return ConstantVector::getSplat(VTy->getNumElements(), C);
551 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
552 LLVMContext &Context = Ty->getContext();
554 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
555 Constant *C = get(Context, FV);
557 // For vectors, broadcast the value.
558 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
559 return ConstantVector::getSplat(VTy->getNumElements(), C);
565 ConstantFP *ConstantFP::getNegativeZero(Type *Ty) {
566 LLVMContext &Context = Ty->getContext();
567 APFloat apf = cast<ConstantFP>(Constant::getNullValue(Ty))->getValueAPF();
569 return get(Context, apf);
573 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
574 Type *ScalarTy = Ty->getScalarType();
575 if (ScalarTy->isFloatingPointTy()) {
576 Constant *C = getNegativeZero(ScalarTy);
577 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
578 return ConstantVector::getSplat(VTy->getNumElements(), C);
582 return Constant::getNullValue(Ty);
586 // ConstantFP accessors.
587 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
588 DenseMapAPFloatKeyInfo::KeyTy Key(V);
590 LLVMContextImpl* pImpl = Context.pImpl;
592 ConstantFP *&Slot = pImpl->FPConstants[Key];
596 if (&V.getSemantics() == &APFloat::IEEEhalf)
597 Ty = Type::getHalfTy(Context);
598 else if (&V.getSemantics() == &APFloat::IEEEsingle)
599 Ty = Type::getFloatTy(Context);
600 else if (&V.getSemantics() == &APFloat::IEEEdouble)
601 Ty = Type::getDoubleTy(Context);
602 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
603 Ty = Type::getX86_FP80Ty(Context);
604 else if (&V.getSemantics() == &APFloat::IEEEquad)
605 Ty = Type::getFP128Ty(Context);
607 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
608 "Unknown FP format");
609 Ty = Type::getPPC_FP128Ty(Context);
611 Slot = new ConstantFP(Ty, V);
617 ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
618 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty);
619 return ConstantFP::get(Ty->getContext(),
620 APFloat::getInf(Semantics, Negative));
623 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
624 : Constant(Ty, ConstantFPVal, 0, 0), Val(V) {
625 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
629 bool ConstantFP::isExactlyValue(const APFloat &V) const {
630 return Val.bitwiseIsEqual(V);
633 //===----------------------------------------------------------------------===//
634 // ConstantAggregateZero Implementation
635 //===----------------------------------------------------------------------===//
637 /// getSequentialElement - If this CAZ has array or vector type, return a zero
638 /// with the right element type.
639 Constant *ConstantAggregateZero::getSequentialElement() const {
640 return Constant::getNullValue(getType()->getSequentialElementType());
643 /// getStructElement - If this CAZ has struct type, return a zero with the
644 /// right element type for the specified element.
645 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
646 return Constant::getNullValue(getType()->getStructElementType(Elt));
649 /// getElementValue - Return a zero of the right value for the specified GEP
650 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
651 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
652 if (isa<SequentialType>(getType()))
653 return getSequentialElement();
654 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
657 /// getElementValue - Return a zero of the right value for the specified GEP
659 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
660 if (isa<SequentialType>(getType()))
661 return getSequentialElement();
662 return getStructElement(Idx);
666 //===----------------------------------------------------------------------===//
667 // UndefValue Implementation
668 //===----------------------------------------------------------------------===//
670 /// getSequentialElement - If this undef has array or vector type, return an
671 /// undef with the right element type.
672 UndefValue *UndefValue::getSequentialElement() const {
673 return UndefValue::get(getType()->getSequentialElementType());
676 /// getStructElement - If this undef has struct type, return a zero with the
677 /// right element type for the specified element.
678 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
679 return UndefValue::get(getType()->getStructElementType(Elt));
682 /// getElementValue - Return an undef of the right value for the specified GEP
683 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
684 UndefValue *UndefValue::getElementValue(Constant *C) const {
685 if (isa<SequentialType>(getType()))
686 return getSequentialElement();
687 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
690 /// getElementValue - Return an undef of the right value for the specified GEP
692 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
693 if (isa<SequentialType>(getType()))
694 return getSequentialElement();
695 return getStructElement(Idx);
700 //===----------------------------------------------------------------------===//
701 // ConstantXXX Classes
702 //===----------------------------------------------------------------------===//
704 template <typename ItTy, typename EltTy>
705 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
706 for (; Start != End; ++Start)
712 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
713 : Constant(T, ConstantArrayVal,
714 OperandTraits<ConstantArray>::op_end(this) - V.size(),
716 assert(V.size() == T->getNumElements() &&
717 "Invalid initializer vector for constant array");
718 for (unsigned i = 0, e = V.size(); i != e; ++i)
719 assert(V[i]->getType() == T->getElementType() &&
720 "Initializer for array element doesn't match array element type!");
721 std::copy(V.begin(), V.end(), op_begin());
724 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
725 // Empty arrays are canonicalized to ConstantAggregateZero.
727 return ConstantAggregateZero::get(Ty);
729 for (unsigned i = 0, e = V.size(); i != e; ++i) {
730 assert(V[i]->getType() == Ty->getElementType() &&
731 "Wrong type in array element initializer");
733 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
735 // If this is an all-zero array, return a ConstantAggregateZero object. If
736 // all undef, return an UndefValue, if "all simple", then return a
737 // ConstantDataArray.
739 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
740 return UndefValue::get(Ty);
742 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
743 return ConstantAggregateZero::get(Ty);
745 // Check to see if all of the elements are ConstantFP or ConstantInt and if
746 // the element type is compatible with ConstantDataVector. If so, use it.
747 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
748 // We speculatively build the elements here even if it turns out that there
749 // is a constantexpr or something else weird in the array, since it is so
750 // uncommon for that to happen.
751 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
752 if (CI->getType()->isIntegerTy(8)) {
753 SmallVector<uint8_t, 16> Elts;
754 for (unsigned i = 0, e = V.size(); i != e; ++i)
755 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
756 Elts.push_back(CI->getZExtValue());
759 if (Elts.size() == V.size())
760 return ConstantDataArray::get(C->getContext(), Elts);
761 } else if (CI->getType()->isIntegerTy(16)) {
762 SmallVector<uint16_t, 16> Elts;
763 for (unsigned i = 0, e = V.size(); i != e; ++i)
764 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
765 Elts.push_back(CI->getZExtValue());
768 if (Elts.size() == V.size())
769 return ConstantDataArray::get(C->getContext(), Elts);
770 } else if (CI->getType()->isIntegerTy(32)) {
771 SmallVector<uint32_t, 16> Elts;
772 for (unsigned i = 0, e = V.size(); i != e; ++i)
773 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
774 Elts.push_back(CI->getZExtValue());
777 if (Elts.size() == V.size())
778 return ConstantDataArray::get(C->getContext(), Elts);
779 } else if (CI->getType()->isIntegerTy(64)) {
780 SmallVector<uint64_t, 16> Elts;
781 for (unsigned i = 0, e = V.size(); i != e; ++i)
782 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
783 Elts.push_back(CI->getZExtValue());
786 if (Elts.size() == V.size())
787 return ConstantDataArray::get(C->getContext(), Elts);
791 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
792 if (CFP->getType()->isFloatTy()) {
793 SmallVector<float, 16> Elts;
794 for (unsigned i = 0, e = V.size(); i != e; ++i)
795 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
796 Elts.push_back(CFP->getValueAPF().convertToFloat());
799 if (Elts.size() == V.size())
800 return ConstantDataArray::get(C->getContext(), Elts);
801 } else if (CFP->getType()->isDoubleTy()) {
802 SmallVector<double, 16> Elts;
803 for (unsigned i = 0, e = V.size(); i != e; ++i)
804 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
805 Elts.push_back(CFP->getValueAPF().convertToDouble());
808 if (Elts.size() == V.size())
809 return ConstantDataArray::get(C->getContext(), Elts);
814 // Otherwise, we really do want to create a ConstantArray.
815 return pImpl->ArrayConstants.getOrCreate(Ty, V);
818 /// getTypeForElements - Return an anonymous struct type to use for a constant
819 /// with the specified set of elements. The list must not be empty.
820 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
821 ArrayRef<Constant*> V,
823 unsigned VecSize = V.size();
824 SmallVector<Type*, 16> EltTypes(VecSize);
825 for (unsigned i = 0; i != VecSize; ++i)
826 EltTypes[i] = V[i]->getType();
828 return StructType::get(Context, EltTypes, Packed);
832 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
835 "ConstantStruct::getTypeForElements cannot be called on empty list");
836 return getTypeForElements(V[0]->getContext(), V, Packed);
840 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
841 : Constant(T, ConstantStructVal,
842 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
844 assert(V.size() == T->getNumElements() &&
845 "Invalid initializer vector for constant structure");
846 for (unsigned i = 0, e = V.size(); i != e; ++i)
847 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
848 "Initializer for struct element doesn't match struct element type!");
849 std::copy(V.begin(), V.end(), op_begin());
852 // ConstantStruct accessors.
853 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
854 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
855 "Incorrect # elements specified to ConstantStruct::get");
857 // Create a ConstantAggregateZero value if all elements are zeros.
859 bool isUndef = false;
862 isUndef = isa<UndefValue>(V[0]);
863 isZero = V[0]->isNullValue();
864 if (isUndef || isZero) {
865 for (unsigned i = 0, e = V.size(); i != e; ++i) {
866 if (!V[i]->isNullValue())
868 if (!isa<UndefValue>(V[i]))
874 return ConstantAggregateZero::get(ST);
876 return UndefValue::get(ST);
878 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
881 Constant *ConstantStruct::get(StructType *T, ...) {
883 SmallVector<Constant*, 8> Values;
885 while (Constant *Val = va_arg(ap, llvm::Constant*))
886 Values.push_back(Val);
888 return get(T, Values);
891 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
892 : Constant(T, ConstantVectorVal,
893 OperandTraits<ConstantVector>::op_end(this) - V.size(),
895 for (size_t i = 0, e = V.size(); i != e; i++)
896 assert(V[i]->getType() == T->getElementType() &&
897 "Initializer for vector element doesn't match vector element type!");
898 std::copy(V.begin(), V.end(), op_begin());
901 // ConstantVector accessors.
902 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
903 assert(!V.empty() && "Vectors can't be empty");
904 VectorType *T = VectorType::get(V.front()->getType(), V.size());
905 LLVMContextImpl *pImpl = T->getContext().pImpl;
907 // If this is an all-undef or all-zero vector, return a
908 // ConstantAggregateZero or UndefValue.
910 bool isZero = C->isNullValue();
911 bool isUndef = isa<UndefValue>(C);
913 if (isZero || isUndef) {
914 for (unsigned i = 1, e = V.size(); i != e; ++i)
916 isZero = isUndef = false;
922 return ConstantAggregateZero::get(T);
924 return UndefValue::get(T);
926 // Check to see if all of the elements are ConstantFP or ConstantInt and if
927 // the element type is compatible with ConstantDataVector. If so, use it.
928 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
929 // We speculatively build the elements here even if it turns out that there
930 // is a constantexpr or something else weird in the array, since it is so
931 // uncommon for that to happen.
932 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
933 if (CI->getType()->isIntegerTy(8)) {
934 SmallVector<uint8_t, 16> Elts;
935 for (unsigned i = 0, e = V.size(); i != e; ++i)
936 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
937 Elts.push_back(CI->getZExtValue());
940 if (Elts.size() == V.size())
941 return ConstantDataVector::get(C->getContext(), Elts);
942 } else if (CI->getType()->isIntegerTy(16)) {
943 SmallVector<uint16_t, 16> Elts;
944 for (unsigned i = 0, e = V.size(); i != e; ++i)
945 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
946 Elts.push_back(CI->getZExtValue());
949 if (Elts.size() == V.size())
950 return ConstantDataVector::get(C->getContext(), Elts);
951 } else if (CI->getType()->isIntegerTy(32)) {
952 SmallVector<uint32_t, 16> Elts;
953 for (unsigned i = 0, e = V.size(); i != e; ++i)
954 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
955 Elts.push_back(CI->getZExtValue());
958 if (Elts.size() == V.size())
959 return ConstantDataVector::get(C->getContext(), Elts);
960 } else if (CI->getType()->isIntegerTy(64)) {
961 SmallVector<uint64_t, 16> Elts;
962 for (unsigned i = 0, e = V.size(); i != e; ++i)
963 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
964 Elts.push_back(CI->getZExtValue());
967 if (Elts.size() == V.size())
968 return ConstantDataVector::get(C->getContext(), Elts);
972 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
973 if (CFP->getType()->isFloatTy()) {
974 SmallVector<float, 16> Elts;
975 for (unsigned i = 0, e = V.size(); i != e; ++i)
976 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
977 Elts.push_back(CFP->getValueAPF().convertToFloat());
980 if (Elts.size() == V.size())
981 return ConstantDataVector::get(C->getContext(), Elts);
982 } else if (CFP->getType()->isDoubleTy()) {
983 SmallVector<double, 16> Elts;
984 for (unsigned i = 0, e = V.size(); i != e; ++i)
985 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
986 Elts.push_back(CFP->getValueAPF().convertToDouble());
989 if (Elts.size() == V.size())
990 return ConstantDataVector::get(C->getContext(), Elts);
995 // Otherwise, the element type isn't compatible with ConstantDataVector, or
996 // the operand list constants a ConstantExpr or something else strange.
997 return pImpl->VectorConstants.getOrCreate(T, V);
1000 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1001 // If this splat is compatible with ConstantDataVector, use it instead of
1003 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1004 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1005 return ConstantDataVector::getSplat(NumElts, V);
1007 SmallVector<Constant*, 32> Elts(NumElts, V);
1012 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1013 // can't be inline because we don't want to #include Instruction.h into
1015 bool ConstantExpr::isCast() const {
1016 return Instruction::isCast(getOpcode());
1019 bool ConstantExpr::isCompare() const {
1020 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1023 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1024 if (getOpcode() != Instruction::GetElementPtr) return false;
1026 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1027 User::const_op_iterator OI = llvm::next(this->op_begin());
1029 // Skip the first index, as it has no static limit.
1033 // The remaining indices must be compile-time known integers within the
1034 // bounds of the corresponding notional static array types.
1035 for (; GEPI != E; ++GEPI, ++OI) {
1036 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1037 if (!CI) return false;
1038 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1039 if (CI->getValue().getActiveBits() > 64 ||
1040 CI->getZExtValue() >= ATy->getNumElements())
1044 // All the indices checked out.
1048 bool ConstantExpr::hasIndices() const {
1049 return getOpcode() == Instruction::ExtractValue ||
1050 getOpcode() == Instruction::InsertValue;
1053 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1054 if (const ExtractValueConstantExpr *EVCE =
1055 dyn_cast<ExtractValueConstantExpr>(this))
1056 return EVCE->Indices;
1058 return cast<InsertValueConstantExpr>(this)->Indices;
1061 unsigned ConstantExpr::getPredicate() const {
1062 assert(isCompare());
1063 return ((const CompareConstantExpr*)this)->predicate;
1066 /// getWithOperandReplaced - Return a constant expression identical to this
1067 /// one, but with the specified operand set to the specified value.
1069 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1070 assert(Op->getType() == getOperand(OpNo)->getType() &&
1071 "Replacing operand with value of different type!");
1072 if (getOperand(OpNo) == Op)
1073 return const_cast<ConstantExpr*>(this);
1075 SmallVector<Constant*, 8> NewOps;
1076 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1077 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1079 return getWithOperands(NewOps);
1082 /// getWithOperands - This returns the current constant expression with the
1083 /// operands replaced with the specified values. The specified array must
1084 /// have the same number of operands as our current one.
1085 Constant *ConstantExpr::
1086 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
1087 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1088 bool AnyChange = Ty != getType();
1089 for (unsigned i = 0; i != Ops.size(); ++i)
1090 AnyChange |= Ops[i] != getOperand(i);
1092 if (!AnyChange) // No operands changed, return self.
1093 return const_cast<ConstantExpr*>(this);
1095 switch (getOpcode()) {
1096 case Instruction::Trunc:
1097 case Instruction::ZExt:
1098 case Instruction::SExt:
1099 case Instruction::FPTrunc:
1100 case Instruction::FPExt:
1101 case Instruction::UIToFP:
1102 case Instruction::SIToFP:
1103 case Instruction::FPToUI:
1104 case Instruction::FPToSI:
1105 case Instruction::PtrToInt:
1106 case Instruction::IntToPtr:
1107 case Instruction::BitCast:
1108 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
1109 case Instruction::Select:
1110 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1111 case Instruction::InsertElement:
1112 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1113 case Instruction::ExtractElement:
1114 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1115 case Instruction::InsertValue:
1116 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1117 case Instruction::ExtractValue:
1118 return ConstantExpr::getExtractValue(Ops[0], getIndices());
1119 case Instruction::ShuffleVector:
1120 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1121 case Instruction::GetElementPtr:
1122 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1123 cast<GEPOperator>(this)->isInBounds());
1124 case Instruction::ICmp:
1125 case Instruction::FCmp:
1126 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1128 assert(getNumOperands() == 2 && "Must be binary operator?");
1129 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
1134 //===----------------------------------------------------------------------===//
1135 // isValueValidForType implementations
1137 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1138 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1139 if (Ty->isIntegerTy(1))
1140 return Val == 0 || Val == 1;
1142 return true; // always true, has to fit in largest type
1143 uint64_t Max = (1ll << NumBits) - 1;
1147 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1148 unsigned NumBits = Ty->getIntegerBitWidth();
1149 if (Ty->isIntegerTy(1))
1150 return Val == 0 || Val == 1 || Val == -1;
1152 return true; // always true, has to fit in largest type
1153 int64_t Min = -(1ll << (NumBits-1));
1154 int64_t Max = (1ll << (NumBits-1)) - 1;
1155 return (Val >= Min && Val <= Max);
1158 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1159 // convert modifies in place, so make a copy.
1160 APFloat Val2 = APFloat(Val);
1162 switch (Ty->getTypeID()) {
1164 return false; // These can't be represented as floating point!
1166 // FIXME rounding mode needs to be more flexible
1167 case Type::HalfTyID: {
1168 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1170 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1173 case Type::FloatTyID: {
1174 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1176 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1179 case Type::DoubleTyID: {
1180 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1181 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1182 &Val2.getSemantics() == &APFloat::IEEEdouble)
1184 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1187 case Type::X86_FP80TyID:
1188 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1189 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1190 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1191 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1192 case Type::FP128TyID:
1193 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1194 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1195 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1196 &Val2.getSemantics() == &APFloat::IEEEquad;
1197 case Type::PPC_FP128TyID:
1198 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1199 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1200 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1201 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1206 //===----------------------------------------------------------------------===//
1207 // Factory Function Implementation
1209 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1210 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1211 "Cannot create an aggregate zero of non-aggregate type!");
1213 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1215 Entry = new ConstantAggregateZero(Ty);
1220 /// destroyConstant - Remove the constant from the constant table.
1222 void ConstantAggregateZero::destroyConstant() {
1223 getContext().pImpl->CAZConstants.erase(getType());
1224 destroyConstantImpl();
1227 /// destroyConstant - Remove the constant from the constant table...
1229 void ConstantArray::destroyConstant() {
1230 getType()->getContext().pImpl->ArrayConstants.remove(this);
1231 destroyConstantImpl();
1235 //---- ConstantStruct::get() implementation...
1238 // destroyConstant - Remove the constant from the constant table...
1240 void ConstantStruct::destroyConstant() {
1241 getType()->getContext().pImpl->StructConstants.remove(this);
1242 destroyConstantImpl();
1245 // destroyConstant - Remove the constant from the constant table...
1247 void ConstantVector::destroyConstant() {
1248 getType()->getContext().pImpl->VectorConstants.remove(this);
1249 destroyConstantImpl();
1252 /// getSplatValue - If this is a splat vector constant, meaning that all of
1253 /// the elements have the same value, return that value. Otherwise return 0.
1254 Constant *Constant::getSplatValue() const {
1255 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1256 if (isa<ConstantAggregateZero>(this))
1257 return getNullValue(this->getType()->getVectorElementType());
1258 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1259 return CV->getSplatValue();
1260 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1261 return CV->getSplatValue();
1265 /// getSplatValue - If this is a splat constant, where all of the
1266 /// elements have the same value, return that value. Otherwise return null.
1267 Constant *ConstantVector::getSplatValue() const {
1268 // Check out first element.
1269 Constant *Elt = getOperand(0);
1270 // Then make sure all remaining elements point to the same value.
1271 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1272 if (getOperand(I) != Elt)
1277 /// If C is a constant integer then return its value, otherwise C must be a
1278 /// vector of constant integers, all equal, and the common value is returned.
1279 const APInt &Constant::getUniqueInteger() const {
1280 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1281 return CI->getValue();
1282 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1283 const Constant *C = this->getAggregateElement(0U);
1284 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1285 return cast<ConstantInt>(C)->getValue();
1289 //---- ConstantPointerNull::get() implementation.
1292 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1293 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1295 Entry = new ConstantPointerNull(Ty);
1300 // destroyConstant - Remove the constant from the constant table...
1302 void ConstantPointerNull::destroyConstant() {
1303 getContext().pImpl->CPNConstants.erase(getType());
1304 // Free the constant and any dangling references to it.
1305 destroyConstantImpl();
1309 //---- UndefValue::get() implementation.
1312 UndefValue *UndefValue::get(Type *Ty) {
1313 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1315 Entry = new UndefValue(Ty);
1320 // destroyConstant - Remove the constant from the constant table.
1322 void UndefValue::destroyConstant() {
1323 // Free the constant and any dangling references to it.
1324 getContext().pImpl->UVConstants.erase(getType());
1325 destroyConstantImpl();
1328 //---- BlockAddress::get() implementation.
1331 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1332 assert(BB->getParent() != 0 && "Block must have a parent");
1333 return get(BB->getParent(), BB);
1336 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1338 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1340 BA = new BlockAddress(F, BB);
1342 assert(BA->getFunction() == F && "Basic block moved between functions");
1346 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1347 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1351 BB->AdjustBlockAddressRefCount(1);
1355 // destroyConstant - Remove the constant from the constant table.
1357 void BlockAddress::destroyConstant() {
1358 getFunction()->getType()->getContext().pImpl
1359 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1360 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1361 destroyConstantImpl();
1364 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1365 // This could be replacing either the Basic Block or the Function. In either
1366 // case, we have to remove the map entry.
1367 Function *NewF = getFunction();
1368 BasicBlock *NewBB = getBasicBlock();
1371 NewF = cast<Function>(To);
1373 NewBB = cast<BasicBlock>(To);
1375 // See if the 'new' entry already exists, if not, just update this in place
1376 // and return early.
1377 BlockAddress *&NewBA =
1378 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1380 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1382 // Remove the old entry, this can't cause the map to rehash (just a
1383 // tombstone will get added).
1384 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1387 setOperand(0, NewF);
1388 setOperand(1, NewBB);
1389 getBasicBlock()->AdjustBlockAddressRefCount(1);
1393 // Otherwise, I do need to replace this with an existing value.
1394 assert(NewBA != this && "I didn't contain From!");
1396 // Everyone using this now uses the replacement.
1397 replaceAllUsesWith(NewBA);
1402 //---- ConstantExpr::get() implementations.
1405 /// This is a utility function to handle folding of casts and lookup of the
1406 /// cast in the ExprConstants map. It is used by the various get* methods below.
1407 static inline Constant *getFoldedCast(
1408 Instruction::CastOps opc, Constant *C, Type *Ty) {
1409 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1410 // Fold a few common cases
1411 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1414 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1416 // Look up the constant in the table first to ensure uniqueness
1417 std::vector<Constant*> argVec(1, C);
1418 ExprMapKeyType Key(opc, argVec);
1420 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1423 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1424 Instruction::CastOps opc = Instruction::CastOps(oc);
1425 assert(Instruction::isCast(opc) && "opcode out of range");
1426 assert(C && Ty && "Null arguments to getCast");
1427 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1431 llvm_unreachable("Invalid cast opcode");
1432 case Instruction::Trunc: return getTrunc(C, Ty);
1433 case Instruction::ZExt: return getZExt(C, Ty);
1434 case Instruction::SExt: return getSExt(C, Ty);
1435 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1436 case Instruction::FPExt: return getFPExtend(C, Ty);
1437 case Instruction::UIToFP: return getUIToFP(C, Ty);
1438 case Instruction::SIToFP: return getSIToFP(C, Ty);
1439 case Instruction::FPToUI: return getFPToUI(C, Ty);
1440 case Instruction::FPToSI: return getFPToSI(C, Ty);
1441 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1442 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1443 case Instruction::BitCast: return getBitCast(C, Ty);
1447 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1448 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1449 return getBitCast(C, Ty);
1450 return getZExt(C, Ty);
1453 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1454 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1455 return getBitCast(C, Ty);
1456 return getSExt(C, Ty);
1459 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1460 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1461 return getBitCast(C, Ty);
1462 return getTrunc(C, Ty);
1465 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1466 assert(S->getType()->isPointerTy() && "Invalid cast");
1467 assert((Ty->isIntegerTy() || Ty->isPointerTy()) && "Invalid cast");
1469 if (Ty->isIntegerTy())
1470 return getPtrToInt(S, Ty);
1471 return getBitCast(S, Ty);
1474 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1476 assert(C->getType()->isIntOrIntVectorTy() &&
1477 Ty->isIntOrIntVectorTy() && "Invalid cast");
1478 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1479 unsigned DstBits = Ty->getScalarSizeInBits();
1480 Instruction::CastOps opcode =
1481 (SrcBits == DstBits ? Instruction::BitCast :
1482 (SrcBits > DstBits ? Instruction::Trunc :
1483 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1484 return getCast(opcode, C, Ty);
1487 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1488 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1490 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1491 unsigned DstBits = Ty->getScalarSizeInBits();
1492 if (SrcBits == DstBits)
1493 return C; // Avoid a useless cast
1494 Instruction::CastOps opcode =
1495 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1496 return getCast(opcode, C, Ty);
1499 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty) {
1501 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1502 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1504 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1505 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1506 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1507 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1508 "SrcTy must be larger than DestTy for Trunc!");
1510 return getFoldedCast(Instruction::Trunc, C, Ty);
1513 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1515 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1516 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1518 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1519 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1520 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1521 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1522 "SrcTy must be smaller than DestTy for SExt!");
1524 return getFoldedCast(Instruction::SExt, C, Ty);
1527 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1529 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1530 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1532 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1533 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1534 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1535 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1536 "SrcTy must be smaller than DestTy for ZExt!");
1538 return getFoldedCast(Instruction::ZExt, C, Ty);
1541 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1543 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1544 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1546 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1547 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1548 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1549 "This is an illegal floating point truncation!");
1550 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1553 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1555 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1556 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1558 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1559 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1560 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1561 "This is an illegal floating point extension!");
1562 return getFoldedCast(Instruction::FPExt, C, Ty);
1565 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1567 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1568 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1570 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1571 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1572 "This is an illegal uint to floating point cast!");
1573 return getFoldedCast(Instruction::UIToFP, C, Ty);
1576 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1578 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1579 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1581 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1582 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1583 "This is an illegal sint to floating point cast!");
1584 return getFoldedCast(Instruction::SIToFP, C, Ty);
1587 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1589 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1590 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1592 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1593 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1594 "This is an illegal floating point to uint cast!");
1595 return getFoldedCast(Instruction::FPToUI, C, Ty);
1598 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1600 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1601 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1603 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1604 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1605 "This is an illegal floating point to sint cast!");
1606 return getFoldedCast(Instruction::FPToSI, C, Ty);
1609 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1610 assert(C->getType()->getScalarType()->isPointerTy() &&
1611 "PtrToInt source must be pointer or pointer vector");
1612 assert(DstTy->getScalarType()->isIntegerTy() &&
1613 "PtrToInt destination must be integer or integer vector");
1614 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1615 if (isa<VectorType>(C->getType()))
1616 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1617 "Invalid cast between a different number of vector elements");
1618 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1621 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1622 assert(C->getType()->getScalarType()->isIntegerTy() &&
1623 "IntToPtr source must be integer or integer vector");
1624 assert(DstTy->getScalarType()->isPointerTy() &&
1625 "IntToPtr destination must be a pointer or pointer vector");
1626 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1627 if (isa<VectorType>(C->getType()))
1628 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1629 "Invalid cast between a different number of vector elements");
1630 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1633 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1634 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1635 "Invalid constantexpr bitcast!");
1637 // It is common to ask for a bitcast of a value to its own type, handle this
1639 if (C->getType() == DstTy) return C;
1641 return getFoldedCast(Instruction::BitCast, C, DstTy);
1644 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1646 // Check the operands for consistency first.
1647 assert(Opcode >= Instruction::BinaryOpsBegin &&
1648 Opcode < Instruction::BinaryOpsEnd &&
1649 "Invalid opcode in binary constant expression");
1650 assert(C1->getType() == C2->getType() &&
1651 "Operand types in binary constant expression should match");
1655 case Instruction::Add:
1656 case Instruction::Sub:
1657 case Instruction::Mul:
1658 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1659 assert(C1->getType()->isIntOrIntVectorTy() &&
1660 "Tried to create an integer operation on a non-integer type!");
1662 case Instruction::FAdd:
1663 case Instruction::FSub:
1664 case Instruction::FMul:
1665 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1666 assert(C1->getType()->isFPOrFPVectorTy() &&
1667 "Tried to create a floating-point operation on a "
1668 "non-floating-point type!");
1670 case Instruction::UDiv:
1671 case Instruction::SDiv:
1672 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1673 assert(C1->getType()->isIntOrIntVectorTy() &&
1674 "Tried to create an arithmetic operation on a non-arithmetic type!");
1676 case Instruction::FDiv:
1677 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1678 assert(C1->getType()->isFPOrFPVectorTy() &&
1679 "Tried to create an arithmetic operation on a non-arithmetic type!");
1681 case Instruction::URem:
1682 case Instruction::SRem:
1683 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1684 assert(C1->getType()->isIntOrIntVectorTy() &&
1685 "Tried to create an arithmetic operation on a non-arithmetic type!");
1687 case Instruction::FRem:
1688 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1689 assert(C1->getType()->isFPOrFPVectorTy() &&
1690 "Tried to create an arithmetic operation on a non-arithmetic type!");
1692 case Instruction::And:
1693 case Instruction::Or:
1694 case Instruction::Xor:
1695 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1696 assert(C1->getType()->isIntOrIntVectorTy() &&
1697 "Tried to create a logical operation on a non-integral type!");
1699 case Instruction::Shl:
1700 case Instruction::LShr:
1701 case Instruction::AShr:
1702 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1703 assert(C1->getType()->isIntOrIntVectorTy() &&
1704 "Tried to create a shift operation on a non-integer type!");
1711 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1712 return FC; // Fold a few common cases.
1714 std::vector<Constant*> argVec(1, C1);
1715 argVec.push_back(C2);
1716 ExprMapKeyType Key(Opcode, argVec, 0, Flags);
1718 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1719 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1722 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1723 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1724 // Note that a non-inbounds gep is used, as null isn't within any object.
1725 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1726 Constant *GEP = getGetElementPtr(
1727 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1728 return getPtrToInt(GEP,
1729 Type::getInt64Ty(Ty->getContext()));
1732 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1733 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1734 // Note that a non-inbounds gep is used, as null isn't within any object.
1736 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1737 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo());
1738 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1739 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1740 Constant *Indices[2] = { Zero, One };
1741 Constant *GEP = getGetElementPtr(NullPtr, Indices);
1742 return getPtrToInt(GEP,
1743 Type::getInt64Ty(Ty->getContext()));
1746 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1747 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1751 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1752 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1753 // Note that a non-inbounds gep is used, as null isn't within any object.
1754 Constant *GEPIdx[] = {
1755 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1758 Constant *GEP = getGetElementPtr(
1759 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1760 return getPtrToInt(GEP,
1761 Type::getInt64Ty(Ty->getContext()));
1764 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1765 Constant *C1, Constant *C2) {
1766 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1768 switch (Predicate) {
1769 default: llvm_unreachable("Invalid CmpInst predicate");
1770 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1771 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1772 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1773 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1774 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1775 case CmpInst::FCMP_TRUE:
1776 return getFCmp(Predicate, C1, C2);
1778 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1779 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1780 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1781 case CmpInst::ICMP_SLE:
1782 return getICmp(Predicate, C1, C2);
1786 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1787 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1789 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1790 return SC; // Fold common cases
1792 std::vector<Constant*> argVec(3, C);
1795 ExprMapKeyType Key(Instruction::Select, argVec);
1797 LLVMContextImpl *pImpl = C->getContext().pImpl;
1798 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1801 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1803 assert(C->getType()->isPtrOrPtrVectorTy() &&
1804 "Non-pointer type for constant GetElementPtr expression");
1806 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1807 return FC; // Fold a few common cases.
1809 // Get the result type of the getelementptr!
1810 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1811 assert(Ty && "GEP indices invalid!");
1812 unsigned AS = C->getType()->getPointerAddressSpace();
1813 Type *ReqTy = Ty->getPointerTo(AS);
1814 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1815 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
1817 // Look up the constant in the table first to ensure uniqueness
1818 std::vector<Constant*> ArgVec;
1819 ArgVec.reserve(1 + Idxs.size());
1820 ArgVec.push_back(C);
1821 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1822 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1823 "getelementptr index type missmatch");
1824 assert((!Idxs[i]->getType()->isVectorTy() ||
1825 ReqTy->getVectorNumElements() ==
1826 Idxs[i]->getType()->getVectorNumElements()) &&
1827 "getelementptr index type missmatch");
1828 ArgVec.push_back(cast<Constant>(Idxs[i]));
1830 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1831 InBounds ? GEPOperator::IsInBounds : 0);
1833 LLVMContextImpl *pImpl = C->getContext().pImpl;
1834 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1838 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1839 assert(LHS->getType() == RHS->getType());
1840 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1841 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1843 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1844 return FC; // Fold a few common cases...
1846 // Look up the constant in the table first to ensure uniqueness
1847 std::vector<Constant*> ArgVec;
1848 ArgVec.push_back(LHS);
1849 ArgVec.push_back(RHS);
1850 // Get the key type with both the opcode and predicate
1851 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1853 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1854 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1855 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1857 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1858 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1862 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1863 assert(LHS->getType() == RHS->getType());
1864 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1866 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1867 return FC; // Fold a few common cases...
1869 // Look up the constant in the table first to ensure uniqueness
1870 std::vector<Constant*> ArgVec;
1871 ArgVec.push_back(LHS);
1872 ArgVec.push_back(RHS);
1873 // Get the key type with both the opcode and predicate
1874 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1876 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1877 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1878 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1880 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1881 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1884 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1885 assert(Val->getType()->isVectorTy() &&
1886 "Tried to create extractelement operation on non-vector type!");
1887 assert(Idx->getType()->isIntegerTy(32) &&
1888 "Extractelement index must be i32 type!");
1890 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1891 return FC; // Fold a few common cases.
1893 // Look up the constant in the table first to ensure uniqueness
1894 std::vector<Constant*> ArgVec(1, Val);
1895 ArgVec.push_back(Idx);
1896 const ExprMapKeyType Key(Instruction::ExtractElement,ArgVec);
1898 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1899 Type *ReqTy = Val->getType()->getVectorElementType();
1900 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1903 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1905 assert(Val->getType()->isVectorTy() &&
1906 "Tried to create insertelement operation on non-vector type!");
1907 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1908 "Insertelement types must match!");
1909 assert(Idx->getType()->isIntegerTy(32) &&
1910 "Insertelement index must be i32 type!");
1912 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1913 return FC; // Fold a few common cases.
1914 // Look up the constant in the table first to ensure uniqueness
1915 std::vector<Constant*> ArgVec(1, Val);
1916 ArgVec.push_back(Elt);
1917 ArgVec.push_back(Idx);
1918 const ExprMapKeyType Key(Instruction::InsertElement,ArgVec);
1920 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1921 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
1924 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
1926 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
1927 "Invalid shuffle vector constant expr operands!");
1929 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
1930 return FC; // Fold a few common cases.
1932 unsigned NElts = Mask->getType()->getVectorNumElements();
1933 Type *EltTy = V1->getType()->getVectorElementType();
1934 Type *ShufTy = VectorType::get(EltTy, NElts);
1936 // Look up the constant in the table first to ensure uniqueness
1937 std::vector<Constant*> ArgVec(1, V1);
1938 ArgVec.push_back(V2);
1939 ArgVec.push_back(Mask);
1940 const ExprMapKeyType Key(Instruction::ShuffleVector,ArgVec);
1942 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
1943 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
1946 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
1947 ArrayRef<unsigned> Idxs) {
1948 assert(ExtractValueInst::getIndexedType(Agg->getType(),
1949 Idxs) == Val->getType() &&
1950 "insertvalue indices invalid!");
1951 assert(Agg->getType()->isFirstClassType() &&
1952 "Non-first-class type for constant insertvalue expression");
1953 Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs);
1954 assert(FC && "insertvalue constant expr couldn't be folded!");
1958 Constant *ConstantExpr::getExtractValue(Constant *Agg,
1959 ArrayRef<unsigned> Idxs) {
1960 assert(Agg->getType()->isFirstClassType() &&
1961 "Tried to create extractelement operation on non-first-class type!");
1963 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
1965 assert(ReqTy && "extractvalue indices invalid!");
1967 assert(Agg->getType()->isFirstClassType() &&
1968 "Non-first-class type for constant extractvalue expression");
1969 Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs);
1970 assert(FC && "ExtractValue constant expr couldn't be folded!");
1974 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
1975 assert(C->getType()->isIntOrIntVectorTy() &&
1976 "Cannot NEG a nonintegral value!");
1977 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
1981 Constant *ConstantExpr::getFNeg(Constant *C) {
1982 assert(C->getType()->isFPOrFPVectorTy() &&
1983 "Cannot FNEG a non-floating-point value!");
1984 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
1987 Constant *ConstantExpr::getNot(Constant *C) {
1988 assert(C->getType()->isIntOrIntVectorTy() &&
1989 "Cannot NOT a nonintegral value!");
1990 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
1993 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
1994 bool HasNUW, bool HasNSW) {
1995 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
1996 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
1997 return get(Instruction::Add, C1, C2, Flags);
2000 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2001 return get(Instruction::FAdd, C1, C2);
2004 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2005 bool HasNUW, bool HasNSW) {
2006 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2007 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2008 return get(Instruction::Sub, C1, C2, Flags);
2011 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2012 return get(Instruction::FSub, C1, C2);
2015 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2016 bool HasNUW, bool HasNSW) {
2017 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2018 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2019 return get(Instruction::Mul, C1, C2, Flags);
2022 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2023 return get(Instruction::FMul, C1, C2);
2026 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2027 return get(Instruction::UDiv, C1, C2,
2028 isExact ? PossiblyExactOperator::IsExact : 0);
2031 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2032 return get(Instruction::SDiv, C1, C2,
2033 isExact ? PossiblyExactOperator::IsExact : 0);
2036 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2037 return get(Instruction::FDiv, C1, C2);
2040 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2041 return get(Instruction::URem, C1, C2);
2044 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2045 return get(Instruction::SRem, C1, C2);
2048 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2049 return get(Instruction::FRem, C1, C2);
2052 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2053 return get(Instruction::And, C1, C2);
2056 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2057 return get(Instruction::Or, C1, C2);
2060 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2061 return get(Instruction::Xor, C1, C2);
2064 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2065 bool HasNUW, bool HasNSW) {
2066 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2067 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2068 return get(Instruction::Shl, C1, C2, Flags);
2071 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2072 return get(Instruction::LShr, C1, C2,
2073 isExact ? PossiblyExactOperator::IsExact : 0);
2076 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2077 return get(Instruction::AShr, C1, C2,
2078 isExact ? PossiblyExactOperator::IsExact : 0);
2081 /// getBinOpIdentity - Return the identity for the given binary operation,
2082 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
2083 /// returns null if the operator doesn't have an identity.
2084 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2087 // Doesn't have an identity.
2090 case Instruction::Add:
2091 case Instruction::Or:
2092 case Instruction::Xor:
2093 return Constant::getNullValue(Ty);
2095 case Instruction::Mul:
2096 return ConstantInt::get(Ty, 1);
2098 case Instruction::And:
2099 return Constant::getAllOnesValue(Ty);
2103 /// getBinOpAbsorber - Return the absorbing element for the given binary
2104 /// operation, i.e. a constant C such that X op C = C and C op X = C for
2105 /// every X. For example, this returns zero for integer multiplication.
2106 /// It returns null if the operator doesn't have an absorbing element.
2107 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2110 // Doesn't have an absorber.
2113 case Instruction::Or:
2114 return Constant::getAllOnesValue(Ty);
2116 case Instruction::And:
2117 case Instruction::Mul:
2118 return Constant::getNullValue(Ty);
2122 // destroyConstant - Remove the constant from the constant table...
2124 void ConstantExpr::destroyConstant() {
2125 getType()->getContext().pImpl->ExprConstants.remove(this);
2126 destroyConstantImpl();
2129 const char *ConstantExpr::getOpcodeName() const {
2130 return Instruction::getOpcodeName(getOpcode());
2135 GetElementPtrConstantExpr::
2136 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
2138 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2139 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2140 - (IdxList.size()+1), IdxList.size()+1) {
2142 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2143 OperandList[i+1] = IdxList[i];
2146 //===----------------------------------------------------------------------===//
2147 // ConstantData* implementations
2149 void ConstantDataArray::anchor() {}
2150 void ConstantDataVector::anchor() {}
2152 /// getElementType - Return the element type of the array/vector.
2153 Type *ConstantDataSequential::getElementType() const {
2154 return getType()->getElementType();
2157 StringRef ConstantDataSequential::getRawDataValues() const {
2158 return StringRef(DataElements, getNumElements()*getElementByteSize());
2161 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2162 /// formed with a vector or array of the specified element type.
2163 /// ConstantDataArray only works with normal float and int types that are
2164 /// stored densely in memory, not with things like i42 or x86_f80.
2165 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
2166 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2167 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2168 switch (IT->getBitWidth()) {
2180 /// getNumElements - Return the number of elements in the array or vector.
2181 unsigned ConstantDataSequential::getNumElements() const {
2182 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2183 return AT->getNumElements();
2184 return getType()->getVectorNumElements();
2188 /// getElementByteSize - Return the size in bytes of the elements in the data.
2189 uint64_t ConstantDataSequential::getElementByteSize() const {
2190 return getElementType()->getPrimitiveSizeInBits()/8;
2193 /// getElementPointer - Return the start of the specified element.
2194 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2195 assert(Elt < getNumElements() && "Invalid Elt");
2196 return DataElements+Elt*getElementByteSize();
2200 /// isAllZeros - return true if the array is empty or all zeros.
2201 static bool isAllZeros(StringRef Arr) {
2202 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2208 /// getImpl - This is the underlying implementation of all of the
2209 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2210 /// the correct element type. We take the bytes in as a StringRef because
2211 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2212 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2213 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2214 // If the elements are all zero or there are no elements, return a CAZ, which
2215 // is more dense and canonical.
2216 if (isAllZeros(Elements))
2217 return ConstantAggregateZero::get(Ty);
2219 // Do a lookup to see if we have already formed one of these.
2220 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2221 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2223 // The bucket can point to a linked list of different CDS's that have the same
2224 // body but different types. For example, 0,0,0,1 could be a 4 element array
2225 // of i8, or a 1-element array of i32. They'll both end up in the same
2226 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2227 ConstantDataSequential **Entry = &Slot.getValue();
2228 for (ConstantDataSequential *Node = *Entry; Node != 0;
2229 Entry = &Node->Next, Node = *Entry)
2230 if (Node->getType() == Ty)
2233 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2235 if (isa<ArrayType>(Ty))
2236 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2238 assert(isa<VectorType>(Ty));
2239 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2242 void ConstantDataSequential::destroyConstant() {
2243 // Remove the constant from the StringMap.
2244 StringMap<ConstantDataSequential*> &CDSConstants =
2245 getType()->getContext().pImpl->CDSConstants;
2247 StringMap<ConstantDataSequential*>::iterator Slot =
2248 CDSConstants.find(getRawDataValues());
2250 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2252 ConstantDataSequential **Entry = &Slot->getValue();
2254 // Remove the entry from the hash table.
2255 if ((*Entry)->Next == 0) {
2256 // If there is only one value in the bucket (common case) it must be this
2257 // entry, and removing the entry should remove the bucket completely.
2258 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2259 getContext().pImpl->CDSConstants.erase(Slot);
2261 // Otherwise, there are multiple entries linked off the bucket, unlink the
2262 // node we care about but keep the bucket around.
2263 for (ConstantDataSequential *Node = *Entry; ;
2264 Entry = &Node->Next, Node = *Entry) {
2265 assert(Node && "Didn't find entry in its uniquing hash table!");
2266 // If we found our entry, unlink it from the list and we're done.
2268 *Entry = Node->Next;
2274 // If we were part of a list, make sure that we don't delete the list that is
2275 // still owned by the uniquing map.
2278 // Finally, actually delete it.
2279 destroyConstantImpl();
2282 /// get() constructors - Return a constant with array type with an element
2283 /// count and element type matching the ArrayRef passed in. Note that this
2284 /// can return a ConstantAggregateZero object.
2285 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2286 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2287 const char *Data = reinterpret_cast<const char *>(Elts.data());
2288 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2290 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2291 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2292 const char *Data = reinterpret_cast<const char *>(Elts.data());
2293 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2295 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2296 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2297 const char *Data = reinterpret_cast<const char *>(Elts.data());
2298 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2300 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2301 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2302 const char *Data = reinterpret_cast<const char *>(Elts.data());
2303 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2305 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2306 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2307 const char *Data = reinterpret_cast<const char *>(Elts.data());
2308 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2310 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2311 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2312 const char *Data = reinterpret_cast<const char *>(Elts.data());
2313 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2316 /// getString - This method constructs a CDS and initializes it with a text
2317 /// string. The default behavior (AddNull==true) causes a null terminator to
2318 /// be placed at the end of the array (increasing the length of the string by
2319 /// one more than the StringRef would normally indicate. Pass AddNull=false
2320 /// to disable this behavior.
2321 Constant *ConstantDataArray::getString(LLVMContext &Context,
2322 StringRef Str, bool AddNull) {
2324 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2325 return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data),
2329 SmallVector<uint8_t, 64> ElementVals;
2330 ElementVals.append(Str.begin(), Str.end());
2331 ElementVals.push_back(0);
2332 return get(Context, ElementVals);
2335 /// get() constructors - Return a constant with vector type with an element
2336 /// count and element type matching the ArrayRef passed in. Note that this
2337 /// can return a ConstantAggregateZero object.
2338 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2339 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2340 const char *Data = reinterpret_cast<const char *>(Elts.data());
2341 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2343 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2344 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2345 const char *Data = reinterpret_cast<const char *>(Elts.data());
2346 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2348 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2349 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2350 const char *Data = reinterpret_cast<const char *>(Elts.data());
2351 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2353 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2354 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2355 const char *Data = reinterpret_cast<const char *>(Elts.data());
2356 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2358 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2359 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2360 const char *Data = reinterpret_cast<const char *>(Elts.data());
2361 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2363 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2364 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2365 const char *Data = reinterpret_cast<const char *>(Elts.data());
2366 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2369 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2370 assert(isElementTypeCompatible(V->getType()) &&
2371 "Element type not compatible with ConstantData");
2372 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2373 if (CI->getType()->isIntegerTy(8)) {
2374 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2375 return get(V->getContext(), Elts);
2377 if (CI->getType()->isIntegerTy(16)) {
2378 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2379 return get(V->getContext(), Elts);
2381 if (CI->getType()->isIntegerTy(32)) {
2382 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2383 return get(V->getContext(), Elts);
2385 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2386 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2387 return get(V->getContext(), Elts);
2390 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2391 if (CFP->getType()->isFloatTy()) {
2392 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2393 return get(V->getContext(), Elts);
2395 if (CFP->getType()->isDoubleTy()) {
2396 SmallVector<double, 16> Elts(NumElts,
2397 CFP->getValueAPF().convertToDouble());
2398 return get(V->getContext(), Elts);
2401 return ConstantVector::getSplat(NumElts, V);
2405 /// getElementAsInteger - If this is a sequential container of integers (of
2406 /// any size), return the specified element in the low bits of a uint64_t.
2407 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2408 assert(isa<IntegerType>(getElementType()) &&
2409 "Accessor can only be used when element is an integer");
2410 const char *EltPtr = getElementPointer(Elt);
2412 // The data is stored in host byte order, make sure to cast back to the right
2413 // type to load with the right endianness.
2414 switch (getElementType()->getIntegerBitWidth()) {
2415 default: llvm_unreachable("Invalid bitwidth for CDS");
2417 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2419 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2421 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2423 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2427 /// getElementAsAPFloat - If this is a sequential container of floating point
2428 /// type, return the specified element as an APFloat.
2429 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2430 const char *EltPtr = getElementPointer(Elt);
2432 switch (getElementType()->getTypeID()) {
2434 llvm_unreachable("Accessor can only be used when element is float/double!");
2435 case Type::FloatTyID: {
2436 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2437 return APFloat(*const_cast<float *>(FloatPrt));
2439 case Type::DoubleTyID: {
2440 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2441 return APFloat(*const_cast<double *>(DoublePtr));
2446 /// getElementAsFloat - If this is an sequential container of floats, return
2447 /// the specified element as a float.
2448 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2449 assert(getElementType()->isFloatTy() &&
2450 "Accessor can only be used when element is a 'float'");
2451 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2452 return *const_cast<float *>(EltPtr);
2455 /// getElementAsDouble - If this is an sequential container of doubles, return
2456 /// the specified element as a float.
2457 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2458 assert(getElementType()->isDoubleTy() &&
2459 "Accessor can only be used when element is a 'float'");
2460 const double *EltPtr =
2461 reinterpret_cast<const double *>(getElementPointer(Elt));
2462 return *const_cast<double *>(EltPtr);
2465 /// getElementAsConstant - Return a Constant for a specified index's element.
2466 /// Note that this has to compute a new constant to return, so it isn't as
2467 /// efficient as getElementAsInteger/Float/Double.
2468 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2469 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2470 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2472 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2475 /// isString - This method returns true if this is an array of i8.
2476 bool ConstantDataSequential::isString() const {
2477 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2480 /// isCString - This method returns true if the array "isString", ends with a
2481 /// nul byte, and does not contains any other nul bytes.
2482 bool ConstantDataSequential::isCString() const {
2486 StringRef Str = getAsString();
2488 // The last value must be nul.
2489 if (Str.back() != 0) return false;
2491 // Other elements must be non-nul.
2492 return Str.drop_back().find(0) == StringRef::npos;
2495 /// getSplatValue - If this is a splat constant, meaning that all of the
2496 /// elements have the same value, return that value. Otherwise return NULL.
2497 Constant *ConstantDataVector::getSplatValue() const {
2498 const char *Base = getRawDataValues().data();
2500 // Compare elements 1+ to the 0'th element.
2501 unsigned EltSize = getElementByteSize();
2502 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2503 if (memcmp(Base, Base+i*EltSize, EltSize))
2506 // If they're all the same, return the 0th one as a representative.
2507 return getElementAsConstant(0);
2510 //===----------------------------------------------------------------------===//
2511 // replaceUsesOfWithOnConstant implementations
2513 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2514 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2517 /// Note that we intentionally replace all uses of From with To here. Consider
2518 /// a large array that uses 'From' 1000 times. By handling this case all here,
2519 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2520 /// single invocation handles all 1000 uses. Handling them one at a time would
2521 /// work, but would be really slow because it would have to unique each updated
2524 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2526 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2527 Constant *ToC = cast<Constant>(To);
2529 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
2531 SmallVector<Constant*, 8> Values;
2532 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2533 Lookup.first = cast<ArrayType>(getType());
2534 Values.reserve(getNumOperands()); // Build replacement array.
2536 // Fill values with the modified operands of the constant array. Also,
2537 // compute whether this turns into an all-zeros array.
2538 unsigned NumUpdated = 0;
2540 // Keep track of whether all the values in the array are "ToC".
2541 bool AllSame = true;
2542 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2543 Constant *Val = cast<Constant>(O->get());
2548 Values.push_back(Val);
2549 AllSame &= Val == ToC;
2552 Constant *Replacement = 0;
2553 if (AllSame && ToC->isNullValue()) {
2554 Replacement = ConstantAggregateZero::get(getType());
2555 } else if (AllSame && isa<UndefValue>(ToC)) {
2556 Replacement = UndefValue::get(getType());
2558 // Check to see if we have this array type already.
2559 Lookup.second = makeArrayRef(Values);
2560 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2561 pImpl->ArrayConstants.find(Lookup);
2563 if (I != pImpl->ArrayConstants.map_end()) {
2564 Replacement = I->first;
2566 // Okay, the new shape doesn't exist in the system yet. Instead of
2567 // creating a new constant array, inserting it, replaceallusesof'ing the
2568 // old with the new, then deleting the old... just update the current one
2570 pImpl->ArrayConstants.remove(this);
2572 // Update to the new value. Optimize for the case when we have a single
2573 // operand that we're changing, but handle bulk updates efficiently.
2574 if (NumUpdated == 1) {
2575 unsigned OperandToUpdate = U - OperandList;
2576 assert(getOperand(OperandToUpdate) == From &&
2577 "ReplaceAllUsesWith broken!");
2578 setOperand(OperandToUpdate, ToC);
2580 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2581 if (getOperand(i) == From)
2584 pImpl->ArrayConstants.insert(this);
2589 // Otherwise, I do need to replace this with an existing value.
2590 assert(Replacement != this && "I didn't contain From!");
2592 // Everyone using this now uses the replacement.
2593 replaceAllUsesWith(Replacement);
2595 // Delete the old constant!
2599 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2601 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2602 Constant *ToC = cast<Constant>(To);
2604 unsigned OperandToUpdate = U-OperandList;
2605 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2607 SmallVector<Constant*, 8> Values;
2608 LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2609 Lookup.first = cast<StructType>(getType());
2610 Values.reserve(getNumOperands()); // Build replacement struct.
2612 // Fill values with the modified operands of the constant struct. Also,
2613 // compute whether this turns into an all-zeros struct.
2614 bool isAllZeros = false;
2615 bool isAllUndef = false;
2616 if (ToC->isNullValue()) {
2618 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2619 Constant *Val = cast<Constant>(O->get());
2620 Values.push_back(Val);
2621 if (isAllZeros) isAllZeros = Val->isNullValue();
2623 } else if (isa<UndefValue>(ToC)) {
2625 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2626 Constant *Val = cast<Constant>(O->get());
2627 Values.push_back(Val);
2628 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2631 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2632 Values.push_back(cast<Constant>(O->get()));
2634 Values[OperandToUpdate] = ToC;
2636 LLVMContextImpl *pImpl = getContext().pImpl;
2638 Constant *Replacement = 0;
2640 Replacement = ConstantAggregateZero::get(getType());
2641 } else if (isAllUndef) {
2642 Replacement = UndefValue::get(getType());
2644 // Check to see if we have this struct type already.
2645 Lookup.second = makeArrayRef(Values);
2646 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2647 pImpl->StructConstants.find(Lookup);
2649 if (I != pImpl->StructConstants.map_end()) {
2650 Replacement = I->first;
2652 // Okay, the new shape doesn't exist in the system yet. Instead of
2653 // creating a new constant struct, inserting it, replaceallusesof'ing the
2654 // old with the new, then deleting the old... just update the current one
2656 pImpl->StructConstants.remove(this);
2658 // Update to the new value.
2659 setOperand(OperandToUpdate, ToC);
2660 pImpl->StructConstants.insert(this);
2665 assert(Replacement != this && "I didn't contain From!");
2667 // Everyone using this now uses the replacement.
2668 replaceAllUsesWith(Replacement);
2670 // Delete the old constant!
2674 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2676 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2678 SmallVector<Constant*, 8> Values;
2679 Values.reserve(getNumOperands()); // Build replacement array...
2680 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2681 Constant *Val = getOperand(i);
2682 if (Val == From) Val = cast<Constant>(To);
2683 Values.push_back(Val);
2686 Constant *Replacement = get(Values);
2687 assert(Replacement != this && "I didn't contain From!");
2689 // Everyone using this now uses the replacement.
2690 replaceAllUsesWith(Replacement);
2692 // Delete the old constant!
2696 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2698 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2699 Constant *To = cast<Constant>(ToV);
2701 SmallVector<Constant*, 8> NewOps;
2702 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2703 Constant *Op = getOperand(i);
2704 NewOps.push_back(Op == From ? To : Op);
2707 Constant *Replacement = getWithOperands(NewOps);
2708 assert(Replacement != this && "I didn't contain From!");
2710 // Everyone using this now uses the replacement.
2711 replaceAllUsesWith(Replacement);
2713 // Delete the old constant!
2717 Instruction *ConstantExpr::getAsInstruction() {
2718 SmallVector<Value*,4> ValueOperands;
2719 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2720 ValueOperands.push_back(cast<Value>(I));
2722 ArrayRef<Value*> Ops(ValueOperands);
2724 switch (getOpcode()) {
2725 case Instruction::Trunc:
2726 case Instruction::ZExt:
2727 case Instruction::SExt:
2728 case Instruction::FPTrunc:
2729 case Instruction::FPExt:
2730 case Instruction::UIToFP:
2731 case Instruction::SIToFP:
2732 case Instruction::FPToUI:
2733 case Instruction::FPToSI:
2734 case Instruction::PtrToInt:
2735 case Instruction::IntToPtr:
2736 case Instruction::BitCast:
2737 return CastInst::Create((Instruction::CastOps)getOpcode(),
2739 case Instruction::Select:
2740 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2741 case Instruction::InsertElement:
2742 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2743 case Instruction::ExtractElement:
2744 return ExtractElementInst::Create(Ops[0], Ops[1]);
2745 case Instruction::InsertValue:
2746 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2747 case Instruction::ExtractValue:
2748 return ExtractValueInst::Create(Ops[0], getIndices());
2749 case Instruction::ShuffleVector:
2750 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2752 case Instruction::GetElementPtr:
2753 if (cast<GEPOperator>(this)->isInBounds())
2754 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2756 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2758 case Instruction::ICmp:
2759 case Instruction::FCmp:
2760 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2761 getPredicate(), Ops[0], Ops[1]);
2764 assert(getNumOperands() == 2 && "Must be binary operator?");
2765 BinaryOperator *BO =
2766 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2768 if (isa<OverflowingBinaryOperator>(BO)) {
2769 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2770 OverflowingBinaryOperator::NoUnsignedWrap);
2771 BO->setHasNoSignedWrap(SubclassOptionalData &
2772 OverflowingBinaryOperator::NoSignedWrap);
2774 if (isa<PossiblyExactOperator>(BO))
2775 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);