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/GetElementPtrTypeIterator.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.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 // Equivalent for a vector of -0.0's.
51 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
52 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
56 // We've already handled true FP case; any other FP vectors can't represent -0.0.
57 if (getType()->isFPOrFPVectorTy())
60 // Otherwise, just use +0.0.
64 // Return true iff this constant is positive zero (floating point), negative
65 // zero (floating point), or a null value.
66 bool Constant::isZeroValue() const {
67 // Floating point values have an explicit -0.0 value.
68 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
71 // Otherwise, just use +0.0.
75 bool Constant::isNullValue() const {
77 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
81 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
82 return CFP->isZero() && !CFP->isNegative();
84 // constant zero is zero for aggregates and cpnull is null for pointers.
85 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
88 bool Constant::isAllOnesValue() const {
89 // Check for -1 integers
90 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
91 return CI->isMinusOne();
93 // Check for FP which are bitcasted from -1 integers
94 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
95 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
97 // Check for constant vectors which are splats of -1 values.
98 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
99 if (Constant *Splat = CV->getSplatValue())
100 return Splat->isAllOnesValue();
102 // Check for constant vectors which are splats of -1 values.
103 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
104 if (Constant *Splat = CV->getSplatValue())
105 return Splat->isAllOnesValue();
110 // Constructor to create a '0' constant of arbitrary type...
111 Constant *Constant::getNullValue(Type *Ty) {
112 switch (Ty->getTypeID()) {
113 case Type::IntegerTyID:
114 return ConstantInt::get(Ty, 0);
116 return ConstantFP::get(Ty->getContext(),
117 APFloat::getZero(APFloat::IEEEhalf));
118 case Type::FloatTyID:
119 return ConstantFP::get(Ty->getContext(),
120 APFloat::getZero(APFloat::IEEEsingle));
121 case Type::DoubleTyID:
122 return ConstantFP::get(Ty->getContext(),
123 APFloat::getZero(APFloat::IEEEdouble));
124 case Type::X86_FP80TyID:
125 return ConstantFP::get(Ty->getContext(),
126 APFloat::getZero(APFloat::x87DoubleExtended));
127 case Type::FP128TyID:
128 return ConstantFP::get(Ty->getContext(),
129 APFloat::getZero(APFloat::IEEEquad));
130 case Type::PPC_FP128TyID:
131 return ConstantFP::get(Ty->getContext(),
132 APFloat(APFloat::PPCDoubleDouble,
133 APInt::getNullValue(128)));
134 case Type::PointerTyID:
135 return ConstantPointerNull::get(cast<PointerType>(Ty));
136 case Type::StructTyID:
137 case Type::ArrayTyID:
138 case Type::VectorTyID:
139 return ConstantAggregateZero::get(Ty);
141 // Function, Label, or Opaque type?
142 llvm_unreachable("Cannot create a null constant of that type!");
146 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
147 Type *ScalarTy = Ty->getScalarType();
149 // Create the base integer constant.
150 Constant *C = ConstantInt::get(Ty->getContext(), V);
152 // Convert an integer to a pointer, if necessary.
153 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
154 C = ConstantExpr::getIntToPtr(C, PTy);
156 // Broadcast a scalar to a vector, if necessary.
157 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
158 C = ConstantVector::getSplat(VTy->getNumElements(), C);
163 Constant *Constant::getAllOnesValue(Type *Ty) {
164 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
165 return ConstantInt::get(Ty->getContext(),
166 APInt::getAllOnesValue(ITy->getBitWidth()));
168 if (Ty->isFloatingPointTy()) {
169 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
170 !Ty->isPPC_FP128Ty());
171 return ConstantFP::get(Ty->getContext(), FL);
174 VectorType *VTy = cast<VectorType>(Ty);
175 return ConstantVector::getSplat(VTy->getNumElements(),
176 getAllOnesValue(VTy->getElementType()));
179 /// getAggregateElement - For aggregates (struct/array/vector) return the
180 /// constant that corresponds to the specified element if possible, or null if
181 /// not. This can return null if the element index is a ConstantExpr, or if
182 /// 'this' is a constant expr.
183 Constant *Constant::getAggregateElement(unsigned Elt) const {
184 if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
185 return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
187 if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
188 return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
190 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
191 return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
193 if (const ConstantAggregateZero *CAZ =dyn_cast<ConstantAggregateZero>(this))
194 return CAZ->getElementValue(Elt);
196 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
197 return UV->getElementValue(Elt);
199 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
200 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
205 Constant *Constant::getAggregateElement(Constant *Elt) const {
206 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
207 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
208 return getAggregateElement(CI->getZExtValue());
213 void Constant::destroyConstantImpl() {
214 // When a Constant is destroyed, there may be lingering
215 // references to the constant by other constants in the constant pool. These
216 // constants are implicitly dependent on the module that is being deleted,
217 // but they don't know that. Because we only find out when the CPV is
218 // deleted, we must now notify all of our users (that should only be
219 // Constants) that they are, in fact, invalid now and should be deleted.
221 while (!use_empty()) {
222 Value *V = user_back();
223 #ifndef NDEBUG // Only in -g mode...
224 if (!isa<Constant>(V)) {
225 dbgs() << "While deleting: " << *this
226 << "\n\nUse still stuck around after Def is destroyed: "
230 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
231 cast<Constant>(V)->destroyConstant();
233 // The constant should remove itself from our use list...
234 assert((use_empty() || user_back() != V) && "Constant not removed!");
237 // Value has no outstanding references it is safe to delete it now...
241 static bool canTrapImpl(const Constant *C,
242 SmallPtrSet<const ConstantExpr *, 4> &NonTrappingOps) {
243 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
244 // The only thing that could possibly trap are constant exprs.
245 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
249 // ConstantExpr traps if any operands can trap.
250 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
251 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
252 if (NonTrappingOps.insert(Op) && canTrapImpl(Op, NonTrappingOps))
257 // Otherwise, only specific operations can trap.
258 switch (CE->getOpcode()) {
261 case Instruction::UDiv:
262 case Instruction::SDiv:
263 case Instruction::FDiv:
264 case Instruction::URem:
265 case Instruction::SRem:
266 case Instruction::FRem:
267 // Div and rem can trap if the RHS is not known to be non-zero.
268 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
274 /// canTrap - Return true if evaluation of this constant could trap. This is
275 /// true for things like constant expressions that could divide by zero.
276 bool Constant::canTrap() const {
277 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
278 return canTrapImpl(this, NonTrappingOps);
281 /// Check if C contains a GlobalValue for which Predicate is true.
283 ConstHasGlobalValuePredicate(const Constant *C,
284 bool (*Predicate)(const GlobalValue *)) {
285 SmallPtrSet<const Constant *, 8> Visited;
286 SmallVector<const Constant *, 8> WorkList;
287 WorkList.push_back(C);
290 while (!WorkList.empty()) {
291 const Constant *WorkItem = WorkList.pop_back_val();
292 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
295 for (const Value *Op : WorkItem->operands()) {
296 const Constant *ConstOp = dyn_cast<Constant>(Op);
299 if (Visited.insert(ConstOp))
300 WorkList.push_back(ConstOp);
306 /// Return true if the value can vary between threads.
307 bool Constant::isThreadDependent() const {
308 auto DLLImportPredicate = [](const GlobalValue *GV) {
309 return GV->isThreadLocal();
311 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
314 bool Constant::isDLLImportDependent() const {
315 auto DLLImportPredicate = [](const GlobalValue *GV) {
316 return GV->hasDLLImportStorageClass();
318 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
321 /// Return true if the constant has users other than constant exprs and other
323 bool Constant::isConstantUsed() const {
324 for (const User *U : users()) {
325 const Constant *UC = dyn_cast<Constant>(U);
326 if (!UC || isa<GlobalValue>(UC))
329 if (UC->isConstantUsed())
337 /// getRelocationInfo - This method classifies the entry according to
338 /// whether or not it may generate a relocation entry. This must be
339 /// conservative, so if it might codegen to a relocatable entry, it should say
340 /// so. The return values are:
342 /// NoRelocation: This constant pool entry is guaranteed to never have a
343 /// relocation applied to it (because it holds a simple constant like
345 /// LocalRelocation: This entry has relocations, but the entries are
346 /// guaranteed to be resolvable by the static linker, so the dynamic
347 /// linker will never see them.
348 /// GlobalRelocations: This entry may have arbitrary relocations.
350 /// FIXME: This really should not be in IR.
351 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
352 if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
353 if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
354 return LocalRelocation; // Local to this file/library.
355 return GlobalRelocations; // Global reference.
358 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
359 return BA->getFunction()->getRelocationInfo();
361 // While raw uses of blockaddress need to be relocated, differences between
362 // two of them don't when they are for labels in the same function. This is a
363 // common idiom when creating a table for the indirect goto extension, so we
364 // handle it efficiently here.
365 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
366 if (CE->getOpcode() == Instruction::Sub) {
367 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
368 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
370 LHS->getOpcode() == Instruction::PtrToInt &&
371 RHS->getOpcode() == Instruction::PtrToInt &&
372 isa<BlockAddress>(LHS->getOperand(0)) &&
373 isa<BlockAddress>(RHS->getOperand(0)) &&
374 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
375 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
379 PossibleRelocationsTy Result = NoRelocation;
380 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
381 Result = std::max(Result,
382 cast<Constant>(getOperand(i))->getRelocationInfo());
387 /// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
388 /// it. This involves recursively eliminating any dead users of the
390 static bool removeDeadUsersOfConstant(const Constant *C) {
391 if (isa<GlobalValue>(C)) return false; // Cannot remove this
393 while (!C->use_empty()) {
394 const Constant *User = dyn_cast<Constant>(C->user_back());
395 if (!User) return false; // Non-constant usage;
396 if (!removeDeadUsersOfConstant(User))
397 return false; // Constant wasn't dead
400 const_cast<Constant*>(C)->destroyConstant();
405 /// removeDeadConstantUsers - If there are any dead constant users dangling
406 /// off of this constant, remove them. This method is useful for clients
407 /// that want to check to see if a global is unused, but don't want to deal
408 /// with potentially dead constants hanging off of the globals.
409 void Constant::removeDeadConstantUsers() const {
410 Value::const_user_iterator I = user_begin(), E = user_end();
411 Value::const_user_iterator LastNonDeadUser = E;
413 const Constant *User = dyn_cast<Constant>(*I);
420 if (!removeDeadUsersOfConstant(User)) {
421 // If the constant wasn't dead, remember that this was the last live use
422 // and move on to the next constant.
428 // If the constant was dead, then the iterator is invalidated.
429 if (LastNonDeadUser == E) {
441 //===----------------------------------------------------------------------===//
443 //===----------------------------------------------------------------------===//
445 void ConstantInt::anchor() { }
447 ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
448 : Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
449 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
452 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
453 LLVMContextImpl *pImpl = Context.pImpl;
454 if (!pImpl->TheTrueVal)
455 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
456 return pImpl->TheTrueVal;
459 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
460 LLVMContextImpl *pImpl = Context.pImpl;
461 if (!pImpl->TheFalseVal)
462 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
463 return pImpl->TheFalseVal;
466 Constant *ConstantInt::getTrue(Type *Ty) {
467 VectorType *VTy = dyn_cast<VectorType>(Ty);
469 assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
470 return ConstantInt::getTrue(Ty->getContext());
472 assert(VTy->getElementType()->isIntegerTy(1) &&
473 "True must be vector of i1 or i1.");
474 return ConstantVector::getSplat(VTy->getNumElements(),
475 ConstantInt::getTrue(Ty->getContext()));
478 Constant *ConstantInt::getFalse(Type *Ty) {
479 VectorType *VTy = dyn_cast<VectorType>(Ty);
481 assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
482 return ConstantInt::getFalse(Ty->getContext());
484 assert(VTy->getElementType()->isIntegerTy(1) &&
485 "False must be vector of i1 or i1.");
486 return ConstantVector::getSplat(VTy->getNumElements(),
487 ConstantInt::getFalse(Ty->getContext()));
491 // Get a ConstantInt from an APInt. Note that the value stored in the DenseMap
492 // as the key, is a DenseMapAPIntKeyInfo::KeyTy which has provided the
493 // operator== and operator!= to ensure that the DenseMap doesn't attempt to
494 // compare APInt's of different widths, which would violate an APInt class
495 // invariant which generates an assertion.
496 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
497 // Get the corresponding integer type for the bit width of the value.
498 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
499 // get an existing value or the insertion position
500 LLVMContextImpl *pImpl = Context.pImpl;
501 ConstantInt *&Slot = pImpl->IntConstants[DenseMapAPIntKeyInfo::KeyTy(V, ITy)];
502 if (!Slot) Slot = new ConstantInt(ITy, V);
506 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
507 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
509 // For vectors, broadcast the value.
510 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
511 return ConstantVector::getSplat(VTy->getNumElements(), C);
516 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
518 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
521 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
522 return get(Ty, V, true);
525 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
526 return get(Ty, V, true);
529 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
530 ConstantInt *C = get(Ty->getContext(), V);
531 assert(C->getType() == Ty->getScalarType() &&
532 "ConstantInt type doesn't match the type implied by its value!");
534 // For vectors, broadcast the value.
535 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
536 return ConstantVector::getSplat(VTy->getNumElements(), C);
541 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
543 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
546 //===----------------------------------------------------------------------===//
548 //===----------------------------------------------------------------------===//
550 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
552 return &APFloat::IEEEhalf;
554 return &APFloat::IEEEsingle;
555 if (Ty->isDoubleTy())
556 return &APFloat::IEEEdouble;
557 if (Ty->isX86_FP80Ty())
558 return &APFloat::x87DoubleExtended;
559 else if (Ty->isFP128Ty())
560 return &APFloat::IEEEquad;
562 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
563 return &APFloat::PPCDoubleDouble;
566 void ConstantFP::anchor() { }
568 /// get() - This returns a constant fp for the specified value in the
569 /// specified type. This should only be used for simple constant values like
570 /// 2.0/1.0 etc, that are known-valid both as double and as the target format.
571 Constant *ConstantFP::get(Type *Ty, double V) {
572 LLVMContext &Context = Ty->getContext();
576 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
577 APFloat::rmNearestTiesToEven, &ignored);
578 Constant *C = get(Context, FV);
580 // For vectors, broadcast the value.
581 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
582 return ConstantVector::getSplat(VTy->getNumElements(), C);
588 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
589 LLVMContext &Context = Ty->getContext();
591 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
592 Constant *C = get(Context, FV);
594 // For vectors, broadcast the value.
595 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
596 return ConstantVector::getSplat(VTy->getNumElements(), C);
601 Constant *ConstantFP::getNegativeZero(Type *Ty) {
602 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
603 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
604 Constant *C = get(Ty->getContext(), NegZero);
606 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
607 return ConstantVector::getSplat(VTy->getNumElements(), C);
613 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
614 if (Ty->isFPOrFPVectorTy())
615 return getNegativeZero(Ty);
617 return Constant::getNullValue(Ty);
621 // ConstantFP accessors.
622 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
623 LLVMContextImpl* pImpl = Context.pImpl;
625 ConstantFP *&Slot = pImpl->FPConstants[DenseMapAPFloatKeyInfo::KeyTy(V)];
629 if (&V.getSemantics() == &APFloat::IEEEhalf)
630 Ty = Type::getHalfTy(Context);
631 else if (&V.getSemantics() == &APFloat::IEEEsingle)
632 Ty = Type::getFloatTy(Context);
633 else if (&V.getSemantics() == &APFloat::IEEEdouble)
634 Ty = Type::getDoubleTy(Context);
635 else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
636 Ty = Type::getX86_FP80Ty(Context);
637 else if (&V.getSemantics() == &APFloat::IEEEquad)
638 Ty = Type::getFP128Ty(Context);
640 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
641 "Unknown FP format");
642 Ty = Type::getPPC_FP128Ty(Context);
644 Slot = new ConstantFP(Ty, V);
650 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
651 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
652 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
654 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
655 return ConstantVector::getSplat(VTy->getNumElements(), C);
660 ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
661 : Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
662 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
666 bool ConstantFP::isExactlyValue(const APFloat &V) const {
667 return Val.bitwiseIsEqual(V);
670 //===----------------------------------------------------------------------===//
671 // ConstantAggregateZero Implementation
672 //===----------------------------------------------------------------------===//
674 /// getSequentialElement - If this CAZ has array or vector type, return a zero
675 /// with the right element type.
676 Constant *ConstantAggregateZero::getSequentialElement() const {
677 return Constant::getNullValue(getType()->getSequentialElementType());
680 /// getStructElement - If this CAZ has struct type, return a zero with the
681 /// right element type for the specified element.
682 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
683 return Constant::getNullValue(getType()->getStructElementType(Elt));
686 /// getElementValue - Return a zero of the right value for the specified GEP
687 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
688 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
689 if (isa<SequentialType>(getType()))
690 return getSequentialElement();
691 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
694 /// getElementValue - Return a zero of the right value for the specified GEP
696 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
697 if (isa<SequentialType>(getType()))
698 return getSequentialElement();
699 return getStructElement(Idx);
703 //===----------------------------------------------------------------------===//
704 // UndefValue Implementation
705 //===----------------------------------------------------------------------===//
707 /// getSequentialElement - If this undef has array or vector type, return an
708 /// undef with the right element type.
709 UndefValue *UndefValue::getSequentialElement() const {
710 return UndefValue::get(getType()->getSequentialElementType());
713 /// getStructElement - If this undef has struct type, return a zero with the
714 /// right element type for the specified element.
715 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
716 return UndefValue::get(getType()->getStructElementType(Elt));
719 /// getElementValue - Return an undef of the right value for the specified GEP
720 /// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
721 UndefValue *UndefValue::getElementValue(Constant *C) const {
722 if (isa<SequentialType>(getType()))
723 return getSequentialElement();
724 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
727 /// getElementValue - Return an undef of the right value for the specified GEP
729 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
730 if (isa<SequentialType>(getType()))
731 return getSequentialElement();
732 return getStructElement(Idx);
737 //===----------------------------------------------------------------------===//
738 // ConstantXXX Classes
739 //===----------------------------------------------------------------------===//
741 template <typename ItTy, typename EltTy>
742 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
743 for (; Start != End; ++Start)
749 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
750 : Constant(T, ConstantArrayVal,
751 OperandTraits<ConstantArray>::op_end(this) - V.size(),
753 assert(V.size() == T->getNumElements() &&
754 "Invalid initializer vector for constant array");
755 for (unsigned i = 0, e = V.size(); i != e; ++i)
756 assert(V[i]->getType() == T->getElementType() &&
757 "Initializer for array element doesn't match array element type!");
758 std::copy(V.begin(), V.end(), op_begin());
761 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
762 // Empty arrays are canonicalized to ConstantAggregateZero.
764 return ConstantAggregateZero::get(Ty);
766 for (unsigned i = 0, e = V.size(); i != e; ++i) {
767 assert(V[i]->getType() == Ty->getElementType() &&
768 "Wrong type in array element initializer");
770 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
772 // If this is an all-zero array, return a ConstantAggregateZero object. If
773 // all undef, return an UndefValue, if "all simple", then return a
774 // ConstantDataArray.
776 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
777 return UndefValue::get(Ty);
779 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
780 return ConstantAggregateZero::get(Ty);
782 // Check to see if all of the elements are ConstantFP or ConstantInt and if
783 // the element type is compatible with ConstantDataVector. If so, use it.
784 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
785 // We speculatively build the elements here even if it turns out that there
786 // is a constantexpr or something else weird in the array, since it is so
787 // uncommon for that to happen.
788 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
789 if (CI->getType()->isIntegerTy(8)) {
790 SmallVector<uint8_t, 16> Elts;
791 for (unsigned i = 0, e = V.size(); i != e; ++i)
792 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
793 Elts.push_back(CI->getZExtValue());
796 if (Elts.size() == V.size())
797 return ConstantDataArray::get(C->getContext(), Elts);
798 } else if (CI->getType()->isIntegerTy(16)) {
799 SmallVector<uint16_t, 16> Elts;
800 for (unsigned i = 0, e = V.size(); i != e; ++i)
801 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
802 Elts.push_back(CI->getZExtValue());
805 if (Elts.size() == V.size())
806 return ConstantDataArray::get(C->getContext(), Elts);
807 } else if (CI->getType()->isIntegerTy(32)) {
808 SmallVector<uint32_t, 16> Elts;
809 for (unsigned i = 0, e = V.size(); i != e; ++i)
810 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
811 Elts.push_back(CI->getZExtValue());
814 if (Elts.size() == V.size())
815 return ConstantDataArray::get(C->getContext(), Elts);
816 } else if (CI->getType()->isIntegerTy(64)) {
817 SmallVector<uint64_t, 16> Elts;
818 for (unsigned i = 0, e = V.size(); i != e; ++i)
819 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
820 Elts.push_back(CI->getZExtValue());
823 if (Elts.size() == V.size())
824 return ConstantDataArray::get(C->getContext(), Elts);
828 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
829 if (CFP->getType()->isFloatTy()) {
830 SmallVector<float, 16> Elts;
831 for (unsigned i = 0, e = V.size(); i != e; ++i)
832 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
833 Elts.push_back(CFP->getValueAPF().convertToFloat());
836 if (Elts.size() == V.size())
837 return ConstantDataArray::get(C->getContext(), Elts);
838 } else if (CFP->getType()->isDoubleTy()) {
839 SmallVector<double, 16> Elts;
840 for (unsigned i = 0, e = V.size(); i != e; ++i)
841 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
842 Elts.push_back(CFP->getValueAPF().convertToDouble());
845 if (Elts.size() == V.size())
846 return ConstantDataArray::get(C->getContext(), Elts);
851 // Otherwise, we really do want to create a ConstantArray.
852 return pImpl->ArrayConstants.getOrCreate(Ty, V);
855 /// getTypeForElements - Return an anonymous struct type to use for a constant
856 /// with the specified set of elements. The list must not be empty.
857 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
858 ArrayRef<Constant*> V,
860 unsigned VecSize = V.size();
861 SmallVector<Type*, 16> EltTypes(VecSize);
862 for (unsigned i = 0; i != VecSize; ++i)
863 EltTypes[i] = V[i]->getType();
865 return StructType::get(Context, EltTypes, Packed);
869 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
872 "ConstantStruct::getTypeForElements cannot be called on empty list");
873 return getTypeForElements(V[0]->getContext(), V, Packed);
877 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
878 : Constant(T, ConstantStructVal,
879 OperandTraits<ConstantStruct>::op_end(this) - V.size(),
881 assert(V.size() == T->getNumElements() &&
882 "Invalid initializer vector for constant structure");
883 for (unsigned i = 0, e = V.size(); i != e; ++i)
884 assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
885 "Initializer for struct element doesn't match struct element type!");
886 std::copy(V.begin(), V.end(), op_begin());
889 // ConstantStruct accessors.
890 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
891 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
892 "Incorrect # elements specified to ConstantStruct::get");
894 // Create a ConstantAggregateZero value if all elements are zeros.
896 bool isUndef = false;
899 isUndef = isa<UndefValue>(V[0]);
900 isZero = V[0]->isNullValue();
901 if (isUndef || isZero) {
902 for (unsigned i = 0, e = V.size(); i != e; ++i) {
903 if (!V[i]->isNullValue())
905 if (!isa<UndefValue>(V[i]))
911 return ConstantAggregateZero::get(ST);
913 return UndefValue::get(ST);
915 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
918 Constant *ConstantStruct::get(StructType *T, ...) {
920 SmallVector<Constant*, 8> Values;
922 while (Constant *Val = va_arg(ap, llvm::Constant*))
923 Values.push_back(Val);
925 return get(T, Values);
928 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
929 : Constant(T, ConstantVectorVal,
930 OperandTraits<ConstantVector>::op_end(this) - V.size(),
932 for (size_t i = 0, e = V.size(); i != e; i++)
933 assert(V[i]->getType() == T->getElementType() &&
934 "Initializer for vector element doesn't match vector element type!");
935 std::copy(V.begin(), V.end(), op_begin());
938 // ConstantVector accessors.
939 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
940 assert(!V.empty() && "Vectors can't be empty");
941 VectorType *T = VectorType::get(V.front()->getType(), V.size());
942 LLVMContextImpl *pImpl = T->getContext().pImpl;
944 // If this is an all-undef or all-zero vector, return a
945 // ConstantAggregateZero or UndefValue.
947 bool isZero = C->isNullValue();
948 bool isUndef = isa<UndefValue>(C);
950 if (isZero || isUndef) {
951 for (unsigned i = 1, e = V.size(); i != e; ++i)
953 isZero = isUndef = false;
959 return ConstantAggregateZero::get(T);
961 return UndefValue::get(T);
963 // Check to see if all of the elements are ConstantFP or ConstantInt and if
964 // the element type is compatible with ConstantDataVector. If so, use it.
965 if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
966 // We speculatively build the elements here even if it turns out that there
967 // is a constantexpr or something else weird in the array, since it is so
968 // uncommon for that to happen.
969 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
970 if (CI->getType()->isIntegerTy(8)) {
971 SmallVector<uint8_t, 16> Elts;
972 for (unsigned i = 0, e = V.size(); i != e; ++i)
973 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
974 Elts.push_back(CI->getZExtValue());
977 if (Elts.size() == V.size())
978 return ConstantDataVector::get(C->getContext(), Elts);
979 } else if (CI->getType()->isIntegerTy(16)) {
980 SmallVector<uint16_t, 16> Elts;
981 for (unsigned i = 0, e = V.size(); i != e; ++i)
982 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
983 Elts.push_back(CI->getZExtValue());
986 if (Elts.size() == V.size())
987 return ConstantDataVector::get(C->getContext(), Elts);
988 } else if (CI->getType()->isIntegerTy(32)) {
989 SmallVector<uint32_t, 16> Elts;
990 for (unsigned i = 0, e = V.size(); i != e; ++i)
991 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
992 Elts.push_back(CI->getZExtValue());
995 if (Elts.size() == V.size())
996 return ConstantDataVector::get(C->getContext(), Elts);
997 } else if (CI->getType()->isIntegerTy(64)) {
998 SmallVector<uint64_t, 16> Elts;
999 for (unsigned i = 0, e = V.size(); i != e; ++i)
1000 if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
1001 Elts.push_back(CI->getZExtValue());
1004 if (Elts.size() == V.size())
1005 return ConstantDataVector::get(C->getContext(), Elts);
1009 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1010 if (CFP->getType()->isFloatTy()) {
1011 SmallVector<float, 16> Elts;
1012 for (unsigned i = 0, e = V.size(); i != e; ++i)
1013 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
1014 Elts.push_back(CFP->getValueAPF().convertToFloat());
1017 if (Elts.size() == V.size())
1018 return ConstantDataVector::get(C->getContext(), Elts);
1019 } else if (CFP->getType()->isDoubleTy()) {
1020 SmallVector<double, 16> Elts;
1021 for (unsigned i = 0, e = V.size(); i != e; ++i)
1022 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
1023 Elts.push_back(CFP->getValueAPF().convertToDouble());
1026 if (Elts.size() == V.size())
1027 return ConstantDataVector::get(C->getContext(), Elts);
1032 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1033 // the operand list constants a ConstantExpr or something else strange.
1034 return pImpl->VectorConstants.getOrCreate(T, V);
1037 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1038 // If this splat is compatible with ConstantDataVector, use it instead of
1040 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1041 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1042 return ConstantDataVector::getSplat(NumElts, V);
1044 SmallVector<Constant*, 32> Elts(NumElts, V);
1049 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1050 // can't be inline because we don't want to #include Instruction.h into
1052 bool ConstantExpr::isCast() const {
1053 return Instruction::isCast(getOpcode());
1056 bool ConstantExpr::isCompare() const {
1057 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1060 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1061 if (getOpcode() != Instruction::GetElementPtr) return false;
1063 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1064 User::const_op_iterator OI = std::next(this->op_begin());
1066 // Skip the first index, as it has no static limit.
1070 // The remaining indices must be compile-time known integers within the
1071 // bounds of the corresponding notional static array types.
1072 for (; GEPI != E; ++GEPI, ++OI) {
1073 ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
1074 if (!CI) return false;
1075 if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
1076 if (CI->getValue().getActiveBits() > 64 ||
1077 CI->getZExtValue() >= ATy->getNumElements())
1081 // All the indices checked out.
1085 bool ConstantExpr::hasIndices() const {
1086 return getOpcode() == Instruction::ExtractValue ||
1087 getOpcode() == Instruction::InsertValue;
1090 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1091 if (const ExtractValueConstantExpr *EVCE =
1092 dyn_cast<ExtractValueConstantExpr>(this))
1093 return EVCE->Indices;
1095 return cast<InsertValueConstantExpr>(this)->Indices;
1098 unsigned ConstantExpr::getPredicate() const {
1099 assert(isCompare());
1100 return ((const CompareConstantExpr*)this)->predicate;
1103 /// getWithOperandReplaced - Return a constant expression identical to this
1104 /// one, but with the specified operand set to the specified value.
1106 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1107 assert(Op->getType() == getOperand(OpNo)->getType() &&
1108 "Replacing operand with value of different type!");
1109 if (getOperand(OpNo) == Op)
1110 return const_cast<ConstantExpr*>(this);
1112 SmallVector<Constant*, 8> NewOps;
1113 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1114 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1116 return getWithOperands(NewOps);
1119 /// getWithOperands - This returns the current constant expression with the
1120 /// operands replaced with the specified values. The specified array must
1121 /// have the same number of operands as our current one.
1122 Constant *ConstantExpr::
1123 getWithOperands(ArrayRef<Constant*> Ops, Type *Ty) const {
1124 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1125 bool AnyChange = Ty != getType();
1126 for (unsigned i = 0; i != Ops.size(); ++i)
1127 AnyChange |= Ops[i] != getOperand(i);
1129 if (!AnyChange) // No operands changed, return self.
1130 return const_cast<ConstantExpr*>(this);
1132 switch (getOpcode()) {
1133 case Instruction::Trunc:
1134 case Instruction::ZExt:
1135 case Instruction::SExt:
1136 case Instruction::FPTrunc:
1137 case Instruction::FPExt:
1138 case Instruction::UIToFP:
1139 case Instruction::SIToFP:
1140 case Instruction::FPToUI:
1141 case Instruction::FPToSI:
1142 case Instruction::PtrToInt:
1143 case Instruction::IntToPtr:
1144 case Instruction::BitCast:
1145 case Instruction::AddrSpaceCast:
1146 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty);
1147 case Instruction::Select:
1148 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1149 case Instruction::InsertElement:
1150 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1151 case Instruction::ExtractElement:
1152 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1153 case Instruction::InsertValue:
1154 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices());
1155 case Instruction::ExtractValue:
1156 return ConstantExpr::getExtractValue(Ops[0], getIndices());
1157 case Instruction::ShuffleVector:
1158 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
1159 case Instruction::GetElementPtr:
1160 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1),
1161 cast<GEPOperator>(this)->isInBounds());
1162 case Instruction::ICmp:
1163 case Instruction::FCmp:
1164 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1]);
1166 assert(getNumOperands() == 2 && "Must be binary operator?");
1167 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData);
1172 //===----------------------------------------------------------------------===//
1173 // isValueValidForType implementations
1175 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1176 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1177 if (Ty->isIntegerTy(1))
1178 return Val == 0 || Val == 1;
1180 return true; // always true, has to fit in largest type
1181 uint64_t Max = (1ll << NumBits) - 1;
1185 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1186 unsigned NumBits = Ty->getIntegerBitWidth();
1187 if (Ty->isIntegerTy(1))
1188 return Val == 0 || Val == 1 || Val == -1;
1190 return true; // always true, has to fit in largest type
1191 int64_t Min = -(1ll << (NumBits-1));
1192 int64_t Max = (1ll << (NumBits-1)) - 1;
1193 return (Val >= Min && Val <= Max);
1196 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1197 // convert modifies in place, so make a copy.
1198 APFloat Val2 = APFloat(Val);
1200 switch (Ty->getTypeID()) {
1202 return false; // These can't be represented as floating point!
1204 // FIXME rounding mode needs to be more flexible
1205 case Type::HalfTyID: {
1206 if (&Val2.getSemantics() == &APFloat::IEEEhalf)
1208 Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
1211 case Type::FloatTyID: {
1212 if (&Val2.getSemantics() == &APFloat::IEEEsingle)
1214 Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
1217 case Type::DoubleTyID: {
1218 if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
1219 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1220 &Val2.getSemantics() == &APFloat::IEEEdouble)
1222 Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
1225 case Type::X86_FP80TyID:
1226 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1227 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1228 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1229 &Val2.getSemantics() == &APFloat::x87DoubleExtended;
1230 case Type::FP128TyID:
1231 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1232 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1233 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1234 &Val2.getSemantics() == &APFloat::IEEEquad;
1235 case Type::PPC_FP128TyID:
1236 return &Val2.getSemantics() == &APFloat::IEEEhalf ||
1237 &Val2.getSemantics() == &APFloat::IEEEsingle ||
1238 &Val2.getSemantics() == &APFloat::IEEEdouble ||
1239 &Val2.getSemantics() == &APFloat::PPCDoubleDouble;
1244 //===----------------------------------------------------------------------===//
1245 // Factory Function Implementation
1247 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1248 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1249 "Cannot create an aggregate zero of non-aggregate type!");
1251 ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
1253 Entry = new ConstantAggregateZero(Ty);
1258 /// destroyConstant - Remove the constant from the constant table.
1260 void ConstantAggregateZero::destroyConstant() {
1261 getContext().pImpl->CAZConstants.erase(getType());
1262 destroyConstantImpl();
1265 /// destroyConstant - Remove the constant from the constant table...
1267 void ConstantArray::destroyConstant() {
1268 getType()->getContext().pImpl->ArrayConstants.remove(this);
1269 destroyConstantImpl();
1273 //---- ConstantStruct::get() implementation...
1276 // destroyConstant - Remove the constant from the constant table...
1278 void ConstantStruct::destroyConstant() {
1279 getType()->getContext().pImpl->StructConstants.remove(this);
1280 destroyConstantImpl();
1283 // destroyConstant - Remove the constant from the constant table...
1285 void ConstantVector::destroyConstant() {
1286 getType()->getContext().pImpl->VectorConstants.remove(this);
1287 destroyConstantImpl();
1290 /// getSplatValue - If this is a splat vector constant, meaning that all of
1291 /// the elements have the same value, return that value. Otherwise return 0.
1292 Constant *Constant::getSplatValue() const {
1293 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1294 if (isa<ConstantAggregateZero>(this))
1295 return getNullValue(this->getType()->getVectorElementType());
1296 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1297 return CV->getSplatValue();
1298 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1299 return CV->getSplatValue();
1303 /// getSplatValue - If this is a splat constant, where all of the
1304 /// elements have the same value, return that value. Otherwise return null.
1305 Constant *ConstantVector::getSplatValue() const {
1306 // Check out first element.
1307 Constant *Elt = getOperand(0);
1308 // Then make sure all remaining elements point to the same value.
1309 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1310 if (getOperand(I) != Elt)
1315 /// If C is a constant integer then return its value, otherwise C must be a
1316 /// vector of constant integers, all equal, and the common value is returned.
1317 const APInt &Constant::getUniqueInteger() const {
1318 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1319 return CI->getValue();
1320 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1321 const Constant *C = this->getAggregateElement(0U);
1322 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1323 return cast<ConstantInt>(C)->getValue();
1327 //---- ConstantPointerNull::get() implementation.
1330 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1331 ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
1333 Entry = new ConstantPointerNull(Ty);
1338 // destroyConstant - Remove the constant from the constant table...
1340 void ConstantPointerNull::destroyConstant() {
1341 getContext().pImpl->CPNConstants.erase(getType());
1342 // Free the constant and any dangling references to it.
1343 destroyConstantImpl();
1347 //---- UndefValue::get() implementation.
1350 UndefValue *UndefValue::get(Type *Ty) {
1351 UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
1353 Entry = new UndefValue(Ty);
1358 // destroyConstant - Remove the constant from the constant table.
1360 void UndefValue::destroyConstant() {
1361 // Free the constant and any dangling references to it.
1362 getContext().pImpl->UVConstants.erase(getType());
1363 destroyConstantImpl();
1366 //---- BlockAddress::get() implementation.
1369 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1370 assert(BB->getParent() && "Block must have a parent");
1371 return get(BB->getParent(), BB);
1374 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1376 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1378 BA = new BlockAddress(F, BB);
1380 assert(BA->getFunction() == F && "Basic block moved between functions");
1384 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1385 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1389 BB->AdjustBlockAddressRefCount(1);
1392 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1393 if (!BB->hasAddressTaken())
1396 const Function *F = BB->getParent();
1397 assert(F && "Block must have a parent");
1399 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1400 assert(BA && "Refcount and block address map disagree!");
1404 // destroyConstant - Remove the constant from the constant table.
1406 void BlockAddress::destroyConstant() {
1407 getFunction()->getType()->getContext().pImpl
1408 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1409 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1410 destroyConstantImpl();
1413 void BlockAddress::replaceUsesOfWithOnConstant(Value *From, Value *To, Use *U) {
1414 // This could be replacing either the Basic Block or the Function. In either
1415 // case, we have to remove the map entry.
1416 Function *NewF = getFunction();
1417 BasicBlock *NewBB = getBasicBlock();
1420 NewF = cast<Function>(To->stripPointerCasts());
1422 NewBB = cast<BasicBlock>(To);
1424 // See if the 'new' entry already exists, if not, just update this in place
1425 // and return early.
1426 BlockAddress *&NewBA =
1427 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1429 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1431 // Remove the old entry, this can't cause the map to rehash (just a
1432 // tombstone will get added).
1433 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1436 setOperand(0, NewF);
1437 setOperand(1, NewBB);
1438 getBasicBlock()->AdjustBlockAddressRefCount(1);
1442 // Otherwise, I do need to replace this with an existing value.
1443 assert(NewBA != this && "I didn't contain From!");
1445 // Everyone using this now uses the replacement.
1446 replaceAllUsesWith(NewBA);
1451 //---- ConstantExpr::get() implementations.
1454 /// This is a utility function to handle folding of casts and lookup of the
1455 /// cast in the ExprConstants map. It is used by the various get* methods below.
1456 static inline Constant *getFoldedCast(
1457 Instruction::CastOps opc, Constant *C, Type *Ty) {
1458 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1459 // Fold a few common cases
1460 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1463 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1465 // Look up the constant in the table first to ensure uniqueness.
1466 ExprMapKeyType Key(opc, C);
1468 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1471 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty) {
1472 Instruction::CastOps opc = Instruction::CastOps(oc);
1473 assert(Instruction::isCast(opc) && "opcode out of range");
1474 assert(C && Ty && "Null arguments to getCast");
1475 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1479 llvm_unreachable("Invalid cast opcode");
1480 case Instruction::Trunc: return getTrunc(C, Ty);
1481 case Instruction::ZExt: return getZExt(C, Ty);
1482 case Instruction::SExt: return getSExt(C, Ty);
1483 case Instruction::FPTrunc: return getFPTrunc(C, Ty);
1484 case Instruction::FPExt: return getFPExtend(C, Ty);
1485 case Instruction::UIToFP: return getUIToFP(C, Ty);
1486 case Instruction::SIToFP: return getSIToFP(C, Ty);
1487 case Instruction::FPToUI: return getFPToUI(C, Ty);
1488 case Instruction::FPToSI: return getFPToSI(C, Ty);
1489 case Instruction::PtrToInt: return getPtrToInt(C, Ty);
1490 case Instruction::IntToPtr: return getIntToPtr(C, Ty);
1491 case Instruction::BitCast: return getBitCast(C, Ty);
1492 case Instruction::AddrSpaceCast: return getAddrSpaceCast(C, Ty);
1496 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1497 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1498 return getBitCast(C, Ty);
1499 return getZExt(C, Ty);
1502 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1503 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1504 return getBitCast(C, Ty);
1505 return getSExt(C, Ty);
1508 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1509 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1510 return getBitCast(C, Ty);
1511 return getTrunc(C, Ty);
1514 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1515 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1516 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1519 if (Ty->isIntOrIntVectorTy())
1520 return getPtrToInt(S, Ty);
1522 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1523 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1524 return getAddrSpaceCast(S, Ty);
1526 return getBitCast(S, Ty);
1529 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1531 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1532 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1534 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1535 return getAddrSpaceCast(S, Ty);
1537 return getBitCast(S, Ty);
1540 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
1542 assert(C->getType()->isIntOrIntVectorTy() &&
1543 Ty->isIntOrIntVectorTy() && "Invalid cast");
1544 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1545 unsigned DstBits = Ty->getScalarSizeInBits();
1546 Instruction::CastOps opcode =
1547 (SrcBits == DstBits ? Instruction::BitCast :
1548 (SrcBits > DstBits ? Instruction::Trunc :
1549 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1550 return getCast(opcode, C, Ty);
1553 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1554 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1556 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1557 unsigned DstBits = Ty->getScalarSizeInBits();
1558 if (SrcBits == DstBits)
1559 return C; // Avoid a useless cast
1560 Instruction::CastOps opcode =
1561 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1562 return getCast(opcode, C, Ty);
1565 Constant *ConstantExpr::getTrunc(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() && "Trunc operand must be integer");
1572 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1573 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1574 "SrcTy must be larger than DestTy for Trunc!");
1576 return getFoldedCast(Instruction::Trunc, C, Ty);
1579 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty) {
1581 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1582 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1584 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1585 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1586 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1587 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1588 "SrcTy must be smaller than DestTy for SExt!");
1590 return getFoldedCast(Instruction::SExt, C, Ty);
1593 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty) {
1595 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1596 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1598 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1599 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1600 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1601 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1602 "SrcTy must be smaller than DestTy for ZExt!");
1604 return getFoldedCast(Instruction::ZExt, C, Ty);
1607 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty) {
1609 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1610 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1612 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1613 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1614 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1615 "This is an illegal floating point truncation!");
1616 return getFoldedCast(Instruction::FPTrunc, C, Ty);
1619 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty) {
1621 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1622 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1624 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1625 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1626 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1627 "This is an illegal floating point extension!");
1628 return getFoldedCast(Instruction::FPExt, C, Ty);
1631 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty) {
1633 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1634 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1636 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1637 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1638 "This is an illegal uint to floating point cast!");
1639 return getFoldedCast(Instruction::UIToFP, C, Ty);
1642 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty) {
1644 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1645 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1647 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1648 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1649 "This is an illegal sint to floating point cast!");
1650 return getFoldedCast(Instruction::SIToFP, C, Ty);
1653 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty) {
1655 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1656 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1658 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1659 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1660 "This is an illegal floating point to uint cast!");
1661 return getFoldedCast(Instruction::FPToUI, C, Ty);
1664 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty) {
1666 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1667 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1669 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1670 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1671 "This is an illegal floating point to sint cast!");
1672 return getFoldedCast(Instruction::FPToSI, C, Ty);
1675 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy) {
1676 assert(C->getType()->getScalarType()->isPointerTy() &&
1677 "PtrToInt source must be pointer or pointer vector");
1678 assert(DstTy->getScalarType()->isIntegerTy() &&
1679 "PtrToInt destination must be integer or integer vector");
1680 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1681 if (isa<VectorType>(C->getType()))
1682 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1683 "Invalid cast between a different number of vector elements");
1684 return getFoldedCast(Instruction::PtrToInt, C, DstTy);
1687 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy) {
1688 assert(C->getType()->getScalarType()->isIntegerTy() &&
1689 "IntToPtr source must be integer or integer vector");
1690 assert(DstTy->getScalarType()->isPointerTy() &&
1691 "IntToPtr destination must be a pointer or pointer vector");
1692 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1693 if (isa<VectorType>(C->getType()))
1694 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1695 "Invalid cast between a different number of vector elements");
1696 return getFoldedCast(Instruction::IntToPtr, C, DstTy);
1699 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy) {
1700 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1701 "Invalid constantexpr bitcast!");
1703 // It is common to ask for a bitcast of a value to its own type, handle this
1705 if (C->getType() == DstTy) return C;
1707 return getFoldedCast(Instruction::BitCast, C, DstTy);
1710 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy) {
1711 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1712 "Invalid constantexpr addrspacecast!");
1714 // Canonicalize addrspacecasts between different pointer types by first
1715 // bitcasting the pointer type and then converting the address space.
1716 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1717 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1718 Type *DstElemTy = DstScalarTy->getElementType();
1719 if (SrcScalarTy->getElementType() != DstElemTy) {
1720 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1721 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1722 // Handle vectors of pointers.
1723 MidTy = VectorType::get(MidTy, VT->getNumElements());
1725 C = getBitCast(C, MidTy);
1727 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy);
1730 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1732 // Check the operands for consistency first.
1733 assert(Opcode >= Instruction::BinaryOpsBegin &&
1734 Opcode < Instruction::BinaryOpsEnd &&
1735 "Invalid opcode in binary constant expression");
1736 assert(C1->getType() == C2->getType() &&
1737 "Operand types in binary constant expression should match");
1741 case Instruction::Add:
1742 case Instruction::Sub:
1743 case Instruction::Mul:
1744 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1745 assert(C1->getType()->isIntOrIntVectorTy() &&
1746 "Tried to create an integer operation on a non-integer type!");
1748 case Instruction::FAdd:
1749 case Instruction::FSub:
1750 case Instruction::FMul:
1751 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1752 assert(C1->getType()->isFPOrFPVectorTy() &&
1753 "Tried to create a floating-point operation on a "
1754 "non-floating-point type!");
1756 case Instruction::UDiv:
1757 case Instruction::SDiv:
1758 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1759 assert(C1->getType()->isIntOrIntVectorTy() &&
1760 "Tried to create an arithmetic operation on a non-arithmetic type!");
1762 case Instruction::FDiv:
1763 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1764 assert(C1->getType()->isFPOrFPVectorTy() &&
1765 "Tried to create an arithmetic operation on a non-arithmetic type!");
1767 case Instruction::URem:
1768 case Instruction::SRem:
1769 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1770 assert(C1->getType()->isIntOrIntVectorTy() &&
1771 "Tried to create an arithmetic operation on a non-arithmetic type!");
1773 case Instruction::FRem:
1774 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1775 assert(C1->getType()->isFPOrFPVectorTy() &&
1776 "Tried to create an arithmetic operation on a non-arithmetic type!");
1778 case Instruction::And:
1779 case Instruction::Or:
1780 case Instruction::Xor:
1781 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1782 assert(C1->getType()->isIntOrIntVectorTy() &&
1783 "Tried to create a logical operation on a non-integral type!");
1785 case Instruction::Shl:
1786 case Instruction::LShr:
1787 case Instruction::AShr:
1788 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1789 assert(C1->getType()->isIntOrIntVectorTy() &&
1790 "Tried to create a shift operation on a non-integer type!");
1797 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1798 return FC; // Fold a few common cases.
1800 Constant *ArgVec[] = { C1, C2 };
1801 ExprMapKeyType Key(Opcode, ArgVec, 0, Flags);
1803 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1804 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1807 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1808 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1809 // Note that a non-inbounds gep is used, as null isn't within any object.
1810 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1811 Constant *GEP = getGetElementPtr(
1812 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1813 return getPtrToInt(GEP,
1814 Type::getInt64Ty(Ty->getContext()));
1817 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1818 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1819 // Note that a non-inbounds gep is used, as null isn't within any object.
1821 StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, NULL);
1822 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1823 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1824 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1825 Constant *Indices[2] = { Zero, One };
1826 Constant *GEP = getGetElementPtr(NullPtr, Indices);
1827 return getPtrToInt(GEP,
1828 Type::getInt64Ty(Ty->getContext()));
1831 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1832 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1836 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1837 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1838 // Note that a non-inbounds gep is used, as null isn't within any object.
1839 Constant *GEPIdx[] = {
1840 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1843 Constant *GEP = getGetElementPtr(
1844 Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1845 return getPtrToInt(GEP,
1846 Type::getInt64Ty(Ty->getContext()));
1849 Constant *ConstantExpr::getCompare(unsigned short Predicate,
1850 Constant *C1, Constant *C2) {
1851 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1853 switch (Predicate) {
1854 default: llvm_unreachable("Invalid CmpInst predicate");
1855 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1856 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1857 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1858 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1859 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1860 case CmpInst::FCMP_TRUE:
1861 return getFCmp(Predicate, C1, C2);
1863 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1864 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1865 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1866 case CmpInst::ICMP_SLE:
1867 return getICmp(Predicate, C1, C2);
1871 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2) {
1872 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1874 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1875 return SC; // Fold common cases
1877 Constant *ArgVec[] = { C, V1, V2 };
1878 ExprMapKeyType Key(Instruction::Select, ArgVec);
1880 LLVMContextImpl *pImpl = C->getContext().pImpl;
1881 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1884 Constant *ConstantExpr::getGetElementPtr(Constant *C, ArrayRef<Value *> Idxs,
1886 assert(C->getType()->isPtrOrPtrVectorTy() &&
1887 "Non-pointer type for constant GetElementPtr expression");
1889 if (Constant *FC = ConstantFoldGetElementPtr(C, InBounds, Idxs))
1890 return FC; // Fold a few common cases.
1892 // Get the result type of the getelementptr!
1893 Type *Ty = GetElementPtrInst::getIndexedType(C->getType(), Idxs);
1894 assert(Ty && "GEP indices invalid!");
1895 unsigned AS = C->getType()->getPointerAddressSpace();
1896 Type *ReqTy = Ty->getPointerTo(AS);
1897 if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
1898 ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
1900 // Look up the constant in the table first to ensure uniqueness
1901 std::vector<Constant*> ArgVec;
1902 ArgVec.reserve(1 + Idxs.size());
1903 ArgVec.push_back(C);
1904 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1905 assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
1906 "getelementptr index type missmatch");
1907 assert((!Idxs[i]->getType()->isVectorTy() ||
1908 ReqTy->getVectorNumElements() ==
1909 Idxs[i]->getType()->getVectorNumElements()) &&
1910 "getelementptr index type missmatch");
1911 ArgVec.push_back(cast<Constant>(Idxs[i]));
1913 const ExprMapKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1914 InBounds ? GEPOperator::IsInBounds : 0);
1916 LLVMContextImpl *pImpl = C->getContext().pImpl;
1917 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1921 ConstantExpr::getICmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1922 assert(LHS->getType() == RHS->getType());
1923 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1924 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1926 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1927 return FC; // Fold a few common cases...
1929 // Look up the constant in the table first to ensure uniqueness
1930 Constant *ArgVec[] = { LHS, RHS };
1931 // Get the key type with both the opcode and predicate
1932 const ExprMapKeyType Key(Instruction::ICmp, ArgVec, pred);
1934 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1935 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1936 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1938 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1939 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1943 ConstantExpr::getFCmp(unsigned short pred, Constant *LHS, Constant *RHS) {
1944 assert(LHS->getType() == RHS->getType());
1945 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1947 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1948 return FC; // Fold a few common cases...
1950 // Look up the constant in the table first to ensure uniqueness
1951 Constant *ArgVec[] = { LHS, RHS };
1952 // Get the key type with both the opcode and predicate
1953 const ExprMapKeyType Key(Instruction::FCmp, ArgVec, pred);
1955 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1956 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1957 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1959 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1960 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1963 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx) {
1964 assert(Val->getType()->isVectorTy() &&
1965 "Tried to create extractelement operation on non-vector type!");
1966 assert(Idx->getType()->isIntegerTy() &&
1967 "Extractelement index must be an integer type!");
1969 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1970 return FC; // Fold a few common cases.
1972 // Look up the constant in the table first to ensure uniqueness
1973 Constant *ArgVec[] = { Val, Idx };
1974 const ExprMapKeyType Key(Instruction::ExtractElement, ArgVec);
1976 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1977 Type *ReqTy = Val->getType()->getVectorElementType();
1978 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1981 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1983 assert(Val->getType()->isVectorTy() &&
1984 "Tried to create insertelement operation on non-vector type!");
1985 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1986 "Insertelement types must match!");
1987 assert(Idx->getType()->isIntegerTy() &&
1988 "Insertelement index must be i32 type!");
1990 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
1991 return FC; // Fold a few common cases.
1992 // Look up the constant in the table first to ensure uniqueness
1993 Constant *ArgVec[] = { Val, Elt, Idx };
1994 const ExprMapKeyType Key(Instruction::InsertElement, ArgVec);
1996 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1997 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2000 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2002 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2003 "Invalid shuffle vector constant expr operands!");
2005 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2006 return FC; // Fold a few common cases.
2008 unsigned NElts = Mask->getType()->getVectorNumElements();
2009 Type *EltTy = V1->getType()->getVectorElementType();
2010 Type *ShufTy = VectorType::get(EltTy, NElts);
2012 // Look up the constant in the table first to ensure uniqueness
2013 Constant *ArgVec[] = { V1, V2, Mask };
2014 const ExprMapKeyType Key(Instruction::ShuffleVector, ArgVec);
2016 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2017 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2020 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2021 ArrayRef<unsigned> Idxs) {
2022 assert(Agg->getType()->isFirstClassType() &&
2023 "Non-first-class type for constant insertvalue expression");
2025 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2026 Idxs) == Val->getType() &&
2027 "insertvalue indices invalid!");
2028 Type *ReqTy = Val->getType();
2030 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2033 Constant *ArgVec[] = { Agg, Val };
2034 const ExprMapKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2036 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2037 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2040 Constant *ConstantExpr::getExtractValue(Constant *Agg,
2041 ArrayRef<unsigned> Idxs) {
2042 assert(Agg->getType()->isFirstClassType() &&
2043 "Tried to create extractelement operation on non-first-class type!");
2045 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2047 assert(ReqTy && "extractvalue indices invalid!");
2049 assert(Agg->getType()->isFirstClassType() &&
2050 "Non-first-class type for constant extractvalue expression");
2051 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2054 Constant *ArgVec[] = { Agg };
2055 const ExprMapKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2057 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2058 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2061 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2062 assert(C->getType()->isIntOrIntVectorTy() &&
2063 "Cannot NEG a nonintegral value!");
2064 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2068 Constant *ConstantExpr::getFNeg(Constant *C) {
2069 assert(C->getType()->isFPOrFPVectorTy() &&
2070 "Cannot FNEG a non-floating-point value!");
2071 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2074 Constant *ConstantExpr::getNot(Constant *C) {
2075 assert(C->getType()->isIntOrIntVectorTy() &&
2076 "Cannot NOT a nonintegral value!");
2077 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2080 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2081 bool HasNUW, bool HasNSW) {
2082 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2083 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2084 return get(Instruction::Add, C1, C2, Flags);
2087 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2088 return get(Instruction::FAdd, C1, C2);
2091 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2092 bool HasNUW, bool HasNSW) {
2093 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2094 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2095 return get(Instruction::Sub, C1, C2, Flags);
2098 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2099 return get(Instruction::FSub, C1, C2);
2102 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2103 bool HasNUW, bool HasNSW) {
2104 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2105 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2106 return get(Instruction::Mul, C1, C2, Flags);
2109 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2110 return get(Instruction::FMul, C1, C2);
2113 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2114 return get(Instruction::UDiv, C1, C2,
2115 isExact ? PossiblyExactOperator::IsExact : 0);
2118 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2119 return get(Instruction::SDiv, C1, C2,
2120 isExact ? PossiblyExactOperator::IsExact : 0);
2123 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2124 return get(Instruction::FDiv, C1, C2);
2127 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2128 return get(Instruction::URem, C1, C2);
2131 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2132 return get(Instruction::SRem, C1, C2);
2135 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2136 return get(Instruction::FRem, C1, C2);
2139 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2140 return get(Instruction::And, C1, C2);
2143 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2144 return get(Instruction::Or, C1, C2);
2147 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2148 return get(Instruction::Xor, C1, C2);
2151 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2152 bool HasNUW, bool HasNSW) {
2153 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2154 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2155 return get(Instruction::Shl, C1, C2, Flags);
2158 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2159 return get(Instruction::LShr, C1, C2,
2160 isExact ? PossiblyExactOperator::IsExact : 0);
2163 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2164 return get(Instruction::AShr, C1, C2,
2165 isExact ? PossiblyExactOperator::IsExact : 0);
2168 /// getBinOpIdentity - Return the identity for the given binary operation,
2169 /// i.e. a constant C such that X op C = X and C op X = X for every X. It
2170 /// returns null if the operator doesn't have an identity.
2171 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2174 // Doesn't have an identity.
2177 case Instruction::Add:
2178 case Instruction::Or:
2179 case Instruction::Xor:
2180 return Constant::getNullValue(Ty);
2182 case Instruction::Mul:
2183 return ConstantInt::get(Ty, 1);
2185 case Instruction::And:
2186 return Constant::getAllOnesValue(Ty);
2190 /// getBinOpAbsorber - Return the absorbing element for the given binary
2191 /// operation, i.e. a constant C such that X op C = C and C op X = C for
2192 /// every X. For example, this returns zero for integer multiplication.
2193 /// It returns null if the operator doesn't have an absorbing element.
2194 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2197 // Doesn't have an absorber.
2200 case Instruction::Or:
2201 return Constant::getAllOnesValue(Ty);
2203 case Instruction::And:
2204 case Instruction::Mul:
2205 return Constant::getNullValue(Ty);
2209 // destroyConstant - Remove the constant from the constant table...
2211 void ConstantExpr::destroyConstant() {
2212 getType()->getContext().pImpl->ExprConstants.remove(this);
2213 destroyConstantImpl();
2216 const char *ConstantExpr::getOpcodeName() const {
2217 return Instruction::getOpcodeName(getOpcode());
2222 GetElementPtrConstantExpr::
2223 GetElementPtrConstantExpr(Constant *C, ArrayRef<Constant*> IdxList,
2225 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2226 OperandTraits<GetElementPtrConstantExpr>::op_end(this)
2227 - (IdxList.size()+1), IdxList.size()+1) {
2229 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2230 OperandList[i+1] = IdxList[i];
2233 //===----------------------------------------------------------------------===//
2234 // ConstantData* implementations
2236 void ConstantDataArray::anchor() {}
2237 void ConstantDataVector::anchor() {}
2239 /// getElementType - Return the element type of the array/vector.
2240 Type *ConstantDataSequential::getElementType() const {
2241 return getType()->getElementType();
2244 StringRef ConstantDataSequential::getRawDataValues() const {
2245 return StringRef(DataElements, getNumElements()*getElementByteSize());
2248 /// isElementTypeCompatible - Return true if a ConstantDataSequential can be
2249 /// formed with a vector or array of the specified element type.
2250 /// ConstantDataArray only works with normal float and int types that are
2251 /// stored densely in memory, not with things like i42 or x86_f80.
2252 bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
2253 if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2254 if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
2255 switch (IT->getBitWidth()) {
2267 /// getNumElements - Return the number of elements in the array or vector.
2268 unsigned ConstantDataSequential::getNumElements() const {
2269 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2270 return AT->getNumElements();
2271 return getType()->getVectorNumElements();
2275 /// getElementByteSize - Return the size in bytes of the elements in the data.
2276 uint64_t ConstantDataSequential::getElementByteSize() const {
2277 return getElementType()->getPrimitiveSizeInBits()/8;
2280 /// getElementPointer - Return the start of the specified element.
2281 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2282 assert(Elt < getNumElements() && "Invalid Elt");
2283 return DataElements+Elt*getElementByteSize();
2287 /// isAllZeros - return true if the array is empty or all zeros.
2288 static bool isAllZeros(StringRef Arr) {
2289 for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
2295 /// getImpl - This is the underlying implementation of all of the
2296 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2297 /// the correct element type. We take the bytes in as a StringRef because
2298 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2299 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2300 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2301 // If the elements are all zero or there are no elements, return a CAZ, which
2302 // is more dense and canonical.
2303 if (isAllZeros(Elements))
2304 return ConstantAggregateZero::get(Ty);
2306 // Do a lookup to see if we have already formed one of these.
2307 StringMap<ConstantDataSequential*>::MapEntryTy &Slot =
2308 Ty->getContext().pImpl->CDSConstants.GetOrCreateValue(Elements);
2310 // The bucket can point to a linked list of different CDS's that have the same
2311 // body but different types. For example, 0,0,0,1 could be a 4 element array
2312 // of i8, or a 1-element array of i32. They'll both end up in the same
2313 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2314 ConstantDataSequential **Entry = &Slot.getValue();
2315 for (ConstantDataSequential *Node = *Entry; Node;
2316 Entry = &Node->Next, Node = *Entry)
2317 if (Node->getType() == Ty)
2320 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2322 if (isa<ArrayType>(Ty))
2323 return *Entry = new ConstantDataArray(Ty, Slot.getKeyData());
2325 assert(isa<VectorType>(Ty));
2326 return *Entry = new ConstantDataVector(Ty, Slot.getKeyData());
2329 void ConstantDataSequential::destroyConstant() {
2330 // Remove the constant from the StringMap.
2331 StringMap<ConstantDataSequential*> &CDSConstants =
2332 getType()->getContext().pImpl->CDSConstants;
2334 StringMap<ConstantDataSequential*>::iterator Slot =
2335 CDSConstants.find(getRawDataValues());
2337 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2339 ConstantDataSequential **Entry = &Slot->getValue();
2341 // Remove the entry from the hash table.
2342 if (!(*Entry)->Next) {
2343 // If there is only one value in the bucket (common case) it must be this
2344 // entry, and removing the entry should remove the bucket completely.
2345 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2346 getContext().pImpl->CDSConstants.erase(Slot);
2348 // Otherwise, there are multiple entries linked off the bucket, unlink the
2349 // node we care about but keep the bucket around.
2350 for (ConstantDataSequential *Node = *Entry; ;
2351 Entry = &Node->Next, Node = *Entry) {
2352 assert(Node && "Didn't find entry in its uniquing hash table!");
2353 // If we found our entry, unlink it from the list and we're done.
2355 *Entry = Node->Next;
2361 // If we were part of a list, make sure that we don't delete the list that is
2362 // still owned by the uniquing map.
2365 // Finally, actually delete it.
2366 destroyConstantImpl();
2369 /// get() constructors - Return a constant with array type with an element
2370 /// count and element type matching the ArrayRef passed in. Note that this
2371 /// can return a ConstantAggregateZero object.
2372 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2373 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2374 const char *Data = reinterpret_cast<const char *>(Elts.data());
2375 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2377 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2378 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2379 const char *Data = reinterpret_cast<const char *>(Elts.data());
2380 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2382 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2383 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2384 const char *Data = reinterpret_cast<const char *>(Elts.data());
2385 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2387 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2388 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2389 const char *Data = reinterpret_cast<const char *>(Elts.data());
2390 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2392 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2393 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2394 const char *Data = reinterpret_cast<const char *>(Elts.data());
2395 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2397 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2398 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2399 const char *Data = reinterpret_cast<const char *>(Elts.data());
2400 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2403 /// getString - This method constructs a CDS and initializes it with a text
2404 /// string. The default behavior (AddNull==true) causes a null terminator to
2405 /// be placed at the end of the array (increasing the length of the string by
2406 /// one more than the StringRef would normally indicate. Pass AddNull=false
2407 /// to disable this behavior.
2408 Constant *ConstantDataArray::getString(LLVMContext &Context,
2409 StringRef Str, bool AddNull) {
2411 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2412 return get(Context, ArrayRef<uint8_t>(const_cast<uint8_t *>(Data),
2416 SmallVector<uint8_t, 64> ElementVals;
2417 ElementVals.append(Str.begin(), Str.end());
2418 ElementVals.push_back(0);
2419 return get(Context, ElementVals);
2422 /// get() constructors - Return a constant with vector type with an element
2423 /// count and element type matching the ArrayRef passed in. Note that this
2424 /// can return a ConstantAggregateZero object.
2425 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2426 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2427 const char *Data = reinterpret_cast<const char *>(Elts.data());
2428 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2430 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2431 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2432 const char *Data = reinterpret_cast<const char *>(Elts.data());
2433 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2435 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2436 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2437 const char *Data = reinterpret_cast<const char *>(Elts.data());
2438 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2440 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2441 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2442 const char *Data = reinterpret_cast<const char *>(Elts.data());
2443 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2445 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2446 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2447 const char *Data = reinterpret_cast<const char *>(Elts.data());
2448 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2450 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2451 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2452 const char *Data = reinterpret_cast<const char *>(Elts.data());
2453 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2456 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2457 assert(isElementTypeCompatible(V->getType()) &&
2458 "Element type not compatible with ConstantData");
2459 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2460 if (CI->getType()->isIntegerTy(8)) {
2461 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2462 return get(V->getContext(), Elts);
2464 if (CI->getType()->isIntegerTy(16)) {
2465 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2466 return get(V->getContext(), Elts);
2468 if (CI->getType()->isIntegerTy(32)) {
2469 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2470 return get(V->getContext(), Elts);
2472 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2473 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2474 return get(V->getContext(), Elts);
2477 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2478 if (CFP->getType()->isFloatTy()) {
2479 SmallVector<float, 16> Elts(NumElts, CFP->getValueAPF().convertToFloat());
2480 return get(V->getContext(), Elts);
2482 if (CFP->getType()->isDoubleTy()) {
2483 SmallVector<double, 16> Elts(NumElts,
2484 CFP->getValueAPF().convertToDouble());
2485 return get(V->getContext(), Elts);
2488 return ConstantVector::getSplat(NumElts, V);
2492 /// getElementAsInteger - If this is a sequential container of integers (of
2493 /// any size), return the specified element in the low bits of a uint64_t.
2494 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2495 assert(isa<IntegerType>(getElementType()) &&
2496 "Accessor can only be used when element is an integer");
2497 const char *EltPtr = getElementPointer(Elt);
2499 // The data is stored in host byte order, make sure to cast back to the right
2500 // type to load with the right endianness.
2501 switch (getElementType()->getIntegerBitWidth()) {
2502 default: llvm_unreachable("Invalid bitwidth for CDS");
2504 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2506 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2508 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2510 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2514 /// getElementAsAPFloat - If this is a sequential container of floating point
2515 /// type, return the specified element as an APFloat.
2516 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2517 const char *EltPtr = getElementPointer(Elt);
2519 switch (getElementType()->getTypeID()) {
2521 llvm_unreachable("Accessor can only be used when element is float/double!");
2522 case Type::FloatTyID: {
2523 const float *FloatPrt = reinterpret_cast<const float *>(EltPtr);
2524 return APFloat(*const_cast<float *>(FloatPrt));
2526 case Type::DoubleTyID: {
2527 const double *DoublePtr = reinterpret_cast<const double *>(EltPtr);
2528 return APFloat(*const_cast<double *>(DoublePtr));
2533 /// getElementAsFloat - If this is an sequential container of floats, return
2534 /// the specified element as a float.
2535 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2536 assert(getElementType()->isFloatTy() &&
2537 "Accessor can only be used when element is a 'float'");
2538 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2539 return *const_cast<float *>(EltPtr);
2542 /// getElementAsDouble - If this is an sequential container of doubles, return
2543 /// the specified element as a float.
2544 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2545 assert(getElementType()->isDoubleTy() &&
2546 "Accessor can only be used when element is a 'float'");
2547 const double *EltPtr =
2548 reinterpret_cast<const double *>(getElementPointer(Elt));
2549 return *const_cast<double *>(EltPtr);
2552 /// getElementAsConstant - Return a Constant for a specified index's element.
2553 /// Note that this has to compute a new constant to return, so it isn't as
2554 /// efficient as getElementAsInteger/Float/Double.
2555 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2556 if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
2557 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2559 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2562 /// isString - This method returns true if this is an array of i8.
2563 bool ConstantDataSequential::isString() const {
2564 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
2567 /// isCString - This method returns true if the array "isString", ends with a
2568 /// nul byte, and does not contains any other nul bytes.
2569 bool ConstantDataSequential::isCString() const {
2573 StringRef Str = getAsString();
2575 // The last value must be nul.
2576 if (Str.back() != 0) return false;
2578 // Other elements must be non-nul.
2579 return Str.drop_back().find(0) == StringRef::npos;
2582 /// getSplatValue - If this is a splat constant, meaning that all of the
2583 /// elements have the same value, return that value. Otherwise return NULL.
2584 Constant *ConstantDataVector::getSplatValue() const {
2585 const char *Base = getRawDataValues().data();
2587 // Compare elements 1+ to the 0'th element.
2588 unsigned EltSize = getElementByteSize();
2589 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2590 if (memcmp(Base, Base+i*EltSize, EltSize))
2593 // If they're all the same, return the 0th one as a representative.
2594 return getElementAsConstant(0);
2597 //===----------------------------------------------------------------------===//
2598 // replaceUsesOfWithOnConstant implementations
2600 /// replaceUsesOfWithOnConstant - Update this constant array to change uses of
2601 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2604 /// Note that we intentionally replace all uses of From with To here. Consider
2605 /// a large array that uses 'From' 1000 times. By handling this case all here,
2606 /// ConstantArray::replaceUsesOfWithOnConstant is only invoked once, and that
2607 /// single invocation handles all 1000 uses. Handling them one at a time would
2608 /// work, but would be really slow because it would have to unique each updated
2611 void ConstantArray::replaceUsesOfWithOnConstant(Value *From, Value *To,
2613 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2614 Constant *ToC = cast<Constant>(To);
2616 LLVMContextImpl *pImpl = getType()->getContext().pImpl;
2618 SmallVector<Constant*, 8> Values;
2619 LLVMContextImpl::ArrayConstantsTy::LookupKey Lookup;
2620 Lookup.first = cast<ArrayType>(getType());
2621 Values.reserve(getNumOperands()); // Build replacement array.
2623 // Fill values with the modified operands of the constant array. Also,
2624 // compute whether this turns into an all-zeros array.
2625 unsigned NumUpdated = 0;
2627 // Keep track of whether all the values in the array are "ToC".
2628 bool AllSame = true;
2629 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2630 Constant *Val = cast<Constant>(O->get());
2635 Values.push_back(Val);
2636 AllSame &= Val == ToC;
2639 Constant *Replacement = nullptr;
2640 if (AllSame && ToC->isNullValue()) {
2641 Replacement = ConstantAggregateZero::get(getType());
2642 } else if (AllSame && isa<UndefValue>(ToC)) {
2643 Replacement = UndefValue::get(getType());
2645 // Check to see if we have this array type already.
2646 Lookup.second = makeArrayRef(Values);
2647 LLVMContextImpl::ArrayConstantsTy::MapTy::iterator I =
2648 pImpl->ArrayConstants.find(Lookup);
2650 if (I != pImpl->ArrayConstants.map_end()) {
2651 Replacement = I->first;
2653 // Okay, the new shape doesn't exist in the system yet. Instead of
2654 // creating a new constant array, inserting it, replaceallusesof'ing the
2655 // old with the new, then deleting the old... just update the current one
2657 pImpl->ArrayConstants.remove(this);
2659 // Update to the new value. Optimize for the case when we have a single
2660 // operand that we're changing, but handle bulk updates efficiently.
2661 if (NumUpdated == 1) {
2662 unsigned OperandToUpdate = U - OperandList;
2663 assert(getOperand(OperandToUpdate) == From &&
2664 "ReplaceAllUsesWith broken!");
2665 setOperand(OperandToUpdate, ToC);
2667 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2668 if (getOperand(i) == From)
2671 pImpl->ArrayConstants.insert(this);
2676 // Otherwise, I do need to replace this with an existing value.
2677 assert(Replacement != this && "I didn't contain From!");
2679 // Everyone using this now uses the replacement.
2680 replaceAllUsesWith(Replacement);
2682 // Delete the old constant!
2686 void ConstantStruct::replaceUsesOfWithOnConstant(Value *From, Value *To,
2688 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2689 Constant *ToC = cast<Constant>(To);
2691 unsigned OperandToUpdate = U-OperandList;
2692 assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
2694 SmallVector<Constant*, 8> Values;
2695 LLVMContextImpl::StructConstantsTy::LookupKey Lookup;
2696 Lookup.first = cast<StructType>(getType());
2697 Values.reserve(getNumOperands()); // Build replacement struct.
2699 // Fill values with the modified operands of the constant struct. Also,
2700 // compute whether this turns into an all-zeros struct.
2701 bool isAllZeros = false;
2702 bool isAllUndef = false;
2703 if (ToC->isNullValue()) {
2705 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2706 Constant *Val = cast<Constant>(O->get());
2707 Values.push_back(Val);
2708 if (isAllZeros) isAllZeros = Val->isNullValue();
2710 } else if (isa<UndefValue>(ToC)) {
2712 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2713 Constant *Val = cast<Constant>(O->get());
2714 Values.push_back(Val);
2715 if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
2718 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
2719 Values.push_back(cast<Constant>(O->get()));
2721 Values[OperandToUpdate] = ToC;
2723 LLVMContextImpl *pImpl = getContext().pImpl;
2725 Constant *Replacement = nullptr;
2727 Replacement = ConstantAggregateZero::get(getType());
2728 } else if (isAllUndef) {
2729 Replacement = UndefValue::get(getType());
2731 // Check to see if we have this struct type already.
2732 Lookup.second = makeArrayRef(Values);
2733 LLVMContextImpl::StructConstantsTy::MapTy::iterator I =
2734 pImpl->StructConstants.find(Lookup);
2736 if (I != pImpl->StructConstants.map_end()) {
2737 Replacement = I->first;
2739 // Okay, the new shape doesn't exist in the system yet. Instead of
2740 // creating a new constant struct, inserting it, replaceallusesof'ing the
2741 // old with the new, then deleting the old... just update the current one
2743 pImpl->StructConstants.remove(this);
2745 // Update to the new value.
2746 setOperand(OperandToUpdate, ToC);
2747 pImpl->StructConstants.insert(this);
2752 assert(Replacement != this && "I didn't contain From!");
2754 // Everyone using this now uses the replacement.
2755 replaceAllUsesWith(Replacement);
2757 // Delete the old constant!
2761 void ConstantVector::replaceUsesOfWithOnConstant(Value *From, Value *To,
2763 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2765 SmallVector<Constant*, 8> Values;
2766 Values.reserve(getNumOperands()); // Build replacement array...
2767 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2768 Constant *Val = getOperand(i);
2769 if (Val == From) Val = cast<Constant>(To);
2770 Values.push_back(Val);
2773 Constant *Replacement = get(Values);
2774 assert(Replacement != this && "I didn't contain From!");
2776 // Everyone using this now uses the replacement.
2777 replaceAllUsesWith(Replacement);
2779 // Delete the old constant!
2783 void ConstantExpr::replaceUsesOfWithOnConstant(Value *From, Value *ToV,
2785 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2786 Constant *To = cast<Constant>(ToV);
2788 SmallVector<Constant*, 8> NewOps;
2789 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2790 Constant *Op = getOperand(i);
2791 NewOps.push_back(Op == From ? To : Op);
2794 Constant *Replacement = getWithOperands(NewOps);
2795 assert(Replacement != this && "I didn't contain From!");
2797 // Everyone using this now uses the replacement.
2798 replaceAllUsesWith(Replacement);
2800 // Delete the old constant!
2804 Instruction *ConstantExpr::getAsInstruction() {
2805 SmallVector<Value*,4> ValueOperands;
2806 for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2807 ValueOperands.push_back(cast<Value>(I));
2809 ArrayRef<Value*> Ops(ValueOperands);
2811 switch (getOpcode()) {
2812 case Instruction::Trunc:
2813 case Instruction::ZExt:
2814 case Instruction::SExt:
2815 case Instruction::FPTrunc:
2816 case Instruction::FPExt:
2817 case Instruction::UIToFP:
2818 case Instruction::SIToFP:
2819 case Instruction::FPToUI:
2820 case Instruction::FPToSI:
2821 case Instruction::PtrToInt:
2822 case Instruction::IntToPtr:
2823 case Instruction::BitCast:
2824 case Instruction::AddrSpaceCast:
2825 return CastInst::Create((Instruction::CastOps)getOpcode(),
2827 case Instruction::Select:
2828 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2829 case Instruction::InsertElement:
2830 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2831 case Instruction::ExtractElement:
2832 return ExtractElementInst::Create(Ops[0], Ops[1]);
2833 case Instruction::InsertValue:
2834 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2835 case Instruction::ExtractValue:
2836 return ExtractValueInst::Create(Ops[0], getIndices());
2837 case Instruction::ShuffleVector:
2838 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2840 case Instruction::GetElementPtr:
2841 if (cast<GEPOperator>(this)->isInBounds())
2842 return GetElementPtrInst::CreateInBounds(Ops[0], Ops.slice(1));
2844 return GetElementPtrInst::Create(Ops[0], Ops.slice(1));
2846 case Instruction::ICmp:
2847 case Instruction::FCmp:
2848 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2849 getPredicate(), Ops[0], Ops[1]);
2852 assert(getNumOperands() == 2 && "Must be binary operator?");
2853 BinaryOperator *BO =
2854 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2856 if (isa<OverflowingBinaryOperator>(BO)) {
2857 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2858 OverflowingBinaryOperator::NoUnsignedWrap);
2859 BO->setHasNoSignedWrap(SubclassOptionalData &
2860 OverflowingBinaryOperator::NoSignedWrap);
2862 if (isa<PossiblyExactOperator>(BO))
2863 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);