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/StringExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/GlobalValue.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/raw_ostream.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 bool Constant::isNegativeZeroValue() const {
41 // Floating point values have an explicit -0.0 value.
42 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
43 return CFP->isZero() && CFP->isNegative();
45 // Equivalent for a vector of -0.0's.
46 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
47 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
48 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
51 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
52 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
53 if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
56 // We've already handled true FP case; any other FP vectors can't represent -0.0.
57 if (getType()->isFPOrFPVectorTy())
60 // Otherwise, just use +0.0.
64 // Return true iff this constant is positive zero (floating point), negative
65 // zero (floating point), or a null value.
66 bool Constant::isZeroValue() const {
67 // Floating point values have an explicit -0.0 value.
68 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
71 // Equivalent for a vector of -0.0's.
72 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
73 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
74 if (SplatCFP && SplatCFP->isZero())
77 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
78 if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
79 if (SplatCFP && SplatCFP->isZero())
82 // Otherwise, just use +0.0.
86 bool Constant::isNullValue() const {
88 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
92 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
93 return CFP->isZero() && !CFP->isNegative();
95 // constant zero is zero for aggregates, cpnull is null for pointers, none for
97 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
98 isa<ConstantTokenNone>(this);
101 bool Constant::isAllOnesValue() const {
102 // Check for -1 integers
103 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
104 return CI->isMinusOne();
106 // Check for FP which are bitcasted from -1 integers
107 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
108 return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
110 // Check for constant vectors which are splats of -1 values.
111 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
112 if (Constant *Splat = CV->getSplatValue())
113 return Splat->isAllOnesValue();
115 // Check for constant vectors which are splats of -1 values.
116 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
117 if (Constant *Splat = CV->getSplatValue())
118 return Splat->isAllOnesValue();
123 bool Constant::isOneValue() const {
124 // Check for 1 integers
125 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
128 // Check for FP which are bitcasted from 1 integers
129 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
130 return CFP->getValueAPF().bitcastToAPInt() == 1;
132 // Check for constant vectors which are splats of 1 values.
133 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
134 if (Constant *Splat = CV->getSplatValue())
135 return Splat->isOneValue();
137 // Check for constant vectors which are splats of 1 values.
138 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
139 if (Constant *Splat = CV->getSplatValue())
140 return Splat->isOneValue();
145 bool Constant::isMinSignedValue() const {
146 // Check for INT_MIN integers
147 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
148 return CI->isMinValue(/*isSigned=*/true);
150 // Check for FP which are bitcasted from INT_MIN integers
151 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
152 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
154 // Check for constant vectors which are splats of INT_MIN values.
155 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
156 if (Constant *Splat = CV->getSplatValue())
157 return Splat->isMinSignedValue();
159 // Check for constant vectors which are splats of INT_MIN values.
160 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
161 if (Constant *Splat = CV->getSplatValue())
162 return Splat->isMinSignedValue();
167 bool Constant::isNotMinSignedValue() const {
168 // Check for INT_MIN integers
169 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
170 return !CI->isMinValue(/*isSigned=*/true);
172 // Check for FP which are bitcasted from INT_MIN integers
173 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
174 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
176 // Check for constant vectors which are splats of INT_MIN values.
177 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
178 if (Constant *Splat = CV->getSplatValue())
179 return Splat->isNotMinSignedValue();
181 // Check for constant vectors which are splats of INT_MIN values.
182 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
183 if (Constant *Splat = CV->getSplatValue())
184 return Splat->isNotMinSignedValue();
186 // It *may* contain INT_MIN, we can't tell.
190 /// Constructor to create a '0' constant of arbitrary type.
191 Constant *Constant::getNullValue(Type *Ty) {
192 switch (Ty->getTypeID()) {
193 case Type::IntegerTyID:
194 return ConstantInt::get(Ty, 0);
196 return ConstantFP::get(Ty->getContext(),
197 APFloat::getZero(APFloat::IEEEhalf()));
198 case Type::FloatTyID:
199 return ConstantFP::get(Ty->getContext(),
200 APFloat::getZero(APFloat::IEEEsingle()));
201 case Type::DoubleTyID:
202 return ConstantFP::get(Ty->getContext(),
203 APFloat::getZero(APFloat::IEEEdouble()));
204 case Type::X86_FP80TyID:
205 return ConstantFP::get(Ty->getContext(),
206 APFloat::getZero(APFloat::x87DoubleExtended()));
207 case Type::FP128TyID:
208 return ConstantFP::get(Ty->getContext(),
209 APFloat::getZero(APFloat::IEEEquad()));
210 case Type::PPC_FP128TyID:
211 return ConstantFP::get(Ty->getContext(),
212 APFloat(APFloat::PPCDoubleDouble(),
213 APInt::getNullValue(128)));
214 case Type::PointerTyID:
215 return ConstantPointerNull::get(cast<PointerType>(Ty));
216 case Type::StructTyID:
217 case Type::ArrayTyID:
218 case Type::VectorTyID:
219 return ConstantAggregateZero::get(Ty);
220 case Type::TokenTyID:
221 return ConstantTokenNone::get(Ty->getContext());
223 // Function, Label, or Opaque type?
224 llvm_unreachable("Cannot create a null constant of that type!");
228 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
229 Type *ScalarTy = Ty->getScalarType();
231 // Create the base integer constant.
232 Constant *C = ConstantInt::get(Ty->getContext(), V);
234 // Convert an integer to a pointer, if necessary.
235 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
236 C = ConstantExpr::getIntToPtr(C, PTy);
238 // Broadcast a scalar to a vector, if necessary.
239 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
240 C = ConstantVector::getSplat(VTy->getNumElements(), C);
245 Constant *Constant::getAllOnesValue(Type *Ty) {
246 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
247 return ConstantInt::get(Ty->getContext(),
248 APInt::getAllOnesValue(ITy->getBitWidth()));
250 if (Ty->isFloatingPointTy()) {
251 APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
252 !Ty->isPPC_FP128Ty());
253 return ConstantFP::get(Ty->getContext(), FL);
256 VectorType *VTy = cast<VectorType>(Ty);
257 return ConstantVector::getSplat(VTy->getNumElements(),
258 getAllOnesValue(VTy->getElementType()));
261 Constant *Constant::getAggregateElement(unsigned Elt) const {
262 if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
263 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
265 if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
266 return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
268 if (const UndefValue *UV = dyn_cast<UndefValue>(this))
269 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
271 if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
272 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
277 Constant *Constant::getAggregateElement(Constant *Elt) const {
278 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
279 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
280 return getAggregateElement(CI->getZExtValue());
284 void Constant::destroyConstant() {
285 /// First call destroyConstantImpl on the subclass. This gives the subclass
286 /// a chance to remove the constant from any maps/pools it's contained in.
287 switch (getValueID()) {
289 llvm_unreachable("Not a constant!");
290 #define HANDLE_CONSTANT(Name) \
291 case Value::Name##Val: \
292 cast<Name>(this)->destroyConstantImpl(); \
294 #include "llvm/IR/Value.def"
297 // When a Constant is destroyed, there may be lingering
298 // references to the constant by other constants in the constant pool. These
299 // constants are implicitly dependent on the module that is being deleted,
300 // but they don't know that. Because we only find out when the CPV is
301 // deleted, we must now notify all of our users (that should only be
302 // Constants) that they are, in fact, invalid now and should be deleted.
304 while (!use_empty()) {
305 Value *V = user_back();
306 #ifndef NDEBUG // Only in -g mode...
307 if (!isa<Constant>(V)) {
308 dbgs() << "While deleting: " << *this
309 << "\n\nUse still stuck around after Def is destroyed: " << *V
313 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
314 cast<Constant>(V)->destroyConstant();
316 // The constant should remove itself from our use list...
317 assert((use_empty() || user_back() != V) && "Constant not removed!");
320 // Value has no outstanding references it is safe to delete it now...
324 static bool canTrapImpl(const Constant *C,
325 SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
326 assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
327 // The only thing that could possibly trap are constant exprs.
328 const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
332 // ConstantExpr traps if any operands can trap.
333 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
334 if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
335 if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
340 // Otherwise, only specific operations can trap.
341 switch (CE->getOpcode()) {
344 case Instruction::UDiv:
345 case Instruction::SDiv:
346 case Instruction::URem:
347 case Instruction::SRem:
348 // Div and rem can trap if the RHS is not known to be non-zero.
349 if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
355 bool Constant::canTrap() const {
356 SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
357 return canTrapImpl(this, NonTrappingOps);
360 /// Check if C contains a GlobalValue for which Predicate is true.
362 ConstHasGlobalValuePredicate(const Constant *C,
363 bool (*Predicate)(const GlobalValue *)) {
364 SmallPtrSet<const Constant *, 8> Visited;
365 SmallVector<const Constant *, 8> WorkList;
366 WorkList.push_back(C);
369 while (!WorkList.empty()) {
370 const Constant *WorkItem = WorkList.pop_back_val();
371 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
374 for (const Value *Op : WorkItem->operands()) {
375 const Constant *ConstOp = dyn_cast<Constant>(Op);
378 if (Visited.insert(ConstOp).second)
379 WorkList.push_back(ConstOp);
385 bool Constant::isThreadDependent() const {
386 auto DLLImportPredicate = [](const GlobalValue *GV) {
387 return GV->isThreadLocal();
389 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
392 bool Constant::isDLLImportDependent() const {
393 auto DLLImportPredicate = [](const GlobalValue *GV) {
394 return GV->hasDLLImportStorageClass();
396 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
399 bool Constant::isConstantUsed() const {
400 for (const User *U : users()) {
401 const Constant *UC = dyn_cast<Constant>(U);
402 if (!UC || isa<GlobalValue>(UC))
405 if (UC->isConstantUsed())
411 bool Constant::needsRelocation() const {
412 if (isa<GlobalValue>(this))
413 return true; // Global reference.
415 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
416 return BA->getFunction()->needsRelocation();
418 // While raw uses of blockaddress need to be relocated, differences between
419 // two of them don't when they are for labels in the same function. This is a
420 // common idiom when creating a table for the indirect goto extension, so we
421 // handle it efficiently here.
422 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
423 if (CE->getOpcode() == Instruction::Sub) {
424 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
425 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
426 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
427 RHS->getOpcode() == Instruction::PtrToInt &&
428 isa<BlockAddress>(LHS->getOperand(0)) &&
429 isa<BlockAddress>(RHS->getOperand(0)) &&
430 cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
431 cast<BlockAddress>(RHS->getOperand(0))->getFunction())
436 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
437 Result |= cast<Constant>(getOperand(i))->needsRelocation();
442 /// If the specified constantexpr is dead, remove it. This involves recursively
443 /// eliminating any dead users of the constantexpr.
444 static bool removeDeadUsersOfConstant(const Constant *C) {
445 if (isa<GlobalValue>(C)) return false; // Cannot remove this
447 while (!C->use_empty()) {
448 const Constant *User = dyn_cast<Constant>(C->user_back());
449 if (!User) return false; // Non-constant usage;
450 if (!removeDeadUsersOfConstant(User))
451 return false; // Constant wasn't dead
454 const_cast<Constant*>(C)->destroyConstant();
459 void Constant::removeDeadConstantUsers() const {
460 Value::const_user_iterator I = user_begin(), E = user_end();
461 Value::const_user_iterator LastNonDeadUser = E;
463 const Constant *User = dyn_cast<Constant>(*I);
470 if (!removeDeadUsersOfConstant(User)) {
471 // If the constant wasn't dead, remember that this was the last live use
472 // and move on to the next constant.
478 // If the constant was dead, then the iterator is invalidated.
479 if (LastNonDeadUser == E) {
491 //===----------------------------------------------------------------------===//
493 //===----------------------------------------------------------------------===//
495 ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
496 : ConstantData(Ty, ConstantIntVal), Val(V) {
497 assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
500 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
501 LLVMContextImpl *pImpl = Context.pImpl;
502 if (!pImpl->TheTrueVal)
503 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
504 return pImpl->TheTrueVal;
507 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
508 LLVMContextImpl *pImpl = Context.pImpl;
509 if (!pImpl->TheFalseVal)
510 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
511 return pImpl->TheFalseVal;
514 Constant *ConstantInt::getTrue(Type *Ty) {
515 assert(Ty->getScalarType()->isIntegerTy(1) && "Type not i1 or vector of i1.");
516 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
517 if (auto *VTy = dyn_cast<VectorType>(Ty))
518 return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
522 Constant *ConstantInt::getFalse(Type *Ty) {
523 assert(Ty->getScalarType()->isIntegerTy(1) && "Type not i1 or vector of i1.");
524 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
525 if (auto *VTy = dyn_cast<VectorType>(Ty))
526 return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
530 // Get a ConstantInt from an APInt.
531 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
532 // get an existing value or the insertion position
533 LLVMContextImpl *pImpl = Context.pImpl;
534 std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
536 // Get the corresponding integer type for the bit width of the value.
537 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
538 Slot.reset(new ConstantInt(ITy, V));
540 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
544 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
545 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
547 // For vectors, broadcast the value.
548 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
549 return ConstantVector::getSplat(VTy->getNumElements(), C);
554 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
555 return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
558 ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
559 return get(Ty, V, true);
562 Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
563 return get(Ty, V, true);
566 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
567 ConstantInt *C = get(Ty->getContext(), V);
568 assert(C->getType() == Ty->getScalarType() &&
569 "ConstantInt type doesn't match the type implied by its value!");
571 // For vectors, broadcast the value.
572 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
573 return ConstantVector::getSplat(VTy->getNumElements(), C);
578 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
579 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
582 /// Remove the constant from the constant table.
583 void ConstantInt::destroyConstantImpl() {
584 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
587 //===----------------------------------------------------------------------===//
589 //===----------------------------------------------------------------------===//
591 static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
593 return &APFloat::IEEEhalf();
595 return &APFloat::IEEEsingle();
596 if (Ty->isDoubleTy())
597 return &APFloat::IEEEdouble();
598 if (Ty->isX86_FP80Ty())
599 return &APFloat::x87DoubleExtended();
600 else if (Ty->isFP128Ty())
601 return &APFloat::IEEEquad();
603 assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
604 return &APFloat::PPCDoubleDouble();
607 Constant *ConstantFP::get(Type *Ty, double V) {
608 LLVMContext &Context = Ty->getContext();
612 FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
613 APFloat::rmNearestTiesToEven, &ignored);
614 Constant *C = get(Context, FV);
616 // For vectors, broadcast the value.
617 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
618 return ConstantVector::getSplat(VTy->getNumElements(), C);
624 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
625 LLVMContext &Context = Ty->getContext();
627 APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
628 Constant *C = get(Context, FV);
630 // For vectors, broadcast the value.
631 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
632 return ConstantVector::getSplat(VTy->getNumElements(), C);
637 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
638 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
639 APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
640 Constant *C = get(Ty->getContext(), NaN);
642 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
643 return ConstantVector::getSplat(VTy->getNumElements(), C);
648 Constant *ConstantFP::getNegativeZero(Type *Ty) {
649 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
650 APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
651 Constant *C = get(Ty->getContext(), NegZero);
653 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
654 return ConstantVector::getSplat(VTy->getNumElements(), C);
660 Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
661 if (Ty->isFPOrFPVectorTy())
662 return getNegativeZero(Ty);
664 return Constant::getNullValue(Ty);
668 // ConstantFP accessors.
669 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
670 LLVMContextImpl* pImpl = Context.pImpl;
672 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
676 if (&V.getSemantics() == &APFloat::IEEEhalf())
677 Ty = Type::getHalfTy(Context);
678 else if (&V.getSemantics() == &APFloat::IEEEsingle())
679 Ty = Type::getFloatTy(Context);
680 else if (&V.getSemantics() == &APFloat::IEEEdouble())
681 Ty = Type::getDoubleTy(Context);
682 else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
683 Ty = Type::getX86_FP80Ty(Context);
684 else if (&V.getSemantics() == &APFloat::IEEEquad())
685 Ty = Type::getFP128Ty(Context);
687 assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
688 "Unknown FP format");
689 Ty = Type::getPPC_FP128Ty(Context);
691 Slot.reset(new ConstantFP(Ty, V));
697 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
698 const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
699 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
701 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
702 return ConstantVector::getSplat(VTy->getNumElements(), C);
707 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
708 : ConstantData(Ty, ConstantFPVal), Val(V) {
709 assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
713 bool ConstantFP::isExactlyValue(const APFloat &V) const {
714 return Val.bitwiseIsEqual(V);
717 /// Remove the constant from the constant table.
718 void ConstantFP::destroyConstantImpl() {
719 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
722 //===----------------------------------------------------------------------===//
723 // ConstantAggregateZero Implementation
724 //===----------------------------------------------------------------------===//
726 Constant *ConstantAggregateZero::getSequentialElement() const {
727 return Constant::getNullValue(getType()->getSequentialElementType());
730 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
731 return Constant::getNullValue(getType()->getStructElementType(Elt));
734 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
735 if (isa<SequentialType>(getType()))
736 return getSequentialElement();
737 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
740 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
741 if (isa<SequentialType>(getType()))
742 return getSequentialElement();
743 return getStructElement(Idx);
746 unsigned ConstantAggregateZero::getNumElements() const {
747 Type *Ty = getType();
748 if (auto *AT = dyn_cast<ArrayType>(Ty))
749 return AT->getNumElements();
750 if (auto *VT = dyn_cast<VectorType>(Ty))
751 return VT->getNumElements();
752 return Ty->getStructNumElements();
755 //===----------------------------------------------------------------------===//
756 // UndefValue Implementation
757 //===----------------------------------------------------------------------===//
759 UndefValue *UndefValue::getSequentialElement() const {
760 return UndefValue::get(getType()->getSequentialElementType());
763 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
764 return UndefValue::get(getType()->getStructElementType(Elt));
767 UndefValue *UndefValue::getElementValue(Constant *C) const {
768 if (isa<SequentialType>(getType()))
769 return getSequentialElement();
770 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
773 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
774 if (isa<SequentialType>(getType()))
775 return getSequentialElement();
776 return getStructElement(Idx);
779 unsigned UndefValue::getNumElements() const {
780 Type *Ty = getType();
781 if (auto *ST = dyn_cast<SequentialType>(Ty))
782 return ST->getNumElements();
783 return Ty->getStructNumElements();
786 //===----------------------------------------------------------------------===//
787 // ConstantXXX Classes
788 //===----------------------------------------------------------------------===//
790 template <typename ItTy, typename EltTy>
791 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
792 for (; Start != End; ++Start)
798 template <typename SequentialTy, typename ElementTy>
799 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
800 assert(!V.empty() && "Cannot get empty int sequence.");
802 SmallVector<ElementTy, 16> Elts;
803 for (Constant *C : V)
804 if (auto *CI = dyn_cast<ConstantInt>(C))
805 Elts.push_back(CI->getZExtValue());
808 return SequentialTy::get(V[0]->getContext(), Elts);
811 template <typename SequentialTy, typename ElementTy>
812 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
813 assert(!V.empty() && "Cannot get empty FP sequence.");
815 SmallVector<ElementTy, 16> Elts;
816 for (Constant *C : V)
817 if (auto *CFP = dyn_cast<ConstantFP>(C))
818 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
821 return SequentialTy::getFP(V[0]->getContext(), Elts);
824 template <typename SequenceTy>
825 static Constant *getSequenceIfElementsMatch(Constant *C,
826 ArrayRef<Constant *> V) {
827 // We speculatively build the elements here even if it turns out that there is
828 // a constantexpr or something else weird, since it is so uncommon for that to
830 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
831 if (CI->getType()->isIntegerTy(8))
832 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
833 else if (CI->getType()->isIntegerTy(16))
834 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
835 else if (CI->getType()->isIntegerTy(32))
836 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
837 else if (CI->getType()->isIntegerTy(64))
838 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
839 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
840 if (CFP->getType()->isHalfTy())
841 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
842 else if (CFP->getType()->isFloatTy())
843 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
844 else if (CFP->getType()->isDoubleTy())
845 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
851 ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
852 ArrayRef<Constant *> V)
853 : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
855 std::copy(V.begin(), V.end(), op_begin());
857 // Check that types match, unless this is an opaque struct.
858 if (auto *ST = dyn_cast<StructType>(T))
861 for (unsigned I = 0, E = V.size(); I != E; ++I)
862 assert(V[I]->getType() == T->getTypeAtIndex(I) &&
863 "Initializer for composite element doesn't match!");
866 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
867 : ConstantAggregate(T, ConstantArrayVal, V) {
868 assert(V.size() == T->getNumElements() &&
869 "Invalid initializer for constant array");
872 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
873 if (Constant *C = getImpl(Ty, V))
875 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
878 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
879 // Empty arrays are canonicalized to ConstantAggregateZero.
881 return ConstantAggregateZero::get(Ty);
883 for (unsigned i = 0, e = V.size(); i != e; ++i) {
884 assert(V[i]->getType() == Ty->getElementType() &&
885 "Wrong type in array element initializer");
888 // If this is an all-zero array, return a ConstantAggregateZero object. If
889 // all undef, return an UndefValue, if "all simple", then return a
890 // ConstantDataArray.
892 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
893 return UndefValue::get(Ty);
895 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
896 return ConstantAggregateZero::get(Ty);
898 // Check to see if all of the elements are ConstantFP or ConstantInt and if
899 // the element type is compatible with ConstantDataVector. If so, use it.
900 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
901 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
903 // Otherwise, we really do want to create a ConstantArray.
907 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
908 ArrayRef<Constant*> V,
910 unsigned VecSize = V.size();
911 SmallVector<Type*, 16> EltTypes(VecSize);
912 for (unsigned i = 0; i != VecSize; ++i)
913 EltTypes[i] = V[i]->getType();
915 return StructType::get(Context, EltTypes, Packed);
919 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
922 "ConstantStruct::getTypeForElements cannot be called on empty list");
923 return getTypeForElements(V[0]->getContext(), V, Packed);
926 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
927 : ConstantAggregate(T, ConstantStructVal, V) {
928 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
929 "Invalid initializer for constant struct");
932 // ConstantStruct accessors.
933 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
934 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
935 "Incorrect # elements specified to ConstantStruct::get");
937 // Create a ConstantAggregateZero value if all elements are zeros.
939 bool isUndef = false;
942 isUndef = isa<UndefValue>(V[0]);
943 isZero = V[0]->isNullValue();
944 if (isUndef || isZero) {
945 for (unsigned i = 0, e = V.size(); i != e; ++i) {
946 if (!V[i]->isNullValue())
948 if (!isa<UndefValue>(V[i]))
954 return ConstantAggregateZero::get(ST);
956 return UndefValue::get(ST);
958 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
961 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
962 : ConstantAggregate(T, ConstantVectorVal, V) {
963 assert(V.size() == T->getNumElements() &&
964 "Invalid initializer for constant vector");
967 // ConstantVector accessors.
968 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
969 if (Constant *C = getImpl(V))
971 VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
972 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
975 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
976 assert(!V.empty() && "Vectors can't be empty");
977 VectorType *T = VectorType::get(V.front()->getType(), V.size());
979 // If this is an all-undef or all-zero vector, return a
980 // ConstantAggregateZero or UndefValue.
982 bool isZero = C->isNullValue();
983 bool isUndef = isa<UndefValue>(C);
985 if (isZero || isUndef) {
986 for (unsigned i = 1, e = V.size(); i != e; ++i)
988 isZero = isUndef = false;
994 return ConstantAggregateZero::get(T);
996 return UndefValue::get(T);
998 // Check to see if all of the elements are ConstantFP or ConstantInt and if
999 // the element type is compatible with ConstantDataVector. If so, use it.
1000 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1001 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1003 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1004 // the operand list contains a ConstantExpr or something else strange.
1008 Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
1009 // If this splat is compatible with ConstantDataVector, use it instead of
1011 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1012 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1013 return ConstantDataVector::getSplat(NumElts, V);
1015 SmallVector<Constant*, 32> Elts(NumElts, V);
1019 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1020 LLVMContextImpl *pImpl = Context.pImpl;
1021 if (!pImpl->TheNoneToken)
1022 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1023 return pImpl->TheNoneToken.get();
1026 /// Remove the constant from the constant table.
1027 void ConstantTokenNone::destroyConstantImpl() {
1028 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1031 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1032 // can't be inline because we don't want to #include Instruction.h into
1034 bool ConstantExpr::isCast() const {
1035 return Instruction::isCast(getOpcode());
1038 bool ConstantExpr::isCompare() const {
1039 return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
1042 bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
1043 if (getOpcode() != Instruction::GetElementPtr) return false;
1045 gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
1046 User::const_op_iterator OI = std::next(this->op_begin());
1048 // The remaining indices may be compile-time known integers within the bounds
1049 // of the corresponding notional static array types.
1050 for (; GEPI != E; ++GEPI, ++OI) {
1051 if (isa<UndefValue>(*OI))
1053 auto *CI = dyn_cast<ConstantInt>(*OI);
1054 if (!CI || (GEPI.isBoundedSequential() &&
1055 (CI->getValue().getActiveBits() > 64 ||
1056 CI->getZExtValue() >= GEPI.getSequentialNumElements())))
1060 // All the indices checked out.
1064 bool ConstantExpr::hasIndices() const {
1065 return getOpcode() == Instruction::ExtractValue ||
1066 getOpcode() == Instruction::InsertValue;
1069 ArrayRef<unsigned> ConstantExpr::getIndices() const {
1070 if (const ExtractValueConstantExpr *EVCE =
1071 dyn_cast<ExtractValueConstantExpr>(this))
1072 return EVCE->Indices;
1074 return cast<InsertValueConstantExpr>(this)->Indices;
1077 unsigned ConstantExpr::getPredicate() const {
1078 return cast<CompareConstantExpr>(this)->predicate;
1082 ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
1083 assert(Op->getType() == getOperand(OpNo)->getType() &&
1084 "Replacing operand with value of different type!");
1085 if (getOperand(OpNo) == Op)
1086 return const_cast<ConstantExpr*>(this);
1088 SmallVector<Constant*, 8> NewOps;
1089 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1090 NewOps.push_back(i == OpNo ? Op : getOperand(i));
1092 return getWithOperands(NewOps);
1095 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1096 bool OnlyIfReduced, Type *SrcTy) const {
1097 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1099 // If no operands changed return self.
1100 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1101 return const_cast<ConstantExpr*>(this);
1103 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1104 switch (getOpcode()) {
1105 case Instruction::Trunc:
1106 case Instruction::ZExt:
1107 case Instruction::SExt:
1108 case Instruction::FPTrunc:
1109 case Instruction::FPExt:
1110 case Instruction::UIToFP:
1111 case Instruction::SIToFP:
1112 case Instruction::FPToUI:
1113 case Instruction::FPToSI:
1114 case Instruction::PtrToInt:
1115 case Instruction::IntToPtr:
1116 case Instruction::BitCast:
1117 case Instruction::AddrSpaceCast:
1118 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1119 case Instruction::Select:
1120 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
1121 case Instruction::InsertElement:
1122 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1124 case Instruction::ExtractElement:
1125 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1126 case Instruction::InsertValue:
1127 return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
1129 case Instruction::ExtractValue:
1130 return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
1131 case Instruction::ShuffleVector:
1132 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
1134 case Instruction::GetElementPtr: {
1135 auto *GEPO = cast<GEPOperator>(this);
1136 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1137 return ConstantExpr::getGetElementPtr(
1138 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1139 GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
1141 case Instruction::ICmp:
1142 case Instruction::FCmp:
1143 return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
1146 assert(getNumOperands() == 2 && "Must be binary operator?");
1147 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1153 //===----------------------------------------------------------------------===//
1154 // isValueValidForType implementations
1156 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1157 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1158 if (Ty->isIntegerTy(1))
1159 return Val == 0 || Val == 1;
1161 return true; // always true, has to fit in largest type
1162 uint64_t Max = (1ll << NumBits) - 1;
1166 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1167 unsigned NumBits = Ty->getIntegerBitWidth();
1168 if (Ty->isIntegerTy(1))
1169 return Val == 0 || Val == 1 || Val == -1;
1171 return true; // always true, has to fit in largest type
1172 int64_t Min = -(1ll << (NumBits-1));
1173 int64_t Max = (1ll << (NumBits-1)) - 1;
1174 return (Val >= Min && Val <= Max);
1177 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1178 // convert modifies in place, so make a copy.
1179 APFloat Val2 = APFloat(Val);
1181 switch (Ty->getTypeID()) {
1183 return false; // These can't be represented as floating point!
1185 // FIXME rounding mode needs to be more flexible
1186 case Type::HalfTyID: {
1187 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1189 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1192 case Type::FloatTyID: {
1193 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1195 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1198 case Type::DoubleTyID: {
1199 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1200 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1201 &Val2.getSemantics() == &APFloat::IEEEdouble())
1203 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1206 case Type::X86_FP80TyID:
1207 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1208 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1209 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1210 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1211 case Type::FP128TyID:
1212 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1213 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1214 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1215 &Val2.getSemantics() == &APFloat::IEEEquad();
1216 case Type::PPC_FP128TyID:
1217 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1218 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1219 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1220 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1225 //===----------------------------------------------------------------------===//
1226 // Factory Function Implementation
1228 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1229 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1230 "Cannot create an aggregate zero of non-aggregate type!");
1232 std::unique_ptr<ConstantAggregateZero> &Entry =
1233 Ty->getContext().pImpl->CAZConstants[Ty];
1235 Entry.reset(new ConstantAggregateZero(Ty));
1240 /// Remove the constant from the constant table.
1241 void ConstantAggregateZero::destroyConstantImpl() {
1242 getContext().pImpl->CAZConstants.erase(getType());
1245 /// Remove the constant from the constant table.
1246 void ConstantArray::destroyConstantImpl() {
1247 getType()->getContext().pImpl->ArrayConstants.remove(this);
1251 //---- ConstantStruct::get() implementation...
1254 /// Remove the constant from the constant table.
1255 void ConstantStruct::destroyConstantImpl() {
1256 getType()->getContext().pImpl->StructConstants.remove(this);
1259 /// Remove the constant from the constant table.
1260 void ConstantVector::destroyConstantImpl() {
1261 getType()->getContext().pImpl->VectorConstants.remove(this);
1264 Constant *Constant::getSplatValue() const {
1265 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1266 if (isa<ConstantAggregateZero>(this))
1267 return getNullValue(this->getType()->getVectorElementType());
1268 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1269 return CV->getSplatValue();
1270 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1271 return CV->getSplatValue();
1275 Constant *ConstantVector::getSplatValue() const {
1276 // Check out first element.
1277 Constant *Elt = getOperand(0);
1278 // Then make sure all remaining elements point to the same value.
1279 for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
1280 if (getOperand(I) != Elt)
1285 const APInt &Constant::getUniqueInteger() const {
1286 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1287 return CI->getValue();
1288 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1289 const Constant *C = this->getAggregateElement(0U);
1290 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1291 return cast<ConstantInt>(C)->getValue();
1294 //---- ConstantPointerNull::get() implementation.
1297 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1298 std::unique_ptr<ConstantPointerNull> &Entry =
1299 Ty->getContext().pImpl->CPNConstants[Ty];
1301 Entry.reset(new ConstantPointerNull(Ty));
1306 /// Remove the constant from the constant table.
1307 void ConstantPointerNull::destroyConstantImpl() {
1308 getContext().pImpl->CPNConstants.erase(getType());
1311 UndefValue *UndefValue::get(Type *Ty) {
1312 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1314 Entry.reset(new UndefValue(Ty));
1319 /// Remove the constant from the constant table.
1320 void UndefValue::destroyConstantImpl() {
1321 // Free the constant and any dangling references to it.
1322 getContext().pImpl->UVConstants.erase(getType());
1325 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1326 assert(BB->getParent() && "Block must have a parent");
1327 return get(BB->getParent(), BB);
1330 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1332 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1334 BA = new BlockAddress(F, BB);
1336 assert(BA->getFunction() == F && "Basic block moved between functions");
1340 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1341 : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
1345 BB->AdjustBlockAddressRefCount(1);
1348 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1349 if (!BB->hasAddressTaken())
1352 const Function *F = BB->getParent();
1353 assert(F && "Block must have a parent");
1355 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1356 assert(BA && "Refcount and block address map disagree!");
1360 /// Remove the constant from the constant table.
1361 void BlockAddress::destroyConstantImpl() {
1362 getFunction()->getType()->getContext().pImpl
1363 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1364 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1367 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1368 // This could be replacing either the Basic Block or the Function. In either
1369 // case, we have to remove the map entry.
1370 Function *NewF = getFunction();
1371 BasicBlock *NewBB = getBasicBlock();
1374 NewF = cast<Function>(To->stripPointerCasts());
1376 assert(From == NewBB && "From does not match any operand");
1377 NewBB = cast<BasicBlock>(To);
1380 // See if the 'new' entry already exists, if not, just update this in place
1381 // and return early.
1382 BlockAddress *&NewBA =
1383 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1387 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1389 // Remove the old entry, this can't cause the map to rehash (just a
1390 // tombstone will get added).
1391 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1394 setOperand(0, NewF);
1395 setOperand(1, NewBB);
1396 getBasicBlock()->AdjustBlockAddressRefCount(1);
1398 // If we just want to keep the existing value, then return null.
1399 // Callers know that this means we shouldn't delete this value.
1403 //---- ConstantExpr::get() implementations.
1406 /// This is a utility function to handle folding of casts and lookup of the
1407 /// cast in the ExprConstants map. It is used by the various get* methods below.
1408 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
1409 bool OnlyIfReduced = false) {
1410 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
1411 // Fold a few common cases
1412 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
1418 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
1420 // Look up the constant in the table first to ensure uniqueness.
1421 ConstantExprKeyType Key(opc, C);
1423 return pImpl->ExprConstants.getOrCreate(Ty, Key);
1426 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
1427 bool OnlyIfReduced) {
1428 Instruction::CastOps opc = Instruction::CastOps(oc);
1429 assert(Instruction::isCast(opc) && "opcode out of range");
1430 assert(C && Ty && "Null arguments to getCast");
1431 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
1435 llvm_unreachable("Invalid cast opcode");
1436 case Instruction::Trunc:
1437 return getTrunc(C, Ty, OnlyIfReduced);
1438 case Instruction::ZExt:
1439 return getZExt(C, Ty, OnlyIfReduced);
1440 case Instruction::SExt:
1441 return getSExt(C, Ty, OnlyIfReduced);
1442 case Instruction::FPTrunc:
1443 return getFPTrunc(C, Ty, OnlyIfReduced);
1444 case Instruction::FPExt:
1445 return getFPExtend(C, Ty, OnlyIfReduced);
1446 case Instruction::UIToFP:
1447 return getUIToFP(C, Ty, OnlyIfReduced);
1448 case Instruction::SIToFP:
1449 return getSIToFP(C, Ty, OnlyIfReduced);
1450 case Instruction::FPToUI:
1451 return getFPToUI(C, Ty, OnlyIfReduced);
1452 case Instruction::FPToSI:
1453 return getFPToSI(C, Ty, OnlyIfReduced);
1454 case Instruction::PtrToInt:
1455 return getPtrToInt(C, Ty, OnlyIfReduced);
1456 case Instruction::IntToPtr:
1457 return getIntToPtr(C, Ty, OnlyIfReduced);
1458 case Instruction::BitCast:
1459 return getBitCast(C, Ty, OnlyIfReduced);
1460 case Instruction::AddrSpaceCast:
1461 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
1465 Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
1466 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1467 return getBitCast(C, Ty);
1468 return getZExt(C, Ty);
1471 Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
1472 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1473 return getBitCast(C, Ty);
1474 return getSExt(C, Ty);
1477 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
1478 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
1479 return getBitCast(C, Ty);
1480 return getTrunc(C, Ty);
1483 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
1484 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1485 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
1488 if (Ty->isIntOrIntVectorTy())
1489 return getPtrToInt(S, Ty);
1491 unsigned SrcAS = S->getType()->getPointerAddressSpace();
1492 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
1493 return getAddrSpaceCast(S, Ty);
1495 return getBitCast(S, Ty);
1498 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
1500 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
1501 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
1503 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
1504 return getAddrSpaceCast(S, Ty);
1506 return getBitCast(S, Ty);
1509 Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
1510 assert(C->getType()->isIntOrIntVectorTy() &&
1511 Ty->isIntOrIntVectorTy() && "Invalid cast");
1512 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1513 unsigned DstBits = Ty->getScalarSizeInBits();
1514 Instruction::CastOps opcode =
1515 (SrcBits == DstBits ? Instruction::BitCast :
1516 (SrcBits > DstBits ? Instruction::Trunc :
1517 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1518 return getCast(opcode, C, Ty);
1521 Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
1522 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1524 unsigned SrcBits = C->getType()->getScalarSizeInBits();
1525 unsigned DstBits = Ty->getScalarSizeInBits();
1526 if (SrcBits == DstBits)
1527 return C; // Avoid a useless cast
1528 Instruction::CastOps opcode =
1529 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
1530 return getCast(opcode, C, Ty);
1533 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1535 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1536 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1538 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1539 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
1540 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
1541 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1542 "SrcTy must be larger than DestTy for Trunc!");
1544 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
1547 Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1549 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1550 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1552 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1553 assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
1554 assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
1555 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1556 "SrcTy must be smaller than DestTy for SExt!");
1558 return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
1561 Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
1563 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1564 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1566 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1567 assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
1568 assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
1569 assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1570 "SrcTy must be smaller than DestTy for ZExt!");
1572 return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
1575 Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
1577 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1578 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1580 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1581 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1582 C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
1583 "This is an illegal floating point truncation!");
1584 return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
1587 Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
1589 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1590 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1592 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1593 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
1594 C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
1595 "This is an illegal floating point extension!");
1596 return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
1599 Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1601 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1602 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1604 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1605 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1606 "This is an illegal uint to floating point cast!");
1607 return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
1610 Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
1612 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1613 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1615 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1616 assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
1617 "This is an illegal sint to floating point cast!");
1618 return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
1621 Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1623 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1624 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1626 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1627 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1628 "This is an illegal floating point to uint cast!");
1629 return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
1632 Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
1634 bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
1635 bool toVec = Ty->getTypeID() == Type::VectorTyID;
1637 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
1638 assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
1639 "This is an illegal floating point to sint cast!");
1640 return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
1643 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
1644 bool OnlyIfReduced) {
1645 assert(C->getType()->getScalarType()->isPointerTy() &&
1646 "PtrToInt source must be pointer or pointer vector");
1647 assert(DstTy->getScalarType()->isIntegerTy() &&
1648 "PtrToInt destination must be integer or integer vector");
1649 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1650 if (isa<VectorType>(C->getType()))
1651 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1652 "Invalid cast between a different number of vector elements");
1653 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
1656 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
1657 bool OnlyIfReduced) {
1658 assert(C->getType()->getScalarType()->isIntegerTy() &&
1659 "IntToPtr source must be integer or integer vector");
1660 assert(DstTy->getScalarType()->isPointerTy() &&
1661 "IntToPtr destination must be a pointer or pointer vector");
1662 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
1663 if (isa<VectorType>(C->getType()))
1664 assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
1665 "Invalid cast between a different number of vector elements");
1666 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
1669 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
1670 bool OnlyIfReduced) {
1671 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
1672 "Invalid constantexpr bitcast!");
1674 // It is common to ask for a bitcast of a value to its own type, handle this
1676 if (C->getType() == DstTy) return C;
1678 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
1681 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
1682 bool OnlyIfReduced) {
1683 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
1684 "Invalid constantexpr addrspacecast!");
1686 // Canonicalize addrspacecasts between different pointer types by first
1687 // bitcasting the pointer type and then converting the address space.
1688 PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
1689 PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
1690 Type *DstElemTy = DstScalarTy->getElementType();
1691 if (SrcScalarTy->getElementType() != DstElemTy) {
1692 Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
1693 if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
1694 // Handle vectors of pointers.
1695 MidTy = VectorType::get(MidTy, VT->getNumElements());
1697 C = getBitCast(C, MidTy);
1699 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
1702 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
1703 unsigned Flags, Type *OnlyIfReducedTy) {
1704 // Check the operands for consistency first.
1705 assert(Opcode >= Instruction::BinaryOpsBegin &&
1706 Opcode < Instruction::BinaryOpsEnd &&
1707 "Invalid opcode in binary constant expression");
1708 assert(C1->getType() == C2->getType() &&
1709 "Operand types in binary constant expression should match");
1713 case Instruction::Add:
1714 case Instruction::Sub:
1715 case Instruction::Mul:
1716 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1717 assert(C1->getType()->isIntOrIntVectorTy() &&
1718 "Tried to create an integer operation on a non-integer type!");
1720 case Instruction::FAdd:
1721 case Instruction::FSub:
1722 case Instruction::FMul:
1723 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1724 assert(C1->getType()->isFPOrFPVectorTy() &&
1725 "Tried to create a floating-point operation on a "
1726 "non-floating-point type!");
1728 case Instruction::UDiv:
1729 case Instruction::SDiv:
1730 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1731 assert(C1->getType()->isIntOrIntVectorTy() &&
1732 "Tried to create an arithmetic operation on a non-arithmetic type!");
1734 case Instruction::FDiv:
1735 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1736 assert(C1->getType()->isFPOrFPVectorTy() &&
1737 "Tried to create an arithmetic operation on a non-arithmetic type!");
1739 case Instruction::URem:
1740 case Instruction::SRem:
1741 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1742 assert(C1->getType()->isIntOrIntVectorTy() &&
1743 "Tried to create an arithmetic operation on a non-arithmetic type!");
1745 case Instruction::FRem:
1746 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1747 assert(C1->getType()->isFPOrFPVectorTy() &&
1748 "Tried to create an arithmetic operation on a non-arithmetic type!");
1750 case Instruction::And:
1751 case Instruction::Or:
1752 case Instruction::Xor:
1753 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1754 assert(C1->getType()->isIntOrIntVectorTy() &&
1755 "Tried to create a logical operation on a non-integral type!");
1757 case Instruction::Shl:
1758 case Instruction::LShr:
1759 case Instruction::AShr:
1760 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1761 assert(C1->getType()->isIntOrIntVectorTy() &&
1762 "Tried to create a shift operation on a non-integer type!");
1769 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
1770 return FC; // Fold a few common cases.
1772 if (OnlyIfReducedTy == C1->getType())
1775 Constant *ArgVec[] = { C1, C2 };
1776 ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
1778 LLVMContextImpl *pImpl = C1->getContext().pImpl;
1779 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
1782 Constant *ConstantExpr::getSizeOf(Type* Ty) {
1783 // sizeof is implemented as: (i64) gep (Ty*)null, 1
1784 // Note that a non-inbounds gep is used, as null isn't within any object.
1785 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1786 Constant *GEP = getGetElementPtr(
1787 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1788 return getPtrToInt(GEP,
1789 Type::getInt64Ty(Ty->getContext()));
1792 Constant *ConstantExpr::getAlignOf(Type* Ty) {
1793 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
1794 // Note that a non-inbounds gep is used, as null isn't within any object.
1795 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
1796 Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
1797 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
1798 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
1799 Constant *Indices[2] = { Zero, One };
1800 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
1801 return getPtrToInt(GEP,
1802 Type::getInt64Ty(Ty->getContext()));
1805 Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
1806 return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
1810 Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
1811 // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
1812 // Note that a non-inbounds gep is used, as null isn't within any object.
1813 Constant *GEPIdx[] = {
1814 ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
1817 Constant *GEP = getGetElementPtr(
1818 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
1819 return getPtrToInt(GEP,
1820 Type::getInt64Ty(Ty->getContext()));
1823 Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
1824 Constant *C2, bool OnlyIfReduced) {
1825 assert(C1->getType() == C2->getType() && "Op types should be identical!");
1827 switch (Predicate) {
1828 default: llvm_unreachable("Invalid CmpInst predicate");
1829 case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
1830 case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
1831 case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
1832 case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
1833 case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
1834 case CmpInst::FCMP_TRUE:
1835 return getFCmp(Predicate, C1, C2, OnlyIfReduced);
1837 case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
1838 case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
1839 case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
1840 case CmpInst::ICMP_SLE:
1841 return getICmp(Predicate, C1, C2, OnlyIfReduced);
1845 Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
1846 Type *OnlyIfReducedTy) {
1847 assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
1849 if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
1850 return SC; // Fold common cases
1852 if (OnlyIfReducedTy == V1->getType())
1855 Constant *ArgVec[] = { C, V1, V2 };
1856 ConstantExprKeyType Key(Instruction::Select, ArgVec);
1858 LLVMContextImpl *pImpl = C->getContext().pImpl;
1859 return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
1862 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
1863 ArrayRef<Value *> Idxs, bool InBounds,
1864 Optional<unsigned> InRangeIndex,
1865 Type *OnlyIfReducedTy) {
1867 Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
1871 cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
1874 ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
1875 return FC; // Fold a few common cases.
1877 // Get the result type of the getelementptr!
1878 Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
1879 assert(DestTy && "GEP indices invalid!");
1880 unsigned AS = C->getType()->getPointerAddressSpace();
1881 Type *ReqTy = DestTy->getPointerTo(AS);
1883 unsigned NumVecElts = 0;
1884 if (C->getType()->isVectorTy())
1885 NumVecElts = C->getType()->getVectorNumElements();
1886 else for (auto Idx : Idxs)
1887 if (Idx->getType()->isVectorTy())
1888 NumVecElts = Idx->getType()->getVectorNumElements();
1891 ReqTy = VectorType::get(ReqTy, NumVecElts);
1893 if (OnlyIfReducedTy == ReqTy)
1896 // Look up the constant in the table first to ensure uniqueness
1897 std::vector<Constant*> ArgVec;
1898 ArgVec.reserve(1 + Idxs.size());
1899 ArgVec.push_back(C);
1900 for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
1901 assert((!Idxs[i]->getType()->isVectorTy() ||
1902 Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
1903 "getelementptr index type missmatch");
1905 Constant *Idx = cast<Constant>(Idxs[i]);
1906 if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
1907 Idx = ConstantVector::getSplat(NumVecElts, Idx);
1908 ArgVec.push_back(Idx);
1911 unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
1912 if (InRangeIndex && *InRangeIndex < 63)
1913 SubClassOptionalData |= (*InRangeIndex + 1) << 1;
1914 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
1915 SubClassOptionalData, None, Ty);
1917 LLVMContextImpl *pImpl = C->getContext().pImpl;
1918 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1921 Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
1922 Constant *RHS, bool OnlyIfReduced) {
1923 assert(LHS->getType() == RHS->getType());
1924 assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
1925 pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
1927 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1928 return FC; // Fold a few common cases...
1933 // Look up the constant in the table first to ensure uniqueness
1934 Constant *ArgVec[] = { LHS, RHS };
1935 // Get the key type with both the opcode and predicate
1936 const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
1938 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1939 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1940 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1942 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1943 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1946 Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
1947 Constant *RHS, bool OnlyIfReduced) {
1948 assert(LHS->getType() == RHS->getType());
1949 assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
1951 if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
1952 return FC; // Fold a few common cases...
1957 // Look up the constant in the table first to ensure uniqueness
1958 Constant *ArgVec[] = { LHS, RHS };
1959 // Get the key type with both the opcode and predicate
1960 const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
1962 Type *ResultTy = Type::getInt1Ty(LHS->getContext());
1963 if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
1964 ResultTy = VectorType::get(ResultTy, VT->getNumElements());
1966 LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
1967 return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
1970 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
1971 Type *OnlyIfReducedTy) {
1972 assert(Val->getType()->isVectorTy() &&
1973 "Tried to create extractelement operation on non-vector type!");
1974 assert(Idx->getType()->isIntegerTy() &&
1975 "Extractelement index must be an integer type!");
1977 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
1978 return FC; // Fold a few common cases.
1980 Type *ReqTy = Val->getType()->getVectorElementType();
1981 if (OnlyIfReducedTy == ReqTy)
1984 // Look up the constant in the table first to ensure uniqueness
1985 Constant *ArgVec[] = { Val, Idx };
1986 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
1988 LLVMContextImpl *pImpl = Val->getContext().pImpl;
1989 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
1992 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
1993 Constant *Idx, Type *OnlyIfReducedTy) {
1994 assert(Val->getType()->isVectorTy() &&
1995 "Tried to create insertelement operation on non-vector type!");
1996 assert(Elt->getType() == Val->getType()->getVectorElementType() &&
1997 "Insertelement types must match!");
1998 assert(Idx->getType()->isIntegerTy() &&
1999 "Insertelement index must be i32 type!");
2001 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2002 return FC; // Fold a few common cases.
2004 if (OnlyIfReducedTy == Val->getType())
2007 // Look up the constant in the table first to ensure uniqueness
2008 Constant *ArgVec[] = { Val, Elt, Idx };
2009 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2011 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2012 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2015 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2016 Constant *Mask, Type *OnlyIfReducedTy) {
2017 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2018 "Invalid shuffle vector constant expr operands!");
2020 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2021 return FC; // Fold a few common cases.
2023 unsigned NElts = Mask->getType()->getVectorNumElements();
2024 Type *EltTy = V1->getType()->getVectorElementType();
2025 Type *ShufTy = VectorType::get(EltTy, NElts);
2027 if (OnlyIfReducedTy == ShufTy)
2030 // Look up the constant in the table first to ensure uniqueness
2031 Constant *ArgVec[] = { V1, V2, Mask };
2032 const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
2034 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2035 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2038 Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
2039 ArrayRef<unsigned> Idxs,
2040 Type *OnlyIfReducedTy) {
2041 assert(Agg->getType()->isFirstClassType() &&
2042 "Non-first-class type for constant insertvalue expression");
2044 assert(ExtractValueInst::getIndexedType(Agg->getType(),
2045 Idxs) == Val->getType() &&
2046 "insertvalue indices invalid!");
2047 Type *ReqTy = Val->getType();
2049 if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
2052 if (OnlyIfReducedTy == ReqTy)
2055 Constant *ArgVec[] = { Agg, Val };
2056 const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
2058 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2059 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2062 Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
2063 Type *OnlyIfReducedTy) {
2064 assert(Agg->getType()->isFirstClassType() &&
2065 "Tried to create extractelement operation on non-first-class type!");
2067 Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
2069 assert(ReqTy && "extractvalue indices invalid!");
2071 assert(Agg->getType()->isFirstClassType() &&
2072 "Non-first-class type for constant extractvalue expression");
2073 if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
2076 if (OnlyIfReducedTy == ReqTy)
2079 Constant *ArgVec[] = { Agg };
2080 const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
2082 LLVMContextImpl *pImpl = Agg->getContext().pImpl;
2083 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2086 Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
2087 assert(C->getType()->isIntOrIntVectorTy() &&
2088 "Cannot NEG a nonintegral value!");
2089 return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
2093 Constant *ConstantExpr::getFNeg(Constant *C) {
2094 assert(C->getType()->isFPOrFPVectorTy() &&
2095 "Cannot FNEG a non-floating-point value!");
2096 return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
2099 Constant *ConstantExpr::getNot(Constant *C) {
2100 assert(C->getType()->isIntOrIntVectorTy() &&
2101 "Cannot NOT a nonintegral value!");
2102 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2105 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2106 bool HasNUW, bool HasNSW) {
2107 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2108 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2109 return get(Instruction::Add, C1, C2, Flags);
2112 Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
2113 return get(Instruction::FAdd, C1, C2);
2116 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2117 bool HasNUW, bool HasNSW) {
2118 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2119 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2120 return get(Instruction::Sub, C1, C2, Flags);
2123 Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
2124 return get(Instruction::FSub, C1, C2);
2127 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2128 bool HasNUW, bool HasNSW) {
2129 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2130 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2131 return get(Instruction::Mul, C1, C2, Flags);
2134 Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
2135 return get(Instruction::FMul, C1, C2);
2138 Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
2139 return get(Instruction::UDiv, C1, C2,
2140 isExact ? PossiblyExactOperator::IsExact : 0);
2143 Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
2144 return get(Instruction::SDiv, C1, C2,
2145 isExact ? PossiblyExactOperator::IsExact : 0);
2148 Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
2149 return get(Instruction::FDiv, C1, C2);
2152 Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
2153 return get(Instruction::URem, C1, C2);
2156 Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
2157 return get(Instruction::SRem, C1, C2);
2160 Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
2161 return get(Instruction::FRem, C1, C2);
2164 Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
2165 return get(Instruction::And, C1, C2);
2168 Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
2169 return get(Instruction::Or, C1, C2);
2172 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2173 return get(Instruction::Xor, C1, C2);
2176 Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
2177 bool HasNUW, bool HasNSW) {
2178 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2179 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2180 return get(Instruction::Shl, C1, C2, Flags);
2183 Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
2184 return get(Instruction::LShr, C1, C2,
2185 isExact ? PossiblyExactOperator::IsExact : 0);
2188 Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
2189 return get(Instruction::AShr, C1, C2,
2190 isExact ? PossiblyExactOperator::IsExact : 0);
2193 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
2196 // Doesn't have an identity.
2199 case Instruction::Add:
2200 case Instruction::Or:
2201 case Instruction::Xor:
2202 return Constant::getNullValue(Ty);
2204 case Instruction::Mul:
2205 return ConstantInt::get(Ty, 1);
2207 case Instruction::And:
2208 return Constant::getAllOnesValue(Ty);
2212 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
2215 // Doesn't have an absorber.
2218 case Instruction::Or:
2219 return Constant::getAllOnesValue(Ty);
2221 case Instruction::And:
2222 case Instruction::Mul:
2223 return Constant::getNullValue(Ty);
2227 /// Remove the constant from the constant table.
2228 void ConstantExpr::destroyConstantImpl() {
2229 getType()->getContext().pImpl->ExprConstants.remove(this);
2232 const char *ConstantExpr::getOpcodeName() const {
2233 return Instruction::getOpcodeName(getOpcode());
2236 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2237 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
2238 : ConstantExpr(DestTy, Instruction::GetElementPtr,
2239 OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
2240 (IdxList.size() + 1),
2241 IdxList.size() + 1),
2242 SrcElementTy(SrcElementTy),
2243 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
2245 Use *OperandList = getOperandList();
2246 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2247 OperandList[i+1] = IdxList[i];
2250 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2251 return SrcElementTy;
2254 Type *GetElementPtrConstantExpr::getResultElementType() const {
2255 return ResElementTy;
2258 //===----------------------------------------------------------------------===//
2259 // ConstantData* implementations
2261 Type *ConstantDataSequential::getElementType() const {
2262 return getType()->getElementType();
2265 StringRef ConstantDataSequential::getRawDataValues() const {
2266 return StringRef(DataElements, getNumElements()*getElementByteSize());
2269 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2270 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
2271 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2272 switch (IT->getBitWidth()) {
2284 unsigned ConstantDataSequential::getNumElements() const {
2285 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2286 return AT->getNumElements();
2287 return getType()->getVectorNumElements();
2291 uint64_t ConstantDataSequential::getElementByteSize() const {
2292 return getElementType()->getPrimitiveSizeInBits()/8;
2295 /// Return the start of the specified element.
2296 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2297 assert(Elt < getNumElements() && "Invalid Elt");
2298 return DataElements+Elt*getElementByteSize();
2302 /// Return true if the array is empty or all zeros.
2303 static bool isAllZeros(StringRef Arr) {
2310 /// This is the underlying implementation of all of the
2311 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2312 /// the correct element type. We take the bytes in as a StringRef because
2313 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2314 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2315 assert(isElementTypeCompatible(Ty->getSequentialElementType()));
2316 // If the elements are all zero or there are no elements, return a CAZ, which
2317 // is more dense and canonical.
2318 if (isAllZeros(Elements))
2319 return ConstantAggregateZero::get(Ty);
2321 // Do a lookup to see if we have already formed one of these.
2324 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2327 // The bucket can point to a linked list of different CDS's that have the same
2328 // body but different types. For example, 0,0,0,1 could be a 4 element array
2329 // of i8, or a 1-element array of i32. They'll both end up in the same
2330 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2331 ConstantDataSequential **Entry = &Slot.second;
2332 for (ConstantDataSequential *Node = *Entry; Node;
2333 Entry = &Node->Next, Node = *Entry)
2334 if (Node->getType() == Ty)
2337 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2339 if (isa<ArrayType>(Ty))
2340 return *Entry = new ConstantDataArray(Ty, Slot.first().data());
2342 assert(isa<VectorType>(Ty));
2343 return *Entry = new ConstantDataVector(Ty, Slot.first().data());
2346 void ConstantDataSequential::destroyConstantImpl() {
2347 // Remove the constant from the StringMap.
2348 StringMap<ConstantDataSequential*> &CDSConstants =
2349 getType()->getContext().pImpl->CDSConstants;
2351 StringMap<ConstantDataSequential*>::iterator Slot =
2352 CDSConstants.find(getRawDataValues());
2354 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2356 ConstantDataSequential **Entry = &Slot->getValue();
2358 // Remove the entry from the hash table.
2359 if (!(*Entry)->Next) {
2360 // If there is only one value in the bucket (common case) it must be this
2361 // entry, and removing the entry should remove the bucket completely.
2362 assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
2363 getContext().pImpl->CDSConstants.erase(Slot);
2365 // Otherwise, there are multiple entries linked off the bucket, unlink the
2366 // node we care about but keep the bucket around.
2367 for (ConstantDataSequential *Node = *Entry; ;
2368 Entry = &Node->Next, Node = *Entry) {
2369 assert(Node && "Didn't find entry in its uniquing hash table!");
2370 // If we found our entry, unlink it from the list and we're done.
2372 *Entry = Node->Next;
2378 // If we were part of a list, make sure that we don't delete the list that is
2379 // still owned by the uniquing map.
2383 /// get() constructors - Return a constant with array type with an element
2384 /// count and element type matching the ArrayRef passed in. Note that this
2385 /// can return a ConstantAggregateZero object.
2386 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
2387 Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
2388 const char *Data = reinterpret_cast<const char *>(Elts.data());
2389 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2391 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2392 Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
2393 const char *Data = reinterpret_cast<const char *>(Elts.data());
2394 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2396 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2397 Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
2398 const char *Data = reinterpret_cast<const char *>(Elts.data());
2399 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2401 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2402 Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
2403 const char *Data = reinterpret_cast<const char *>(Elts.data());
2404 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2406 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
2407 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2408 const char *Data = reinterpret_cast<const char *>(Elts.data());
2409 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2411 Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
2412 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2413 const char *Data = reinterpret_cast<const char *>(Elts.data());
2414 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2417 /// getFP() constructors - Return a constant with array type with an element
2418 /// count and element type of float with precision matching the number of
2419 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2420 /// double for 64bits) Note that this can return a ConstantAggregateZero
2422 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2423 ArrayRef<uint16_t> Elts) {
2424 Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
2425 const char *Data = reinterpret_cast<const char *>(Elts.data());
2426 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2428 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2429 ArrayRef<uint32_t> Elts) {
2430 Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
2431 const char *Data = reinterpret_cast<const char *>(Elts.data());
2432 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2434 Constant *ConstantDataArray::getFP(LLVMContext &Context,
2435 ArrayRef<uint64_t> Elts) {
2436 Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
2437 const char *Data = reinterpret_cast<const char *>(Elts.data());
2438 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2441 Constant *ConstantDataArray::getString(LLVMContext &Context,
2442 StringRef Str, bool AddNull) {
2444 const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
2445 return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
2449 SmallVector<uint8_t, 64> ElementVals;
2450 ElementVals.append(Str.begin(), Str.end());
2451 ElementVals.push_back(0);
2452 return get(Context, ElementVals);
2455 /// get() constructors - Return a constant with vector type with an element
2456 /// count and element type matching the ArrayRef passed in. Note that this
2457 /// can return a ConstantAggregateZero object.
2458 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2459 Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
2460 const char *Data = reinterpret_cast<const char *>(Elts.data());
2461 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
2463 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
2464 Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
2465 const char *Data = reinterpret_cast<const char *>(Elts.data());
2466 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
2468 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
2469 Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
2470 const char *Data = reinterpret_cast<const char *>(Elts.data());
2471 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2473 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
2474 Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
2475 const char *Data = reinterpret_cast<const char *>(Elts.data());
2476 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
2478 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
2479 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2480 const char *Data = reinterpret_cast<const char *>(Elts.data());
2481 return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
2483 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
2484 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2485 const char *Data = reinterpret_cast<const char *>(Elts.data());
2486 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2489 /// getFP() constructors - Return a constant with vector type with an element
2490 /// count and element type of float with the precision matching the number of
2491 /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
2492 /// double for 64bits) Note that this can return a ConstantAggregateZero
2494 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2495 ArrayRef<uint16_t> Elts) {
2496 Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
2497 const char *Data = reinterpret_cast<const char *>(Elts.data());
2498 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
2500 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2501 ArrayRef<uint32_t> Elts) {
2502 Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
2503 const char *Data = reinterpret_cast<const char *>(Elts.data());
2504 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
2506 Constant *ConstantDataVector::getFP(LLVMContext &Context,
2507 ArrayRef<uint64_t> Elts) {
2508 Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
2509 const char *Data = reinterpret_cast<const char *>(Elts.data());
2510 return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
2513 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
2514 assert(isElementTypeCompatible(V->getType()) &&
2515 "Element type not compatible with ConstantData");
2516 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
2517 if (CI->getType()->isIntegerTy(8)) {
2518 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
2519 return get(V->getContext(), Elts);
2521 if (CI->getType()->isIntegerTy(16)) {
2522 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
2523 return get(V->getContext(), Elts);
2525 if (CI->getType()->isIntegerTy(32)) {
2526 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
2527 return get(V->getContext(), Elts);
2529 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
2530 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
2531 return get(V->getContext(), Elts);
2534 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
2535 if (CFP->getType()->isHalfTy()) {
2536 SmallVector<uint16_t, 16> Elts(
2537 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2538 return getFP(V->getContext(), Elts);
2540 if (CFP->getType()->isFloatTy()) {
2541 SmallVector<uint32_t, 16> Elts(
2542 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2543 return getFP(V->getContext(), Elts);
2545 if (CFP->getType()->isDoubleTy()) {
2546 SmallVector<uint64_t, 16> Elts(
2547 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
2548 return getFP(V->getContext(), Elts);
2551 return ConstantVector::getSplat(NumElts, V);
2555 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
2556 assert(isa<IntegerType>(getElementType()) &&
2557 "Accessor can only be used when element is an integer");
2558 const char *EltPtr = getElementPointer(Elt);
2560 // The data is stored in host byte order, make sure to cast back to the right
2561 // type to load with the right endianness.
2562 switch (getElementType()->getIntegerBitWidth()) {
2563 default: llvm_unreachable("Invalid bitwidth for CDS");
2565 return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
2567 return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
2569 return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
2571 return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
2575 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
2576 const char *EltPtr = getElementPointer(Elt);
2578 switch (getElementType()->getTypeID()) {
2580 llvm_unreachable("Accessor can only be used when element is float/double!");
2581 case Type::HalfTyID: {
2582 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
2583 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
2585 case Type::FloatTyID: {
2586 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
2587 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
2589 case Type::DoubleTyID: {
2590 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
2591 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
2596 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
2597 assert(getElementType()->isFloatTy() &&
2598 "Accessor can only be used when element is a 'float'");
2599 const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
2600 return *const_cast<float *>(EltPtr);
2603 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
2604 assert(getElementType()->isDoubleTy() &&
2605 "Accessor can only be used when element is a 'float'");
2606 const double *EltPtr =
2607 reinterpret_cast<const double *>(getElementPointer(Elt));
2608 return *const_cast<double *>(EltPtr);
2611 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
2612 if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
2613 getElementType()->isDoubleTy())
2614 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
2616 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
2619 bool ConstantDataSequential::isString(unsigned CharSize) const {
2620 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
2623 bool ConstantDataSequential::isCString() const {
2627 StringRef Str = getAsString();
2629 // The last value must be nul.
2630 if (Str.back() != 0) return false;
2632 // Other elements must be non-nul.
2633 return Str.drop_back().find(0) == StringRef::npos;
2636 Constant *ConstantDataVector::getSplatValue() const {
2637 const char *Base = getRawDataValues().data();
2639 // Compare elements 1+ to the 0'th element.
2640 unsigned EltSize = getElementByteSize();
2641 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
2642 if (memcmp(Base, Base+i*EltSize, EltSize))
2645 // If they're all the same, return the 0th one as a representative.
2646 return getElementAsConstant(0);
2649 //===----------------------------------------------------------------------===//
2650 // handleOperandChange implementations
2652 /// Update this constant array to change uses of
2653 /// 'From' to be uses of 'To'. This must update the uniquing data structures
2656 /// Note that we intentionally replace all uses of From with To here. Consider
2657 /// a large array that uses 'From' 1000 times. By handling this case all here,
2658 /// ConstantArray::handleOperandChange is only invoked once, and that
2659 /// single invocation handles all 1000 uses. Handling them one at a time would
2660 /// work, but would be really slow because it would have to unique each updated
2663 void Constant::handleOperandChange(Value *From, Value *To) {
2664 Value *Replacement = nullptr;
2665 switch (getValueID()) {
2667 llvm_unreachable("Not a constant!");
2668 #define HANDLE_CONSTANT(Name) \
2669 case Value::Name##Val: \
2670 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
2672 #include "llvm/IR/Value.def"
2675 // If handleOperandChangeImpl returned nullptr, then it handled
2676 // replacing itself and we don't want to delete or replace anything else here.
2680 // I do need to replace this with an existing value.
2681 assert(Replacement != this && "I didn't contain From!");
2683 // Everyone using this now uses the replacement.
2684 replaceAllUsesWith(Replacement);
2686 // Delete the old constant!
2690 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
2691 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2692 Constant *ToC = cast<Constant>(To);
2694 SmallVector<Constant*, 8> Values;
2695 Values.reserve(getNumOperands()); // Build replacement array.
2697 // Fill values with the modified operands of the constant array. Also,
2698 // compute whether this turns into an all-zeros array.
2699 unsigned NumUpdated = 0;
2701 // Keep track of whether all the values in the array are "ToC".
2702 bool AllSame = true;
2703 Use *OperandList = getOperandList();
2704 unsigned OperandNo = 0;
2705 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
2706 Constant *Val = cast<Constant>(O->get());
2708 OperandNo = (O - OperandList);
2712 Values.push_back(Val);
2713 AllSame &= Val == ToC;
2716 if (AllSame && ToC->isNullValue())
2717 return ConstantAggregateZero::get(getType());
2719 if (AllSame && isa<UndefValue>(ToC))
2720 return UndefValue::get(getType());
2722 // Check for any other type of constant-folding.
2723 if (Constant *C = getImpl(getType(), Values))
2726 // Update to the new value.
2727 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
2728 Values, this, From, ToC, NumUpdated, OperandNo);
2731 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
2732 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2733 Constant *ToC = cast<Constant>(To);
2735 Use *OperandList = getOperandList();
2737 SmallVector<Constant*, 8> Values;
2738 Values.reserve(getNumOperands()); // Build replacement struct.
2740 // Fill values with the modified operands of the constant struct. Also,
2741 // compute whether this turns into an all-zeros struct.
2742 unsigned NumUpdated = 0;
2743 bool AllSame = true;
2744 unsigned OperandNo = 0;
2745 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2746 Constant *Val = cast<Constant>(O->get());
2748 OperandNo = (O - OperandList);
2752 Values.push_back(Val);
2753 AllSame &= Val == ToC;
2756 if (AllSame && ToC->isNullValue())
2757 return ConstantAggregateZero::get(getType());
2759 if (AllSame && isa<UndefValue>(ToC))
2760 return UndefValue::get(getType());
2762 // Update to the new value.
2763 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
2764 Values, this, From, ToC, NumUpdated, OperandNo);
2767 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
2768 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
2769 Constant *ToC = cast<Constant>(To);
2771 SmallVector<Constant*, 8> Values;
2772 Values.reserve(getNumOperands()); // Build replacement array...
2773 unsigned NumUpdated = 0;
2774 unsigned OperandNo = 0;
2775 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2776 Constant *Val = getOperand(i);
2782 Values.push_back(Val);
2785 if (Constant *C = getImpl(Values))
2788 // Update to the new value.
2789 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
2790 Values, this, From, ToC, NumUpdated, OperandNo);
2793 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
2794 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2795 Constant *To = cast<Constant>(ToV);
2797 SmallVector<Constant*, 8> NewOps;
2798 unsigned NumUpdated = 0;
2799 unsigned OperandNo = 0;
2800 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2801 Constant *Op = getOperand(i);
2807 NewOps.push_back(Op);
2809 assert(NumUpdated && "I didn't contain From!");
2811 if (Constant *C = getWithOperands(NewOps, getType(), true))
2814 // Update to the new value.
2815 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
2816 NewOps, this, From, To, NumUpdated, OperandNo);
2819 Instruction *ConstantExpr::getAsInstruction() {
2820 SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
2821 ArrayRef<Value*> Ops(ValueOperands);
2823 switch (getOpcode()) {
2824 case Instruction::Trunc:
2825 case Instruction::ZExt:
2826 case Instruction::SExt:
2827 case Instruction::FPTrunc:
2828 case Instruction::FPExt:
2829 case Instruction::UIToFP:
2830 case Instruction::SIToFP:
2831 case Instruction::FPToUI:
2832 case Instruction::FPToSI:
2833 case Instruction::PtrToInt:
2834 case Instruction::IntToPtr:
2835 case Instruction::BitCast:
2836 case Instruction::AddrSpaceCast:
2837 return CastInst::Create((Instruction::CastOps)getOpcode(),
2839 case Instruction::Select:
2840 return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
2841 case Instruction::InsertElement:
2842 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
2843 case Instruction::ExtractElement:
2844 return ExtractElementInst::Create(Ops[0], Ops[1]);
2845 case Instruction::InsertValue:
2846 return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
2847 case Instruction::ExtractValue:
2848 return ExtractValueInst::Create(Ops[0], getIndices());
2849 case Instruction::ShuffleVector:
2850 return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
2852 case Instruction::GetElementPtr: {
2853 const auto *GO = cast<GEPOperator>(this);
2854 if (GO->isInBounds())
2855 return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
2856 Ops[0], Ops.slice(1));
2857 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
2860 case Instruction::ICmp:
2861 case Instruction::FCmp:
2862 return CmpInst::Create((Instruction::OtherOps)getOpcode(),
2863 (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
2866 assert(getNumOperands() == 2 && "Must be binary operator?");
2867 BinaryOperator *BO =
2868 BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
2870 if (isa<OverflowingBinaryOperator>(BO)) {
2871 BO->setHasNoUnsignedWrap(SubclassOptionalData &
2872 OverflowingBinaryOperator::NoUnsignedWrap);
2873 BO->setHasNoSignedWrap(SubclassOptionalData &
2874 OverflowingBinaryOperator::NoSignedWrap);
2876 if (isa<PossiblyExactOperator>(BO))
2877 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);