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/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/GetElementPtrTypeIterator.h"
22 #include "llvm/IR/GlobalValue.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Operator.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 bool Constant::isNegativeZeroValue() const {
40 // Floating point values have an explicit -0.0 value.
41 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
42 return CFP->isZero() && CFP->isNegative();
44 // Equivalent for a vector of -0.0's.
45 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
46 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
47 if (CV->getElementAsAPFloat(0).isNegZero())
50 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
51 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
52 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
55 // We've already handled true FP case; any other FP vectors can't represent -0.0.
56 if (getType()->isFPOrFPVectorTy())
59 // Otherwise, just use +0.0.
63 // Return true iff this constant is positive zero (floating point), negative
64 // zero (floating point), or a null value.
65 bool Constant::isZeroValue() const {
66 // Floating point values have an explicit -0.0 value.
67 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
70 // Equivalent for a vector of -0.0's.
71 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
72 if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
73 if (CV->getElementAsAPFloat(0).isZero())
76 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
77 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
78 if (SplatCFP && SplatCFP->isZero())
81 // Otherwise, just use +0.0.
85 bool Constant::isNullValue() const {
87 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
91 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
92 return CFP->isZero() && !CFP->isNegative();
94 // constant zero is zero for aggregates, cpnull is null for pointers, none for
96 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
97 isa<ConstantTokenNone>(this);
100 bool Constant::isAllOnesValue() const {
101 // Check for -1 integers
102 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
103 return CI->isMinusOne();
105 // Check for FP which are bitcasted from -1 integers
106 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
107 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
109 // Check for constant vectors which are splats of -1 values.
110 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
111 if (Constant *Splat = CV->getSplatValue())
112 return Splat->isAllOnesValue();
114 // Check for constant vectors which are splats of -1 values.
115 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
117 if (CV->getElementType()->isFloatingPointTy())
118 return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
119 return CV->getElementAsAPInt(0).isAllOnesValue();
126 bool Constant::isOneValue() const {
127 // Check for 1 integers
128 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
131 // Check for FP which are bitcasted from 1 integers
132 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
133 return CFP->getValueAPF().bitcastToAPInt().isOneValue();
135 // Check for constant vectors which are splats of 1 values.
136 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
137 if (Constant *Splat = CV->getSplatValue())
138 return Splat->isOneValue();
140 // Check for constant vectors which are splats of 1 values.
141 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
143 if (CV->getElementType()->isFloatingPointTy())
144 return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
145 return CV->getElementAsAPInt(0).isOneValue();
152 bool Constant::isMinSignedValue() const {
153 // Check for INT_MIN integers
154 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
155 return CI->isMinValue(/*isSigned=*/true);
157 // Check for FP which are bitcasted from INT_MIN integers
158 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
159 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
161 // Check for constant vectors which are splats of INT_MIN values.
162 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
163 if (Constant *Splat = CV->getSplatValue())
164 return Splat->isMinSignedValue();
166 // Check for constant vectors which are splats of INT_MIN values.
167 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
169 if (CV->getElementType()->isFloatingPointTy())
170 return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
171 return CV->getElementAsAPInt(0).isMinSignedValue();
178 bool Constant::isNotMinSignedValue() const {
179 // Check for INT_MIN integers
180 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
181 return !CI->isMinValue(/*isSigned=*/true);
183 // Check for FP which are bitcasted from INT_MIN integers
184 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
185 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
187 // Check for constant vectors which are splats of INT_MIN values.
188 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
189 if (Constant *Splat = CV->getSplatValue())
190 return Splat->isNotMinSignedValue();
192 // Check for constant vectors which are splats of INT_MIN values.
193 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
195 if (CV->getElementType()->isFloatingPointTy())
196 return !CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
197 return !CV->getElementAsAPInt(0).isMinSignedValue();
201 // It *may* contain INT_MIN, we can't tell.
205 /// Constructor to create a '0' constant of arbitrary type.
206 Constant *Constant::getNullValue(Type *Ty) {
207 switch (Ty->getTypeID()) {
208 case Type::IntegerTyID:
209 return ConstantInt::get(Ty, 0);
211 return ConstantFP::get(Ty->getContext(),
212 APFloat::getZero(APFloat::IEEEhalf()));
213 case Type::FloatTyID:
214 return ConstantFP::get(Ty->getContext(),
215 APFloat::getZero(APFloat::IEEEsingle()));
216 case Type::DoubleTyID:
217 return ConstantFP::get(Ty->getContext(),
218 APFloat::getZero(APFloat::IEEEdouble()));
219 case Type::X86_FP80TyID:
220 return ConstantFP::get(Ty->getContext(),
221 APFloat::getZero(APFloat::x87DoubleExtended()));
222 case Type::FP128TyID:
223 return ConstantFP::get(Ty->getContext(),
224 APFloat::getZero(APFloat::IEEEquad()));
225 case Type::PPC_FP128TyID:
226 return ConstantFP::get(Ty->getContext(),
227 APFloat(APFloat::PPCDoubleDouble(),
228 APInt::getNullValue(128)));
229 case Type::PointerTyID:
230 return ConstantPointerNull::get(cast<PointerType>(Ty));
231 case Type::StructTyID:
232 case Type::ArrayTyID:
233 case Type::VectorTyID:
234 return ConstantAggregateZero::get(Ty);
235 case Type::TokenTyID:
236 return ConstantTokenNone::get(Ty->getContext());
238 // Function, Label, or Opaque type?
239 llvm_unreachable("Cannot create a null constant of that type!");
243 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
244 Type *ScalarTy = Ty->getScalarType();
246 // Create the base integer constant.
247 Constant *C = ConstantInt::get(Ty->getContext(), V);
249 // Convert an integer to a pointer, if necessary.
250 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
251 C = ConstantExpr::getIntToPtr(C, PTy);
253 // Broadcast a scalar to a vector, if necessary.
254 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
255 C = ConstantVector::getSplat(VTy->getNumElements(), C);
260 Constant *Constant::getAllOnesValue(Type *Ty) {
261 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
262 return ConstantInt::get(Ty->getContext(),
263 APInt::getAllOnesValue(ITy->getBitWidth()));
265 if (Ty->isFloatingPointTy()) {
266 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
267 !Ty->isPPC_FP128Ty());
268 return ConstantFP::get(Ty->getContext(), FL);
271 VectorType *VTy = cast<VectorType>(Ty);
272 return ConstantVector::getSplat(VTy->getNumElements(),
273 getAllOnesValue(VTy->getElementType()));
276 Constant *Constant::getAggregateElement(unsigned Elt) const {
277 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
278 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
280 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
281 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
283 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
284 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
286 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
287 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
292 Constant *Constant::getAggregateElement(Constant *Elt) const {
293 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
294 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
295 return getAggregateElement(CI->getZExtValue());
299 void Constant::destroyConstant() {
300 /// First call destroyConstantImpl on the subclass. This gives the subclass
301 /// a chance to remove the constant from any maps/pools it's contained in.
302 switch (getValueID()) {
304 llvm_unreachable("Not a constant!");
305 #define HANDLE_CONSTANT(Name) \
306 case Value::Name##Val: \
307 cast<Name>(this)->destroyConstantImpl(); \
309 #include "llvm/IR/Value.def"
312 // When a Constant is destroyed, there may be lingering
313 // references to the constant by other constants in the constant pool. These
314 // constants are implicitly dependent on the module that is being deleted,
315 // but they don't know that. Because we only find out when the CPV is
316 // deleted, we must now notify all of our users (that should only be
317 // Constants) that they are, in fact, invalid now and should be deleted.
319 while (!use_empty()) {
320 Value *V = user_back();
321 #ifndef NDEBUG // Only in -g mode...
322 if (!isa<Constant>(V)) {
323 dbgs() << "While deleting: " << *this
324 << "\n\nUse still stuck around after Def is destroyed: " << *V
328 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
329 cast<Constant>(V)->destroyConstant();
331 // The constant should remove itself from our use list...
332 assert((use_empty() || user_back() != V) && "Constant not removed!");
335 // Value has no outstanding references it is safe to delete it now...
339 static bool canTrapImpl(const Constant *C,
340 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
341 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
342 // The only thing that could possibly trap are constant exprs.
343 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
347 // ConstantExpr traps if any operands can trap.
348 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
349 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
350 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
355 // Otherwise, only specific operations can trap.
356 switch (CE->getOpcode()) {
359 case Instruction::UDiv:
360 case Instruction::SDiv:
361 case Instruction::URem:
362 case Instruction::SRem:
363 // Div and rem can trap if the RHS is not known to be non-zero.
364 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
370 bool Constant::canTrap() const {
371 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
372 return canTrapImpl(this, NonTrappingOps);
375 /// Check if C contains a GlobalValue for which Predicate is true.
377 ConstHasGlobalValuePredicate(const Constant *C,
378 bool (*Predicate)(const GlobalValue *)) {
379 SmallPtrSet<const Constant *, 8> Visited;
380 SmallVector<const Constant *, 8> WorkList;
381 WorkList.push_back(C);
384 while (!WorkList.empty()) {
385 const Constant *WorkItem = WorkList.pop_back_val();
386 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
389 for (const Value *Op : WorkItem->operands()) {
390 const Constant *ConstOp = dyn_cast<Constant>(Op);
393 if (Visited.insert(ConstOp).second)
394 WorkList.push_back(ConstOp);
400 bool Constant::isThreadDependent() const {
401 auto DLLImportPredicate = [](const GlobalValue *GV) {
402 return GV->isThreadLocal();
404 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
407 bool Constant::isDLLImportDependent() const {
408 auto DLLImportPredicate = [](const GlobalValue *GV) {
409 return GV->hasDLLImportStorageClass();
411 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
414 bool Constant::isConstantUsed() const {
415 for (const User *U : users()) {
416 const Constant *UC = dyn_cast<Constant>(U);
417 if (!UC || isa<GlobalValue>(UC))
420 if (UC->isConstantUsed())
426 bool Constant::needsRelocation() const {
427 if (isa<GlobalValue>(this))
428 return true; // Global reference.
430 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
431 return BA->getFunction()->needsRelocation();
433 // While raw uses of blockaddress need to be relocated, differences between
434 // two of them don't when they are for labels in the same function. This is a
435 // common idiom when creating a table for the indirect goto extension, so we
436 // handle it efficiently here.
437 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
438 if (CE->getOpcode() == Instruction::Sub) {
439 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
440 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
441 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
442 RHS->getOpcode() == Instruction::PtrToInt &&
443 isa<BlockAddress>(LHS->getOperand(0)) &&
444 isa<BlockAddress>(RHS->getOperand(0)) &&
445 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
446 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
451 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
452 Result |= cast<Constant>(getOperand(i))->needsRelocation();
457 /// If the specified constantexpr is dead, remove it. This involves recursively
458 /// eliminating any dead users of the constantexpr.
459 static bool removeDeadUsersOfConstant(const Constant *C) {
460 if (isa<GlobalValue>(C)) return false; // Cannot remove this
462 while (!C->use_empty()) {
463 const Constant *User = dyn_cast<Constant>(C->user_back());
464 if (!User) return false; // Non-constant usage;
465 if (!removeDeadUsersOfConstant(User))
466 return false; // Constant wasn't dead
469 const_cast<Constant*>(C)->destroyConstant();
474 void Constant::removeDeadConstantUsers() const {
475 Value::const_user_iterator I = user_begin(), E = user_end();
476 Value::const_user_iterator LastNonDeadUser = E;
478 const Constant *User = dyn_cast<Constant>(*I);
485 if (!removeDeadUsersOfConstant(User)) {
486 // If the constant wasn't dead, remember that this was the last live use
487 // and move on to the next constant.
493 // If the constant was dead, then the iterator is invalidated.
494 if (LastNonDeadUser == E) {
506 //===----------------------------------------------------------------------===//
508 //===----------------------------------------------------------------------===//
510 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
511 : ConstantData(Ty, ConstantIntVal), Val(V) {
512 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
515 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
516 LLVMContextImpl *pImpl = Context.pImpl;
517 if (!pImpl->TheTrueVal)
518 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
519 return pImpl->TheTrueVal;
522 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
523 LLVMContextImpl *pImpl = Context.pImpl;
524 if (!pImpl->TheFalseVal)
525 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
526 return pImpl->TheFalseVal;
529 Constant *ConstantInt::getTrue(Type *Ty) {
530 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
531 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
532 if (auto *VTy = dyn_cast<VectorType>(Ty))
533 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
537 Constant *ConstantInt::getFalse(Type *Ty) {
538 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
539 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
540 if (auto *VTy = dyn_cast<VectorType>(Ty))
541 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
545 // Get a ConstantInt from an APInt.
546 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
547 // get an existing value or the insertion position
548 LLVMContextImpl *pImpl = Context.pImpl;
549 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
551 // Get the corresponding integer type for the bit width of the value.
552 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
553 Slot.reset(new ConstantInt(ITy, V));
555 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
559 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
560 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
562 // For vectors, broadcast the value.
563 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
564 return ConstantVector::getSplat(VTy->getNumElements(), C);
569 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
570 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
573 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
574 return get(Ty, V, true);
577 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
578 return get(Ty, V, true);
581 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
582 ConstantInt *C = get(Ty->getContext(), V);
583 assert(C->getType() == Ty->getScalarType() &&
584 "ConstantInt type doesn't match the type implied by its value!");
586 // For vectors, broadcast the value.
587 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
588 return ConstantVector::getSplat(VTy->getNumElements(), C);
593 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
594 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
597 /// Remove the constant from the constant table.
598 void ConstantInt::destroyConstantImpl() {
599 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
602 //===----------------------------------------------------------------------===//
604 //===----------------------------------------------------------------------===//
606 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
608 return &APFloat::IEEEhalf();
610 return &APFloat::IEEEsingle();
611 if (Ty->isDoubleTy())
612 return &APFloat::IEEEdouble();
613 if (Ty->isX86_FP80Ty())
614 return &APFloat::x87DoubleExtended();
615 else if (Ty->isFP128Ty())
616 return &APFloat::IEEEquad();
618 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
619 return &APFloat::PPCDoubleDouble();
622 Constant *ConstantFP::get(Type *Ty, double V) {
623 LLVMContext &Context = Ty->getContext();
627 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
628 APFloat::rmNearestTiesToEven, &ignored);
629 Constant *C = get(Context, FV);
631 // For vectors, broadcast the value.
632 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
633 return ConstantVector::getSplat(VTy->getNumElements(), C);
639 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
640 LLVMContext &Context = Ty->getContext();
642 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
643 Constant *C = get(Context, FV);
645 // For vectors, broadcast the value.
646 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
647 return ConstantVector::getSplat(VTy->getNumElements(), C);
652 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
653 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
654 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
655 Constant *C = get(Ty->getContext(), NaN);
657 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
658 return ConstantVector::getSplat(VTy->getNumElements(), C);
663 Constant *ConstantFP::getNegativeZero(Type *Ty) {
664 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
665 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
666 Constant *C = get(Ty->getContext(), NegZero);
668 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
669 return ConstantVector::getSplat(VTy->getNumElements(), C);
675 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
676 if (Ty->isFPOrFPVectorTy())
677 return getNegativeZero(Ty);
679 return Constant::getNullValue(Ty);
683 // ConstantFP accessors.
684 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
685 LLVMContextImpl* pImpl = Context.pImpl;
687 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
691 if (&V.getSemantics() == &APFloat::IEEEhalf())
692 Ty = Type::getHalfTy(Context);
693 else if (&V.getSemantics() == &APFloat::IEEEsingle())
694 Ty = Type::getFloatTy(Context);
695 else if (&V.getSemantics() == &APFloat::IEEEdouble())
696 Ty = Type::getDoubleTy(Context);
697 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
698 Ty = Type::getX86_FP80Ty(Context);
699 else if (&V.getSemantics() == &APFloat::IEEEquad())
700 Ty = Type::getFP128Ty(Context);
702 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
703 "Unknown FP format");
704 Ty = Type::getPPC_FP128Ty(Context);
706 Slot.reset(new ConstantFP(Ty, V));
712 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
713 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
714 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
716 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
717 return ConstantVector::getSplat(VTy->getNumElements(), C);
722 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
723 : ConstantData(Ty, ConstantFPVal), Val(V) {
724 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
728 bool ConstantFP::isExactlyValue(const APFloat &V) const {
729 return Val.bitwiseIsEqual(V);
732 /// Remove the constant from the constant table.
733 void ConstantFP::destroyConstantImpl() {
734 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
737 //===----------------------------------------------------------------------===//
738 // ConstantAggregateZero Implementation
739 //===----------------------------------------------------------------------===//
741 Constant *ConstantAggregateZero::getSequentialElement() const {
742 return Constant::getNullValue(getType()->getSequentialElementType());
745 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
746 return Constant::getNullValue(getType()->getStructElementType(Elt));
749 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
750 if (isa<SequentialType>(getType()))
751 return getSequentialElement();
752 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
755 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
756 if (isa<SequentialType>(getType()))
757 return getSequentialElement();
758 return getStructElement(Idx);
761 unsigned ConstantAggregateZero::getNumElements() const {
762 Type *Ty = getType();
763 if (auto *AT = dyn_cast<ArrayType>(Ty))
764 return AT->getNumElements();
765 if (auto *VT = dyn_cast<VectorType>(Ty))
766 return VT->getNumElements();
767 return Ty->getStructNumElements();
770 //===----------------------------------------------------------------------===//
771 // UndefValue Implementation
772 //===----------------------------------------------------------------------===//
774 UndefValue *UndefValue::getSequentialElement() const {
775 return UndefValue::get(getType()->getSequentialElementType());
778 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
779 return UndefValue::get(getType()->getStructElementType(Elt));
782 UndefValue *UndefValue::getElementValue(Constant *C) const {
783 if (isa<SequentialType>(getType()))
784 return getSequentialElement();
785 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
788 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
789 if (isa<SequentialType>(getType()))
790 return getSequentialElement();
791 return getStructElement(Idx);
794 unsigned UndefValue::getNumElements() const {
795 Type *Ty = getType();
796 if (auto *ST = dyn_cast<SequentialType>(Ty))
797 return ST->getNumElements();
798 return Ty->getStructNumElements();
801 //===----------------------------------------------------------------------===//
802 // ConstantXXX Classes
803 //===----------------------------------------------------------------------===//
805 template <typename ItTy, typename EltTy>
806 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
807 for (; Start != End; ++Start)
813 template <typename SequentialTy, typename ElementTy>
814 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
815 assert(!V.empty() && "Cannot get empty int sequence.");
817 SmallVector<ElementTy, 16> Elts;
818 for (Constant *C : V)
819 if (auto *CI = dyn_cast<ConstantInt>(C))
820 Elts.push_back(CI->getZExtValue());
823 return SequentialTy::get(V[0]->getContext(), Elts);
826 template <typename SequentialTy, typename ElementTy>
827 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
828 assert(!V.empty() && "Cannot get empty FP sequence.");
830 SmallVector<ElementTy, 16> Elts;
831 for (Constant *C : V)
832 if (auto *CFP = dyn_cast<ConstantFP>(C))
833 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
836 return SequentialTy::getFP(V[0]->getContext(), Elts);
839 template <typename SequenceTy>
840 static Constant *getSequenceIfElementsMatch(Constant *C,
841 ArrayRef<Constant *> V) {
842 // We speculatively build the elements here even if it turns out that there is
843 // a constantexpr or something else weird, since it is so uncommon for that to
845 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
846 if (CI->getType()->isIntegerTy(8))
847 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
848 else if (CI->getType()->isIntegerTy(16))
849 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
850 else if (CI->getType()->isIntegerTy(32))
851 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
852 else if (CI->getType()->isIntegerTy(64))
853 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
854 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
855 if (CFP->getType()->isHalfTy())
856 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
857 else if (CFP->getType()->isFloatTy())
858 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
859 else if (CFP->getType()->isDoubleTy())
860 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
866 ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
867 ArrayRef<Constant *> V)
868 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
870 std::copy(V.begin(), V.end(), op_begin());
872 // Check that types match, unless this is an opaque struct.
873 if (auto *ST = dyn_cast<StructType>(T))
876 for (unsigned I = 0, E = V.size(); I != E; ++I)
877 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
878 "Initializer for composite element doesn't match!");
881 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
882 : ConstantAggregate(T, ConstantArrayVal, V) {
883 assert(V.size() == T->getNumElements() &&
884 "Invalid initializer for constant array");
887 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
888 if (Constant *C = getImpl(Ty, V))
890 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
893 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
894 // Empty arrays are canonicalized to ConstantAggregateZero.
896 return ConstantAggregateZero::get(Ty);
898 for (unsigned i = 0, e = V.size(); i != e; ++i) {
899 assert(V[i]->getType() == Ty->getElementType() &&
900 "Wrong type in array element initializer");
903 // If this is an all-zero array, return a ConstantAggregateZero object. If
904 // all undef, return an UndefValue, if "all simple", then return a
905 // ConstantDataArray.
907 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
908 return UndefValue::get(Ty);
910 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
911 return ConstantAggregateZero::get(Ty);
913 // Check to see if all of the elements are ConstantFP or ConstantInt and if
914 // the element type is compatible with ConstantDataVector. If so, use it.
915 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
916 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
918 // Otherwise, we really do want to create a ConstantArray.
922 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
923 ArrayRef<Constant*> V,
925 unsigned VecSize = V.size();
926 SmallVector<Type*, 16> EltTypes(VecSize);
927 for (unsigned i = 0; i != VecSize; ++i)
928 EltTypes[i] = V[i]->getType();
930 return StructType::get(Context, EltTypes, Packed);
934 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
937 "ConstantStruct::getTypeForElements cannot be called on empty list");
938 return getTypeForElements(V[0]->getContext(), V, Packed);
941 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
942 : ConstantAggregate(T, ConstantStructVal, V) {
943 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
944 "Invalid initializer for constant struct");
947 // ConstantStruct accessors.
948 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
949 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
950 "Incorrect # elements specified to ConstantStruct::get");
952 // Create a ConstantAggregateZero value if all elements are zeros.
954 bool isUndef = false;
957 isUndef = isa<UndefValue>(V[0]);
958 isZero = V[0]->isNullValue();
959 if (isUndef || isZero) {
960 for (unsigned i = 0, e = V.size(); i != e; ++i) {
961 if (!V[i]->isNullValue())
963 if (!isa<UndefValue>(V[i]))
969 return ConstantAggregateZero::get(ST);
971 return UndefValue::get(ST);
973 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
976 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
977 : ConstantAggregate(T, ConstantVectorVal, V) {
978 assert(V.size() == T->getNumElements() &&
979 "Invalid initializer for constant vector");
982 // ConstantVector accessors.
983 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
984 if (Constant *C = getImpl(V))
986 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
987 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
990 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
991 assert(!V.empty() && "Vectors can't be empty");
992 VectorType *T = VectorType::get(V.front()->getType(), V.size());
994 // If this is an all-undef or all-zero vector, return a
995 // ConstantAggregateZero or UndefValue.
997 bool isZero = C->isNullValue();
998 bool isUndef = isa<UndefValue>(C);
1000 if (isZero || isUndef) {
1001 for (unsigned i = 1, e = V.size(); i != e; ++i)
1003 isZero = isUndef = false;
1009 return ConstantAggregateZero::get(T);
1011 return UndefValue::get(T);
1013 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1014 // the element type is compatible with ConstantDataVector. If so, use it.
1015 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1016 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1018 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1019 // the operand list contains a ConstantExpr or something else strange.
1023 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1024 // If this splat is compatible with ConstantDataVector, use it instead of
1026 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1027 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1028 return ConstantDataVector::getSplat(NumElts, V);
1030 SmallVector<Constant*, 32> Elts(NumElts, V);
1034 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1035 LLVMContextImpl *pImpl = Context.pImpl;
1036 if (!pImpl->TheNoneToken)
1037 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1038 return pImpl->TheNoneToken.get();
1041 /// Remove the constant from the constant table.
1042 void ConstantTokenNone::destroyConstantImpl() {
1043 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1046 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1047 // can't be inline because we don't want to #include Instruction.h into
1049 bool ConstantExpr::isCast() const {
1050 return Instruction::isCast(getOpcode());
1053 bool ConstantExpr::isCompare() const {
1054 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1057 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1058 if (getOpcode() != Instruction::GetElementPtr) return false;
1060 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1061 User::const_op_iterator OI = std::next(this->op_begin());
1063 // The remaining indices may be compile-time known integers within the bounds
1064 // of the corresponding notional static array types.
1065 for (; GEPI != E; ++GEPI, ++OI) {
1066 if (isa<UndefValue>(*OI))
1068 auto *CI = dyn_cast<ConstantInt>(*OI);
1069 if (!CI || (GEPI.isBoundedSequential() &&
1070 (CI->getValue().getActiveBits() > 64 ||
1071 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
1075 // All the indices checked out.
1079 bool ConstantExpr::hasIndices() const {
1080 return getOpcode() == Instruction::ExtractValue ||
1081 getOpcode() == Instruction::InsertValue;
1084 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1085 if (const ExtractValueConstantExpr *EVCE =
1086 dyn_cast<ExtractValueConstantExpr>(this))
1087 return EVCE->Indices;
1089 return cast<InsertValueConstantExpr>(this)->Indices;
1092 unsigned ConstantExpr::getPredicate() const {
1093 return cast<CompareConstantExpr>(this)->predicate;
1097 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1098 assert(Op->getType() == getOperand(OpNo)->getType() &&
1099 "Replacing operand with value of different type!");
1100 if (getOperand(OpNo) == Op)
1101 return const_cast<ConstantExpr*>(this);
1103 SmallVector<Constant*, 8> NewOps;
1104 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1105 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1107 return getWithOperands(NewOps);
1110 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1111 bool OnlyIfReduced, Type *SrcTy) const {
1112 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1114 // If no operands changed return self.
1115 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1116 return const_cast<ConstantExpr*>(this);
1118 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1119 switch (getOpcode()) {
1120 case Instruction::Trunc:
1121 case Instruction::ZExt:
1122 case Instruction::SExt:
1123 case Instruction::FPTrunc:
1124 case Instruction::FPExt:
1125 case Instruction::UIToFP:
1126 case Instruction::SIToFP:
1127 case Instruction::FPToUI:
1128 case Instruction::FPToSI:
1129 case Instruction::PtrToInt:
1130 case Instruction::IntToPtr:
1131 case Instruction::BitCast:
1132 case Instruction::AddrSpaceCast:
1133 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1134 case Instruction::Select:
1135 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1136 case Instruction::InsertElement:
1137 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1139 case Instruction::ExtractElement:
1140 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1141 case Instruction::InsertValue:
1142 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1144 case Instruction::ExtractValue:
1145 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1146 case Instruction::ShuffleVector:
1147 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1149 case Instruction::GetElementPtr: {
1150 auto *GEPO = cast<GEPOperator>(this);
1151 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1152 return ConstantExpr::getGetElementPtr(
1153 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1154 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1156 case Instruction::ICmp:
1157 case Instruction::FCmp:
1158 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1161 assert(getNumOperands() == 2 && "Must be binary operator?");
1162 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1168 //===----------------------------------------------------------------------===//
1169 // isValueValidForType implementations
1171 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1172 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1173 if (Ty->isIntegerTy(1))
1174 return Val == 0 || Val == 1;
1175 return isUIntN(NumBits, Val);
1178 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1179 unsigned NumBits = Ty->getIntegerBitWidth();
1180 if (Ty->isIntegerTy(1))
1181 return Val == 0 || Val == 1 || Val == -1;
1182 return isIntN(NumBits, Val);
1185 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1186 // convert modifies in place, so make a copy.
1187 APFloat Val2 = APFloat(Val);
1189 switch (Ty->getTypeID()) {
1191 return false; // These can't be represented as floating point!
1193 // FIXME rounding mode needs to be more flexible
1194 case Type::HalfTyID: {
1195 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1197 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1200 case Type::FloatTyID: {
1201 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1203 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1206 case Type::DoubleTyID: {
1207 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1208 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1209 &Val2.getSemantics() == &APFloat::IEEEdouble())
1211 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1214 case Type::X86_FP80TyID:
1215 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1216 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1217 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1218 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1219 case Type::FP128TyID:
1220 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1221 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1222 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1223 &Val2.getSemantics() == &APFloat::IEEEquad();
1224 case Type::PPC_FP128TyID:
1225 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1226 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1227 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1228 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1233 //===----------------------------------------------------------------------===//
1234 // Factory Function Implementation
1236 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1237 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1238 "Cannot create an aggregate zero of non-aggregate type!");
1240 std::unique_ptr<ConstantAggregateZero> &Entry =
1241 Ty->getContext().pImpl->CAZConstants[Ty];
1243 Entry.reset(new ConstantAggregateZero(Ty));
1248 /// Remove the constant from the constant table.
1249 void ConstantAggregateZero::destroyConstantImpl() {
1250 getContext().pImpl->CAZConstants.erase(getType());
1253 /// Remove the constant from the constant table.
1254 void ConstantArray::destroyConstantImpl() {
1255 getType()->getContext().pImpl->ArrayConstants.remove(this);
1259 //---- ConstantStruct::get() implementation...
1262 /// Remove the constant from the constant table.
1263 void ConstantStruct::destroyConstantImpl() {
1264 getType()->getContext().pImpl->StructConstants.remove(this);
1267 /// Remove the constant from the constant table.
1268 void ConstantVector::destroyConstantImpl() {
1269 getType()->getContext().pImpl->VectorConstants.remove(this);
1272 Constant *Constant::getSplatValue() const {
1273 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1274 if (isa<ConstantAggregateZero>(this))
1275 return getNullValue(this->getType()->getVectorElementType());
1276 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1277 return CV->getSplatValue();
1278 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1279 return CV->getSplatValue();
1283 Constant *ConstantVector::getSplatValue() const {
1284 // Check out first element.
1285 Constant *Elt = getOperand(0);
1286 // Then make sure all remaining elements point to the same value.
1287 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1288 if (getOperand(I) != Elt)
1293 const APInt &Constant::getUniqueInteger() const {
1294 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1295 return CI->getValue();
1296 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1297 const Constant *C = this->getAggregateElement(0U);
1298 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1299 return cast<ConstantInt>(C)->getValue();
1302 //---- ConstantPointerNull::get() implementation.
1305 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1306 std::unique_ptr<ConstantPointerNull> &Entry =
1307 Ty->getContext().pImpl->CPNConstants[Ty];
1309 Entry.reset(new ConstantPointerNull(Ty));
1314 /// Remove the constant from the constant table.
1315 void ConstantPointerNull::destroyConstantImpl() {
1316 getContext().pImpl->CPNConstants.erase(getType());
1319 UndefValue *UndefValue::get(Type *Ty) {
1320 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1322 Entry.reset(new UndefValue(Ty));
1327 /// Remove the constant from the constant table.
1328 void UndefValue::destroyConstantImpl() {
1329 // Free the constant and any dangling references to it.
1330 getContext().pImpl->UVConstants.erase(getType());
1333 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1334 assert(BB->getParent() && "Block must have a parent");
1335 return get(BB->getParent(), BB);
1338 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1340 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1342 BA = new BlockAddress(F, BB);
1344 assert(BA->getFunction() == F && "Basic block moved between functions");
1348 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1349 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1353 BB->AdjustBlockAddressRefCount(1);
1356 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1357 if (!BB->hasAddressTaken())
1360 const Function *F = BB->getParent();
1361 assert(F && "Block must have a parent");
1363 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1364 assert(BA && "Refcount and block address map disagree!");
1368 /// Remove the constant from the constant table.
1369 void BlockAddress::destroyConstantImpl() {
1370 getFunction()->getType()->getContext().pImpl
1371 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1372 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1375 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1376 // This could be replacing either the Basic Block or the Function. In either
1377 // case, we have to remove the map entry.
1378 Function *NewF = getFunction();
1379 BasicBlock *NewBB = getBasicBlock();
1382 NewF = cast<Function>(To->stripPointerCasts());
1384 assert(From == NewBB && "From does not match any operand");
1385 NewBB = cast<BasicBlock>(To);
1388 // See if the 'new' entry already exists, if not, just update this in place
1389 // and return early.
1390 BlockAddress *&NewBA =
1391 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1395 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1397 // Remove the old entry, this can't cause the map to rehash (just a
1398 // tombstone will get added).
1399 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1402 setOperand(0, NewF);
1403 setOperand(1, NewBB);
1404 getBasicBlock()->AdjustBlockAddressRefCount(1);
1406 // If we just want to keep the existing value, then return null.
1407 // Callers know that this means we shouldn't delete this value.
1411 //---- ConstantExpr::get() implementations.
1414 /// This is a utility function to handle folding of casts and lookup of the
1415 /// cast in the ExprConstants map. It is used by the various get* methods below.
1416 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1417 bool OnlyIfReduced = false) {
1418 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1419 // Fold a few common cases
1420 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1426 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1428 // Look up the constant in the table first to ensure uniqueness.
1429 ConstantExprKeyType Key(opc, C);
1431 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1434 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1435 bool OnlyIfReduced) {
1436 Instruction::CastOps opc = Instruction::CastOps(oc);
1437 assert(Instruction::isCast(opc) && "opcode out of range");
1438 assert(C && Ty && "Null arguments to getCast");
1439 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1443 llvm_unreachable("Invalid cast opcode");
1444 case Instruction::Trunc:
1445 return getTrunc(C, Ty, OnlyIfReduced);
1446 case Instruction::ZExt:
1447 return getZExt(C, Ty, OnlyIfReduced);
1448 case Instruction::SExt:
1449 return getSExt(C, Ty, OnlyIfReduced);
1450 case Instruction::FPTrunc:
1451 return getFPTrunc(C, Ty, OnlyIfReduced);
1452 case Instruction::FPExt:
1453 return getFPExtend(C, Ty, OnlyIfReduced);
1454 case Instruction::UIToFP:
1455 return getUIToFP(C, Ty, OnlyIfReduced);
1456 case Instruction::SIToFP:
1457 return getSIToFP(C, Ty, OnlyIfReduced);
1458 case Instruction::FPToUI:
1459 return getFPToUI(C, Ty, OnlyIfReduced);
1460 case Instruction::FPToSI:
1461 return getFPToSI(C, Ty, OnlyIfReduced);
1462 case Instruction::PtrToInt:
1463 return getPtrToInt(C, Ty, OnlyIfReduced);
1464 case Instruction::IntToPtr:
1465 return getIntToPtr(C, Ty, OnlyIfReduced);
1466 case Instruction::BitCast:
1467 return getBitCast(C, Ty, OnlyIfReduced);
1468 case Instruction::AddrSpaceCast:
1469 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1473 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1474 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1475 return getBitCast(C, Ty);
1476 return getZExt(C, Ty);
1479 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1480 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1481 return getBitCast(C, Ty);
1482 return getSExt(C, Ty);
1485 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1486 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1487 return getBitCast(C, Ty);
1488 return getTrunc(C, Ty);
1491 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1492 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1493 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1496 if (Ty->isIntOrIntVectorTy())
1497 return getPtrToInt(S, Ty);
1499 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1500 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1501 return getAddrSpaceCast(S, Ty);
1503 return getBitCast(S, Ty);
1506 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1508 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1509 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1511 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1512 return getAddrSpaceCast(S, Ty);
1514 return getBitCast(S, Ty);
1517 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
1518 assert(C->getType()->isIntOrIntVectorTy() &&
1519 Ty->isIntOrIntVectorTy() && "Invalid cast");
1520 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1521 unsigned DstBits = Ty->getScalarSizeInBits();
1522 Instruction::CastOps opcode =
1523 (SrcBits == DstBits ? Instruction::BitCast :
1524 (SrcBits > DstBits ? Instruction::Trunc :
1525 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1526 return getCast(opcode, C, Ty);
1529 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1530 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1532 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1533 unsigned DstBits = Ty->getScalarSizeInBits();
1534 if (SrcBits == DstBits)
1535 return C; // Avoid a useless cast
1536 Instruction::CastOps opcode =
1537 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1538 return getCast(opcode, C, Ty);
1541 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1543 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1544 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1546 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1547 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1548 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1549 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1550 "SrcTy must be larger than DestTy for Trunc!");
1552 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1555 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1557 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1558 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1560 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1561 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1562 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1563 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1564 "SrcTy must be smaller than DestTy for SExt!");
1566 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1569 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1571 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1572 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1574 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1575 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1576 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1577 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1578 "SrcTy must be smaller than DestTy for ZExt!");
1580 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1583 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1585 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1586 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1588 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1589 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1590 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1591 "This is an illegal floating point truncation!");
1592 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1595 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1597 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1598 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1600 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1601 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1602 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1603 "This is an illegal floating point extension!");
1604 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1607 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
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()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1614 "This is an illegal uint to floating point cast!");
1615 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1618 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1620 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1621 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1623 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1624 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1625 "This is an illegal sint to floating point cast!");
1626 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1629 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1631 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1632 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1634 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1635 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1636 "This is an illegal floating point to uint cast!");
1637 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1640 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1642 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1643 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1645 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1646 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1647 "This is an illegal floating point to sint cast!");
1648 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1651 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1652 bool OnlyIfReduced) {
1653 assert(C->getType()->isPtrOrPtrVectorTy() &&
1654 "PtrToInt source must be pointer or pointer vector");
1655 assert(DstTy->isIntOrIntVectorTy() &&
1656 "PtrToInt destination must be integer or integer vector");
1657 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1658 if (isa<VectorType>(C->getType()))
1659 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1660 "Invalid cast between a different number of vector elements");
1661 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1664 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1665 bool OnlyIfReduced) {
1666 assert(C->getType()->isIntOrIntVectorTy() &&
1667 "IntToPtr source must be integer or integer vector");
1668 assert(DstTy->isPtrOrPtrVectorTy() &&
1669 "IntToPtr destination must be a pointer or pointer vector");
1670 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1671 if (isa<VectorType>(C->getType()))
1672 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1673 "Invalid cast between a different number of vector elements");
1674 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1677 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1678 bool OnlyIfReduced) {
1679 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1680 "Invalid constantexpr bitcast!");
1682 // It is common to ask for a bitcast of a value to its own type, handle this
1684 if (C->getType() == DstTy) return C;
1686 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1689 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1690 bool OnlyIfReduced) {
1691 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1692 "Invalid constantexpr addrspacecast!");
1694 // Canonicalize addrspacecasts between different pointer types by first
1695 // bitcasting the pointer type and then converting the address space.
1696 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1697 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1698 Type *DstElemTy = DstScalarTy->getElementType();
1699 if (SrcScalarTy->getElementType() != DstElemTy) {
1700 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1701 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1702 // Handle vectors of pointers.
1703 MidTy = VectorType::get(MidTy, VT->getNumElements());
1705 C = getBitCast(C, MidTy);
1707 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1710 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1711 unsigned Flags, Type *OnlyIfReducedTy) {
1712 // Check the operands for consistency first.
1713 assert(Opcode >= Instruction::BinaryOpsBegin &&
1714 Opcode < Instruction::BinaryOpsEnd &&
1715 "Invalid opcode in binary constant expression");
1716 assert(C1->getType() == C2->getType() &&
1717 "Operand types in binary constant expression should match");
1721 case Instruction::Add:
1722 case Instruction::Sub:
1723 case Instruction::Mul:
1724 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1725 assert(C1->getType()->isIntOrIntVectorTy() &&
1726 "Tried to create an integer operation on a non-integer type!");
1728 case Instruction::FAdd:
1729 case Instruction::FSub:
1730 case Instruction::FMul:
1731 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1732 assert(C1->getType()->isFPOrFPVectorTy() &&
1733 "Tried to create a floating-point operation on a "
1734 "non-floating-point type!");
1736 case Instruction::UDiv:
1737 case Instruction::SDiv:
1738 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1739 assert(C1->getType()->isIntOrIntVectorTy() &&
1740 "Tried to create an arithmetic operation on a non-arithmetic type!");
1742 case Instruction::FDiv:
1743 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1744 assert(C1->getType()->isFPOrFPVectorTy() &&
1745 "Tried to create an arithmetic operation on a non-arithmetic type!");
1747 case Instruction::URem:
1748 case Instruction::SRem:
1749 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1750 assert(C1->getType()->isIntOrIntVectorTy() &&
1751 "Tried to create an arithmetic operation on a non-arithmetic type!");
1753 case Instruction::FRem:
1754 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1755 assert(C1->getType()->isFPOrFPVectorTy() &&
1756 "Tried to create an arithmetic operation on a non-arithmetic type!");
1758 case Instruction::And:
1759 case Instruction::Or:
1760 case Instruction::Xor:
1761 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1762 assert(C1->getType()->isIntOrIntVectorTy() &&
1763 "Tried to create a logical operation on a non-integral type!");
1765 case Instruction::Shl:
1766 case Instruction::LShr:
1767 case Instruction::AShr:
1768 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1769 assert(C1->getType()->isIntOrIntVectorTy() &&
1770 "Tried to create a shift operation on a non-integer type!");
1777 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1778 return FC; // Fold a few common cases.
1780 if (OnlyIfReducedTy == C1->getType())
1783 Constant *ArgVec[] = { C1, C2 };
1784 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1786 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1787 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1790 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1791 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1792 // Note that a non-inbounds gep is used, as null isn't within any object.
1793 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1794 Constant *GEP = getGetElementPtr(
1795 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1796 return getPtrToInt(GEP,
1797 Type::getInt64Ty(Ty->getContext()));
1800 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1801 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1802 // Note that a non-inbounds gep is used, as null isn't within any object.
1803 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
1804 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1805 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1806 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1807 Constant *Indices[2] = { Zero, One };
1808 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1809 return getPtrToInt(GEP,
1810 Type::getInt64Ty(Ty->getContext()));
1813 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1814 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1818 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1819 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1820 // Note that a non-inbounds gep is used, as null isn't within any object.
1821 Constant *GEPIdx[] = {
1822 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1825 Constant *GEP = getGetElementPtr(
1826 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1827 return getPtrToInt(GEP,
1828 Type::getInt64Ty(Ty->getContext()));
1831 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1832 Constant *C2, bool OnlyIfReduced) {
1833 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1835 switch (Predicate) {
1836 default: llvm_unreachable("Invalid CmpInst predicate");
1837 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1838 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1839 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1840 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1841 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1842 case CmpInst::FCMP_TRUE:
1843 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1845 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1846 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1847 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1848 case CmpInst::ICMP_SLE:
1849 return getICmp(Predicate, C1, C2, OnlyIfReduced);
1853 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1854 Type *OnlyIfReducedTy) {
1855 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1857 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1858 return SC; // Fold common cases
1860 if (OnlyIfReducedTy == V1->getType())
1863 Constant *ArgVec[] = { C, V1, V2 };
1864 ConstantExprKeyType Key(Instruction::Select, ArgVec);
1866 LLVMContextImpl *pImpl = C->getContext().pImpl;
1867 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1870 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1871 ArrayRef<Value *> Idxs, bool InBounds,
1872 Optional<unsigned> InRangeIndex,
1873 Type *OnlyIfReducedTy) {
1875 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1879 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1882 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
1883 return FC; // Fold a few common cases.
1885 // Get the result type of the getelementptr!
1886 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1887 assert(DestTy && "GEP indices invalid!");
1888 unsigned AS = C->getType()->getPointerAddressSpace();
1889 Type *ReqTy = DestTy->getPointerTo(AS);
1891 unsigned NumVecElts = 0;
1892 if (C->getType()->isVectorTy())
1893 NumVecElts = C->getType()->getVectorNumElements();
1894 else for (auto Idx : Idxs)
1895 if (Idx->getType()->isVectorTy())
1896 NumVecElts = Idx->getType()->getVectorNumElements();
1899 ReqTy = VectorType::get(ReqTy, NumVecElts);
1901 if (OnlyIfReducedTy == ReqTy)
1904 // Look up the constant in the table first to ensure uniqueness
1905 std::vector<Constant*> ArgVec;
1906 ArgVec.reserve(1 + Idxs.size());
1907 ArgVec.push_back(C);
1908 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1909 assert((!Idxs[i]->getType()->isVectorTy() ||
1910 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
1911 "getelementptr index type missmatch");
1913 Constant *Idx = cast<Constant>(Idxs[i]);
1914 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
1915 Idx = ConstantVector::getSplat(NumVecElts, Idx);
1916 ArgVec.push_back(Idx);
1919 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
1920 if (InRangeIndex && *InRangeIndex < 63)
1921 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
1922 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1923 SubClassOptionalData, None, Ty);
1925 LLVMContextImpl *pImpl = C->getContext().pImpl;
1926 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1929 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
1930 Constant *RHS, bool OnlyIfReduced) {
1931 assert(LHS->getType() == RHS->getType());
1932 assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
1933 "Invalid ICmp Predicate");
1935 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1936 return FC; // Fold a few common cases...
1941 // Look up the constant in the table first to ensure uniqueness
1942 Constant *ArgVec[] = { LHS, RHS };
1943 // Get the key type with both the opcode and predicate
1944 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
1946 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1947 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1948 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1950 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1951 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1954 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
1955 Constant *RHS, bool OnlyIfReduced) {
1956 assert(LHS->getType() == RHS->getType());
1957 assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
1958 "Invalid FCmp Predicate");
1960 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1961 return FC; // Fold a few common cases...
1966 // Look up the constant in the table first to ensure uniqueness
1967 Constant *ArgVec[] = { LHS, RHS };
1968 // Get the key type with both the opcode and predicate
1969 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
1971 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1972 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1973 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1975 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1976 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1979 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
1980 Type *OnlyIfReducedTy) {
1981 assert(Val->getType()->isVectorTy() &&
1982 "Tried to create extractelement operation on non-vector type!");
1983 assert(Idx->getType()->isIntegerTy() &&
1984 "Extractelement index must be an integer type!");
1986 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1987 return FC; // Fold a few common cases.
1989 Type *ReqTy = Val->getType()->getVectorElementType();
1990 if (OnlyIfReducedTy == ReqTy)
1993 // Look up the constant in the table first to ensure uniqueness
1994 Constant *ArgVec[] = { Val, Idx };
1995 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
1997 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1998 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2001 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2002 Constant *Idx, Type *OnlyIfReducedTy) {
2003 assert(Val->getType()->isVectorTy() &&
2004 "Tried to create insertelement operation on non-vector type!");
2005 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
2006 "Insertelement types must match!");
2007 assert(Idx->getType()->isIntegerTy() &&
2008 "Insertelement index must be i32 type!");
2010 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2011 return FC; // Fold a few common cases.
2013 if (OnlyIfReducedTy == Val->getType())
2016 // Look up the constant in the table first to ensure uniqueness
2017 Constant *ArgVec[] = { Val, Elt, Idx };
2018 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2020 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2021 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2024 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2025 Constant *Mask, Type *OnlyIfReducedTy) {
2026 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2027 "Invalid shuffle vector constant expr operands!");
2029 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2030 return FC; // Fold a few common cases.
2032 unsigned NElts = Mask->getType()->getVectorNumElements();
2033 Type *EltTy = V1->getType()->getVectorElementType();
2034 Type *ShufTy = VectorType::get(EltTy, NElts);
2036 if (OnlyIfReducedTy == ShufTy)
2039 // Look up the constant in the table first to ensure uniqueness
2040 Constant *ArgVec[] = { V1, V2, Mask };
2041 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2043 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2044 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2047 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2048 ArrayRef<unsigned> Idxs,
2049 Type *OnlyIfReducedTy) {
2050 assert(Agg->getType()->isFirstClassType() &&
2051 "Non-first-class type for constant insertvalue expression");
2053 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2054 Idxs) == Val->getType() &&
2055 "insertvalue indices invalid!");
2056 Type *ReqTy = Val->getType();
2058 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2061 if (OnlyIfReducedTy == ReqTy)
2064 Constant *ArgVec[] = { Agg, Val };
2065 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2067 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2068 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2071 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2072 Type *OnlyIfReducedTy) {
2073 assert(Agg->getType()->isFirstClassType() &&
2074 "Tried to create extractelement operation on non-first-class type!");
2076 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2078 assert(ReqTy && "extractvalue indices invalid!");
2080 assert(Agg->getType()->isFirstClassType() &&
2081 "Non-first-class type for constant extractvalue expression");
2082 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2085 if (OnlyIfReducedTy == ReqTy)
2088 Constant *ArgVec[] = { Agg };
2089 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2091 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2092 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2095 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2096 assert(C->getType()->isIntOrIntVectorTy() &&
2097 "Cannot NEG a nonintegral value!");
2098 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2102 Constant *ConstantExpr::getFNeg(Constant *C) {
2103 assert(C->getType()->isFPOrFPVectorTy() &&
2104 "Cannot FNEG a non-floating-point value!");
2105 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2108 Constant *ConstantExpr::getNot(Constant *C) {
2109 assert(C->getType()->isIntOrIntVectorTy() &&
2110 "Cannot NOT a nonintegral value!");
2111 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2114 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2115 bool HasNUW, bool HasNSW) {
2116 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2117 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2118 return get(Instruction::Add, C1, C2, Flags);
2121 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2122 return get(Instruction::FAdd, C1, C2);
2125 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2126 bool HasNUW, bool HasNSW) {
2127 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2128 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2129 return get(Instruction::Sub, C1, C2, Flags);
2132 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2133 return get(Instruction::FSub, C1, C2);
2136 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2137 bool HasNUW, bool HasNSW) {
2138 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2139 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2140 return get(Instruction::Mul, C1, C2, Flags);
2143 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2144 return get(Instruction::FMul, C1, C2);
2147 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2148 return get(Instruction::UDiv, C1, C2,
2149 isExact ? PossiblyExactOperator::IsExact : 0);
2152 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2153 return get(Instruction::SDiv, C1, C2,
2154 isExact ? PossiblyExactOperator::IsExact : 0);
2157 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2158 return get(Instruction::FDiv, C1, C2);
2161 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2162 return get(Instruction::URem, C1, C2);
2165 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2166 return get(Instruction::SRem, C1, C2);
2169 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2170 return get(Instruction::FRem, C1, C2);
2173 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2174 return get(Instruction::And, C1, C2);
2177 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2178 return get(Instruction::Or, C1, C2);
2181 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2182 return get(Instruction::Xor, C1, C2);
2185 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2186 bool HasNUW, bool HasNSW) {
2187 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2188 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2189 return get(Instruction::Shl, C1, C2, Flags);
2192 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2193 return get(Instruction::LShr, C1, C2,
2194 isExact ? PossiblyExactOperator::IsExact : 0);
2197 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2198 return get(Instruction::AShr, C1, C2,
2199 isExact ? PossiblyExactOperator::IsExact : 0);
2202 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2205 // Doesn't have an identity.
2208 case Instruction::Add:
2209 case Instruction::Or:
2210 case Instruction::Xor:
2211 return Constant::getNullValue(Ty);
2213 case Instruction::Mul:
2214 return ConstantInt::get(Ty, 1);
2216 case Instruction::And:
2217 return Constant::getAllOnesValue(Ty);
2221 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2224 // Doesn't have an absorber.
2227 case Instruction::Or:
2228 return Constant::getAllOnesValue(Ty);
2230 case Instruction::And:
2231 case Instruction::Mul:
2232 return Constant::getNullValue(Ty);
2236 /// Remove the constant from the constant table.
2237 void ConstantExpr::destroyConstantImpl() {
2238 getType()->getContext().pImpl->ExprConstants.remove(this);
2241 const char *ConstantExpr::getOpcodeName() const {
2242 return Instruction::getOpcodeName(getOpcode());
2245 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2246 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2247 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2248 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2249 (IdxList.size() + 1),
2250 IdxList.size() + 1),
2251 SrcElementTy(SrcElementTy),
2252 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2254 Use *OperandList = getOperandList();
2255 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2256 OperandList[i+1] = IdxList[i];
2259 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2260 return SrcElementTy;
2263 Type *GetElementPtrConstantExpr::getResultElementType() const {
2264 return ResElementTy;
2267 //===----------------------------------------------------------------------===//
2268 // ConstantData* implementations
2270 Type *ConstantDataSequential::getElementType() const {
2271 return getType()->getElementType();
2274 StringRef ConstantDataSequential::getRawDataValues() const {
2275 return StringRef(DataElements, getNumElements()*getElementByteSize());
2278 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2279 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2280 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2281 switch (IT->getBitWidth()) {
2293 unsigned ConstantDataSequential::getNumElements() const {
2294 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2295 return AT->getNumElements();
2296 return getType()->getVectorNumElements();
2300 uint64_t ConstantDataSequential::getElementByteSize() const {
2301 return getElementType()->getPrimitiveSizeInBits()/8;
2304 /// Return the start of the specified element.
2305 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2306 assert(Elt < getNumElements() && "Invalid Elt");
2307 return DataElements+Elt*getElementByteSize();
2311 /// Return true if the array is empty or all zeros.
2312 static bool isAllZeros(StringRef Arr) {
2319 /// This is the underlying implementation of all of the
2320 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2321 /// the correct element type. We take the bytes in as a StringRef because
2322 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2323 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2324 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2325 // If the elements are all zero or there are no elements, return a CAZ, which
2326 // is more dense and canonical.
2327 if (isAllZeros(Elements))
2328 return ConstantAggregateZero::get(Ty);
2330 // Do a lookup to see if we have already formed one of these.
2333 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2336 // The bucket can point to a linked list of different CDS's that have the same
2337 // body but different types. For example, 0,0,0,1 could be a 4 element array
2338 // of i8, or a 1-element array of i32. They'll both end up in the same
2339 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2340 ConstantDataSequential **Entry = &Slot.second;
2341 for (ConstantDataSequential *Node = *Entry; Node;
2342 Entry = &Node->Next, Node = *Entry)
2343 if (Node->getType() == Ty)
2346 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2348 if (isa<ArrayType>(Ty))
2349 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2351 assert(isa<VectorType>(Ty));
2352 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2355 void ConstantDataSequential::destroyConstantImpl() {
2356 // Remove the constant from the StringMap.
2357 StringMap<ConstantDataSequential*> &CDSConstants =
2358 getType()->getContext().pImpl->CDSConstants;
2360 StringMap<ConstantDataSequential*>::iterator Slot =
2361 CDSConstants.find(getRawDataValues());
2363 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2365 ConstantDataSequential **Entry = &Slot->getValue();
2367 // Remove the entry from the hash table.
2368 if (!(*Entry)->Next) {
2369 // If there is only one value in the bucket (common case) it must be this
2370 // entry, and removing the entry should remove the bucket completely.
2371 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2372 getContext().pImpl->CDSConstants.erase(Slot);
2374 // Otherwise, there are multiple entries linked off the bucket, unlink the
2375 // node we care about but keep the bucket around.
2376 for (ConstantDataSequential *Node = *Entry; ;
2377 Entry = &Node->Next, Node = *Entry) {
2378 assert(Node && "Didn't find entry in its uniquing hash table!");
2379 // If we found our entry, unlink it from the list and we're done.
2381 *Entry = Node->Next;
2387 // If we were part of a list, make sure that we don't delete the list that is
2388 // still owned by the uniquing map.
2392 /// get() constructors - Return a constant with array type with an element
2393 /// count and element type matching the ArrayRef passed in. Note that this
2394 /// can return a ConstantAggregateZero object.
2395 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2396 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2397 const char *Data = reinterpret_cast<const char *>(Elts.data());
2398 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2400 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2401 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2402 const char *Data = reinterpret_cast<const char *>(Elts.data());
2403 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2405 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2406 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2407 const char *Data = reinterpret_cast<const char *>(Elts.data());
2408 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2410 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2411 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2412 const char *Data = reinterpret_cast<const char *>(Elts.data());
2413 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2415 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2416 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2417 const char *Data = reinterpret_cast<const char *>(Elts.data());
2418 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2420 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2421 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2422 const char *Data = reinterpret_cast<const char *>(Elts.data());
2423 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2426 /// getFP() constructors - Return a constant with array type with an element
2427 /// count and element type of float with precision matching the number of
2428 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2429 /// double for 64bits) Note that this can return a ConstantAggregateZero
2431 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2432 ArrayRef<uint16_t> Elts) {
2433 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
2434 const char *Data = reinterpret_cast<const char *>(Elts.data());
2435 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2437 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2438 ArrayRef<uint32_t> Elts) {
2439 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2440 const char *Data = reinterpret_cast<const char *>(Elts.data());
2441 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2443 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2444 ArrayRef<uint64_t> Elts) {
2445 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2446 const char *Data = reinterpret_cast<const char *>(Elts.data());
2447 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2450 Constant *ConstantDataArray::getString(LLVMContext &Context,
2451 StringRef Str, bool AddNull) {
2453 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2454 return get(Context, makeArrayRef(Data, Str.size()));
2457 SmallVector<uint8_t, 64> ElementVals;
2458 ElementVals.append(Str.begin(), Str.end());
2459 ElementVals.push_back(0);
2460 return get(Context, ElementVals);
2463 /// get() constructors - Return a constant with vector type with an element
2464 /// count and element type matching the ArrayRef passed in. Note that this
2465 /// can return a ConstantAggregateZero object.
2466 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2467 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2468 const char *Data = reinterpret_cast<const char *>(Elts.data());
2469 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
2471 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2472 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2473 const char *Data = reinterpret_cast<const char *>(Elts.data());
2474 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2476 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2477 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2478 const char *Data = reinterpret_cast<const char *>(Elts.data());
2479 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2481 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2482 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2483 const char *Data = reinterpret_cast<const char *>(Elts.data());
2484 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2486 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2487 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2488 const char *Data = reinterpret_cast<const char *>(Elts.data());
2489 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2491 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2492 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2493 const char *Data = reinterpret_cast<const char *>(Elts.data());
2494 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2497 /// getFP() constructors - Return a constant with vector type with an element
2498 /// count and element type of float with the precision matching the number of
2499 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2500 /// double for 64bits) Note that this can return a ConstantAggregateZero
2502 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2503 ArrayRef<uint16_t> Elts) {
2504 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2505 const char *Data = reinterpret_cast<const char *>(Elts.data());
2506 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2508 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2509 ArrayRef<uint32_t> Elts) {
2510 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2511 const char *Data = reinterpret_cast<const char *>(Elts.data());
2512 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2514 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2515 ArrayRef<uint64_t> Elts) {
2516 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2517 const char *Data = reinterpret_cast<const char *>(Elts.data());
2518 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2521 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2522 assert(isElementTypeCompatible(V->getType()) &&
2523 "Element type not compatible with ConstantData");
2524 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2525 if (CI->getType()->isIntegerTy(8)) {
2526 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2527 return get(V->getContext(), Elts);
2529 if (CI->getType()->isIntegerTy(16)) {
2530 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2531 return get(V->getContext(), Elts);
2533 if (CI->getType()->isIntegerTy(32)) {
2534 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2535 return get(V->getContext(), Elts);
2537 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2538 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2539 return get(V->getContext(), Elts);
2542 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2543 if (CFP->getType()->isHalfTy()) {
2544 SmallVector<uint16_t, 16> Elts(
2545 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2546 return getFP(V->getContext(), Elts);
2548 if (CFP->getType()->isFloatTy()) {
2549 SmallVector<uint32_t, 16> Elts(
2550 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2551 return getFP(V->getContext(), Elts);
2553 if (CFP->getType()->isDoubleTy()) {
2554 SmallVector<uint64_t, 16> Elts(
2555 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2556 return getFP(V->getContext(), Elts);
2559 return ConstantVector::getSplat(NumElts, V);
2563 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2564 assert(isa<IntegerType>(getElementType()) &&
2565 "Accessor can only be used when element is an integer");
2566 const char *EltPtr = getElementPointer(Elt);
2568 // The data is stored in host byte order, make sure to cast back to the right
2569 // type to load with the right endianness.
2570 switch (getElementType()->getIntegerBitWidth()) {
2571 default: llvm_unreachable("Invalid bitwidth for CDS");
2573 return *reinterpret_cast<const uint8_t *>(EltPtr);
2575 return *reinterpret_cast<const uint16_t *>(EltPtr);
2577 return *reinterpret_cast<const uint32_t *>(EltPtr);
2579 return *reinterpret_cast<const uint64_t *>(EltPtr);
2583 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
2584 assert(isa<IntegerType>(getElementType()) &&
2585 "Accessor can only be used when element is an integer");
2586 const char *EltPtr = getElementPointer(Elt);
2588 // The data is stored in host byte order, make sure to cast back to the right
2589 // type to load with the right endianness.
2590 switch (getElementType()->getIntegerBitWidth()) {
2591 default: llvm_unreachable("Invalid bitwidth for CDS");
2593 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
2594 return APInt(8, EltVal);
2597 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2598 return APInt(16, EltVal);
2601 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2602 return APInt(32, EltVal);
2605 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2606 return APInt(64, EltVal);
2611 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2612 const char *EltPtr = getElementPointer(Elt);
2614 switch (getElementType()->getTypeID()) {
2616 llvm_unreachable("Accessor can only be used when element is float/double!");
2617 case Type::HalfTyID: {
2618 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2619 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
2621 case Type::FloatTyID: {
2622 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2623 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
2625 case Type::DoubleTyID: {
2626 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2627 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
2632 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2633 assert(getElementType()->isFloatTy() &&
2634 "Accessor can only be used when element is a 'float'");
2635 return *reinterpret_cast<const float *>(getElementPointer(Elt));
2638 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2639 assert(getElementType()->isDoubleTy() &&
2640 "Accessor can only be used when element is a 'float'");
2641 return *reinterpret_cast<const double *>(getElementPointer(Elt));
2644 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2645 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2646 getElementType()->isDoubleTy())
2647 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2649 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2652 bool ConstantDataSequential::isString(unsigned CharSize) const {
2653 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
2656 bool ConstantDataSequential::isCString() const {
2660 StringRef Str = getAsString();
2662 // The last value must be nul.
2663 if (Str.back() != 0) return false;
2665 // Other elements must be non-nul.
2666 return Str.drop_back().find(0) == StringRef::npos;
2669 bool ConstantDataVector::isSplat() const {
2670 const char *Base = getRawDataValues().data();
2672 // Compare elements 1+ to the 0'th element.
2673 unsigned EltSize = getElementByteSize();
2674 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2675 if (memcmp(Base, Base+i*EltSize, EltSize))
2681 Constant *ConstantDataVector::getSplatValue() const {
2682 // If they're all the same, return the 0th one as a representative.
2683 return isSplat() ? getElementAsConstant(0) : nullptr;
2686 //===----------------------------------------------------------------------===//
2687 // handleOperandChange implementations
2689 /// Update this constant array to change uses of
2690 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2693 /// Note that we intentionally replace all uses of From with To here. Consider
2694 /// a large array that uses 'From' 1000 times. By handling this case all here,
2695 /// ConstantArray::handleOperandChange is only invoked once, and that
2696 /// single invocation handles all 1000 uses. Handling them one at a time would
2697 /// work, but would be really slow because it would have to unique each updated
2700 void Constant::handleOperandChange(Value *From, Value *To) {
2701 Value *Replacement = nullptr;
2702 switch (getValueID()) {
2704 llvm_unreachable("Not a constant!");
2705 #define HANDLE_CONSTANT(Name) \
2706 case Value::Name##Val: \
2707 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
2709 #include "llvm/IR/Value.def"
2712 // If handleOperandChangeImpl returned nullptr, then it handled
2713 // replacing itself and we don't want to delete or replace anything else here.
2717 // I do need to replace this with an existing value.
2718 assert(Replacement != this && "I didn't contain From!");
2720 // Everyone using this now uses the replacement.
2721 replaceAllUsesWith(Replacement);
2723 // Delete the old constant!
2727 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
2728 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2729 Constant *ToC = cast<Constant>(To);
2731 SmallVector<Constant*, 8> Values;
2732 Values.reserve(getNumOperands()); // Build replacement array.
2734 // Fill values with the modified operands of the constant array. Also,
2735 // compute whether this turns into an all-zeros array.
2736 unsigned NumUpdated = 0;
2738 // Keep track of whether all the values in the array are "ToC".
2739 bool AllSame = true;
2740 Use *OperandList = getOperandList();
2741 unsigned OperandNo = 0;
2742 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2743 Constant *Val = cast<Constant>(O->get());
2745 OperandNo = (O - OperandList);
2749 Values.push_back(Val);
2750 AllSame &= Val == ToC;
2753 if (AllSame && ToC->isNullValue())
2754 return ConstantAggregateZero::get(getType());
2756 if (AllSame && isa<UndefValue>(ToC))
2757 return UndefValue::get(getType());
2759 // Check for any other type of constant-folding.
2760 if (Constant *C = getImpl(getType(), Values))
2763 // Update to the new value.
2764 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2765 Values, this, From, ToC, NumUpdated, OperandNo);
2768 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
2769 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2770 Constant *ToC = cast<Constant>(To);
2772 Use *OperandList = getOperandList();
2774 SmallVector<Constant*, 8> Values;
2775 Values.reserve(getNumOperands()); // Build replacement struct.
2777 // Fill values with the modified operands of the constant struct. Also,
2778 // compute whether this turns into an all-zeros struct.
2779 unsigned NumUpdated = 0;
2780 bool AllSame = true;
2781 unsigned OperandNo = 0;
2782 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2783 Constant *Val = cast<Constant>(O->get());
2785 OperandNo = (O - OperandList);
2789 Values.push_back(Val);
2790 AllSame &= Val == ToC;
2793 if (AllSame && ToC->isNullValue())
2794 return ConstantAggregateZero::get(getType());
2796 if (AllSame && isa<UndefValue>(ToC))
2797 return UndefValue::get(getType());
2799 // Update to the new value.
2800 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
2801 Values, this, From, ToC, NumUpdated, OperandNo);
2804 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
2805 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2806 Constant *ToC = cast<Constant>(To);
2808 SmallVector<Constant*, 8> Values;
2809 Values.reserve(getNumOperands()); // Build replacement array...
2810 unsigned NumUpdated = 0;
2811 unsigned OperandNo = 0;
2812 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2813 Constant *Val = getOperand(i);
2819 Values.push_back(Val);
2822 if (Constant *C = getImpl(Values))
2825 // Update to the new value.
2826 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2827 Values, this, From, ToC, NumUpdated, OperandNo);
2830 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
2831 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2832 Constant *To = cast<Constant>(ToV);
2834 SmallVector<Constant*, 8> NewOps;
2835 unsigned NumUpdated = 0;
2836 unsigned OperandNo = 0;
2837 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2838 Constant *Op = getOperand(i);
2844 NewOps.push_back(Op);
2846 assert(NumUpdated && "I didn't contain From!");
2848 if (Constant *C = getWithOperands(NewOps, getType(), true))
2851 // Update to the new value.
2852 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2853 NewOps, this, From, To, NumUpdated, OperandNo);
2856 Instruction *ConstantExpr::getAsInstruction() {
2857 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
2858 ArrayRef<Value*> Ops(ValueOperands);
2860 switch (getOpcode()) {
2861 case Instruction::Trunc:
2862 case Instruction::ZExt:
2863 case Instruction::SExt:
2864 case Instruction::FPTrunc:
2865 case Instruction::FPExt:
2866 case Instruction::UIToFP:
2867 case Instruction::SIToFP:
2868 case Instruction::FPToUI:
2869 case Instruction::FPToSI:
2870 case Instruction::PtrToInt:
2871 case Instruction::IntToPtr:
2872 case Instruction::BitCast:
2873 case Instruction::AddrSpaceCast:
2874 return CastInst::Create((Instruction::CastOps)getOpcode(),
2876 case Instruction::Select:
2877 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2878 case Instruction::InsertElement:
2879 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2880 case Instruction::ExtractElement:
2881 return ExtractElementInst::Create(Ops[0], Ops[1]);
2882 case Instruction::InsertValue:
2883 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2884 case Instruction::ExtractValue:
2885 return ExtractValueInst::Create(Ops[0], getIndices());
2886 case Instruction::ShuffleVector:
2887 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2889 case Instruction::GetElementPtr: {
2890 const auto *GO = cast<GEPOperator>(this);
2891 if (GO->isInBounds())
2892 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
2893 Ops[0], Ops.slice(1));
2894 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
2897 case Instruction::ICmp:
2898 case Instruction::FCmp:
2899 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2900 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
2903 assert(getNumOperands() == 2 && "Must be binary operator?");
2904 BinaryOperator *BO =
2905 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2907 if (isa<OverflowingBinaryOperator>(BO)) {
2908 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2909 OverflowingBinaryOperator::NoUnsignedWrap);
2910 BO->setHasNoSignedWrap(SubclassOptionalData &
2911 OverflowingBinaryOperator::NoSignedWrap);
2913 if (isa<PossiblyExactOperator>(BO))
2914 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);