[lld/COFF] Demangle symbol name in discarded section relocation error message (#119726)
[llvm-project.git] / llvm / lib / IR / Constants.cpp
blob95832ed0b8951a375a5ed7d8f28e8de670ebe663
1 //===-- Constants.cpp - Implement Constant nodes --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Constant* classes.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/Constants.h"
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/ConstantFold.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/GlobalAlias.h"
24 #include "llvm/IR/GlobalIFunc.h"
25 #include "llvm/IR/GlobalValue.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/IR/PatternMatch.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
35 using namespace llvm;
36 using namespace PatternMatch;
38 // As set of temporary options to help migrate how splats are represented.
39 static cl::opt<bool> UseConstantIntForFixedLengthSplat(
40 "use-constant-int-for-fixed-length-splat", cl::init(false), cl::Hidden,
41 cl::desc("Use ConstantInt's native fixed-length vector splat support."));
42 static cl::opt<bool> UseConstantFPForFixedLengthSplat(
43 "use-constant-fp-for-fixed-length-splat", cl::init(false), cl::Hidden,
44 cl::desc("Use ConstantFP's native fixed-length vector splat support."));
45 static cl::opt<bool> UseConstantIntForScalableSplat(
46 "use-constant-int-for-scalable-splat", cl::init(false), cl::Hidden,
47 cl::desc("Use ConstantInt's native scalable vector splat support."));
48 static cl::opt<bool> UseConstantFPForScalableSplat(
49 "use-constant-fp-for-scalable-splat", cl::init(false), cl::Hidden,
50 cl::desc("Use ConstantFP's native scalable vector splat support."));
52 //===----------------------------------------------------------------------===//
53 // Constant Class
54 //===----------------------------------------------------------------------===//
56 bool Constant::isNegativeZeroValue() const {
57 // Floating point values have an explicit -0.0 value.
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero() && CFP->isNegative();
61 // Equivalent for a vector of -0.0's.
62 if (getType()->isVectorTy())
63 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
64 return SplatCFP->isNegativeZeroValue();
66 // We've already handled true FP case; any other FP vectors can't represent -0.0.
67 if (getType()->isFPOrFPVectorTy())
68 return false;
70 // Otherwise, just use +0.0.
71 return isNullValue();
74 // Return true iff this constant is positive zero (floating point), negative
75 // zero (floating point), or a null value.
76 bool Constant::isZeroValue() const {
77 // Floating point values have an explicit -0.0 value.
78 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
79 return CFP->isZero();
81 // Check for constant splat vectors of 1 values.
82 if (getType()->isVectorTy())
83 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
84 return SplatCFP->isZero();
86 // Otherwise, just use +0.0.
87 return isNullValue();
90 bool Constant::isNullValue() const {
91 // 0 is null.
92 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
93 return CI->isZero();
95 // +0.0 is null.
96 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
97 // ppc_fp128 determine isZero using high order double only
98 // Should check the bitwise value to make sure all bits are zero.
99 return CFP->isExactlyValue(+0.0);
101 // constant zero is zero for aggregates, cpnull is null for pointers, none for
102 // tokens.
103 return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
104 isa<ConstantTokenNone>(this) || isa<ConstantTargetNone>(this);
107 bool Constant::isAllOnesValue() const {
108 // Check for -1 integers
109 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
110 return CI->isMinusOne();
112 // Check for FP which are bitcasted from -1 integers
113 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
114 return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
116 // Check for constant splat vectors of 1 values.
117 if (getType()->isVectorTy())
118 if (const auto *SplatVal = getSplatValue())
119 return SplatVal->isAllOnesValue();
121 return false;
124 bool Constant::isOneValue() const {
125 // Check for 1 integers
126 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
127 return CI->isOne();
129 // Check for FP which are bitcasted from 1 integers
130 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
131 return CFP->getValueAPF().bitcastToAPInt().isOne();
133 // Check for constant splat vectors of 1 values.
134 if (getType()->isVectorTy())
135 if (const auto *SplatVal = getSplatValue())
136 return SplatVal->isOneValue();
138 return false;
141 bool Constant::isNotOneValue() const {
142 // Check for 1 integers
143 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
144 return !CI->isOneValue();
146 // Check for FP which are bitcasted from 1 integers
147 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
148 return !CFP->getValueAPF().bitcastToAPInt().isOne();
150 // Check that vectors don't contain 1
151 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
152 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
153 Constant *Elt = getAggregateElement(I);
154 if (!Elt || !Elt->isNotOneValue())
155 return false;
157 return true;
160 // Check for splats that don't contain 1
161 if (getType()->isVectorTy())
162 if (const auto *SplatVal = getSplatValue())
163 return SplatVal->isNotOneValue();
165 // It *may* contain 1, we can't tell.
166 return false;
169 bool Constant::isMinSignedValue() const {
170 // Check for INT_MIN integers
171 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
172 return CI->isMinValue(/*isSigned=*/true);
174 // Check for FP which are bitcasted from INT_MIN integers
175 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
176 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
178 // Check for splats of INT_MIN values.
179 if (getType()->isVectorTy())
180 if (const auto *SplatVal = getSplatValue())
181 return SplatVal->isMinSignedValue();
183 return false;
186 bool Constant::isNotMinSignedValue() const {
187 // Check for INT_MIN integers
188 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
189 return !CI->isMinValue(/*isSigned=*/true);
191 // Check for FP which are bitcasted from INT_MIN integers
192 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
193 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
195 // Check that vectors don't contain INT_MIN
196 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
197 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
198 Constant *Elt = getAggregateElement(I);
199 if (!Elt || !Elt->isNotMinSignedValue())
200 return false;
202 return true;
205 // Check for splats that aren't INT_MIN
206 if (getType()->isVectorTy())
207 if (const auto *SplatVal = getSplatValue())
208 return SplatVal->isNotMinSignedValue();
210 // It *may* contain INT_MIN, we can't tell.
211 return false;
214 bool Constant::isFiniteNonZeroFP() const {
215 if (auto *CFP = dyn_cast<ConstantFP>(this))
216 return CFP->getValueAPF().isFiniteNonZero();
218 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
219 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
220 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
221 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
222 return false;
224 return true;
227 if (getType()->isVectorTy())
228 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
229 return SplatCFP->isFiniteNonZeroFP();
231 // It *may* contain finite non-zero, we can't tell.
232 return false;
235 bool Constant::isNormalFP() const {
236 if (auto *CFP = dyn_cast<ConstantFP>(this))
237 return CFP->getValueAPF().isNormal();
239 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
240 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
241 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
242 if (!CFP || !CFP->getValueAPF().isNormal())
243 return false;
245 return true;
248 if (getType()->isVectorTy())
249 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
250 return SplatCFP->isNormalFP();
252 // It *may* contain a normal fp value, we can't tell.
253 return false;
256 bool Constant::hasExactInverseFP() const {
257 if (auto *CFP = dyn_cast<ConstantFP>(this))
258 return CFP->getValueAPF().getExactInverse(nullptr);
260 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
261 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
262 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
263 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
264 return false;
266 return true;
269 if (getType()->isVectorTy())
270 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
271 return SplatCFP->hasExactInverseFP();
273 // It *may* have an exact inverse fp value, we can't tell.
274 return false;
277 bool Constant::isNaN() const {
278 if (auto *CFP = dyn_cast<ConstantFP>(this))
279 return CFP->isNaN();
281 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
282 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
283 auto *CFP = dyn_cast_or_null<ConstantFP>(getAggregateElement(I));
284 if (!CFP || !CFP->isNaN())
285 return false;
287 return true;
290 if (getType()->isVectorTy())
291 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
292 return SplatCFP->isNaN();
294 // It *may* be NaN, we can't tell.
295 return false;
298 bool Constant::isElementWiseEqual(Value *Y) const {
299 // Are they fully identical?
300 if (this == Y)
301 return true;
303 // The input value must be a vector constant with the same type.
304 auto *VTy = dyn_cast<VectorType>(getType());
305 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
306 return false;
308 // TODO: Compare pointer constants?
309 if (!(VTy->getElementType()->isIntegerTy() ||
310 VTy->getElementType()->isFloatingPointTy()))
311 return false;
313 // They may still be identical element-wise (if they have `undef`s).
314 // Bitcast to integer to allow exact bitwise comparison for all types.
315 Type *IntTy = VectorType::getInteger(VTy);
316 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
317 Constant *C1 = ConstantExpr::getBitCast(cast<Constant>(Y), IntTy);
318 Constant *CmpEq = ConstantFoldCompareInstruction(ICmpInst::ICMP_EQ, C0, C1);
319 return CmpEq && (isa<PoisonValue>(CmpEq) || match(CmpEq, m_One()));
322 static bool
323 containsUndefinedElement(const Constant *C,
324 function_ref<bool(const Constant *)> HasFn) {
325 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
326 if (HasFn(C))
327 return true;
328 if (isa<ConstantAggregateZero>(C))
329 return false;
330 if (isa<ScalableVectorType>(C->getType()))
331 return false;
333 for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
334 i != e; ++i) {
335 if (Constant *Elem = C->getAggregateElement(i))
336 if (HasFn(Elem))
337 return true;
341 return false;
344 bool Constant::containsUndefOrPoisonElement() const {
345 return containsUndefinedElement(
346 this, [&](const auto *C) { return isa<UndefValue>(C); });
349 bool Constant::containsPoisonElement() const {
350 return containsUndefinedElement(
351 this, [&](const auto *C) { return isa<PoisonValue>(C); });
354 bool Constant::containsUndefElement() const {
355 return containsUndefinedElement(this, [&](const auto *C) {
356 return isa<UndefValue>(C) && !isa<PoisonValue>(C);
360 bool Constant::containsConstantExpression() const {
361 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
362 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
363 if (isa<ConstantExpr>(getAggregateElement(i)))
364 return true;
366 return false;
369 /// Constructor to create a '0' constant of arbitrary type.
370 Constant *Constant::getNullValue(Type *Ty) {
371 switch (Ty->getTypeID()) {
372 case Type::IntegerTyID:
373 return ConstantInt::get(Ty, 0);
374 case Type::HalfTyID:
375 case Type::BFloatTyID:
376 case Type::FloatTyID:
377 case Type::DoubleTyID:
378 case Type::X86_FP80TyID:
379 case Type::FP128TyID:
380 case Type::PPC_FP128TyID:
381 return ConstantFP::get(Ty->getContext(),
382 APFloat::getZero(Ty->getFltSemantics()));
383 case Type::PointerTyID:
384 return ConstantPointerNull::get(cast<PointerType>(Ty));
385 case Type::StructTyID:
386 case Type::ArrayTyID:
387 case Type::FixedVectorTyID:
388 case Type::ScalableVectorTyID:
389 return ConstantAggregateZero::get(Ty);
390 case Type::TokenTyID:
391 return ConstantTokenNone::get(Ty->getContext());
392 case Type::TargetExtTyID:
393 return ConstantTargetNone::get(cast<TargetExtType>(Ty));
394 default:
395 // Function, Label, or Opaque type?
396 llvm_unreachable("Cannot create a null constant of that type!");
400 Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
401 Type *ScalarTy = Ty->getScalarType();
403 // Create the base integer constant.
404 Constant *C = ConstantInt::get(Ty->getContext(), V);
406 // Convert an integer to a pointer, if necessary.
407 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
408 C = ConstantExpr::getIntToPtr(C, PTy);
410 // Broadcast a scalar to a vector, if necessary.
411 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
412 C = ConstantVector::getSplat(VTy->getElementCount(), C);
414 return C;
417 Constant *Constant::getAllOnesValue(Type *Ty) {
418 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
419 return ConstantInt::get(Ty->getContext(),
420 APInt::getAllOnes(ITy->getBitWidth()));
422 if (Ty->isFloatingPointTy()) {
423 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
424 return ConstantFP::get(Ty->getContext(), FL);
427 VectorType *VTy = cast<VectorType>(Ty);
428 return ConstantVector::getSplat(VTy->getElementCount(),
429 getAllOnesValue(VTy->getElementType()));
432 Constant *Constant::getAggregateElement(unsigned Elt) const {
433 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
434 "Must be an aggregate/vector constant");
436 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
437 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
439 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
440 return Elt < CAZ->getElementCount().getKnownMinValue()
441 ? CAZ->getElementValue(Elt)
442 : nullptr;
444 if (const auto *CI = dyn_cast<ConstantInt>(this))
445 return Elt < cast<VectorType>(getType())
446 ->getElementCount()
447 .getKnownMinValue()
448 ? ConstantInt::get(getContext(), CI->getValue())
449 : nullptr;
451 // FIXME: getNumElements() will fail for non-fixed vector types.
452 if (isa<ScalableVectorType>(getType()))
453 return nullptr;
455 if (const auto *PV = dyn_cast<PoisonValue>(this))
456 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
458 if (const auto *UV = dyn_cast<UndefValue>(this))
459 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
461 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
462 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
463 : nullptr;
465 return nullptr;
468 Constant *Constant::getAggregateElement(Constant *Elt) const {
469 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
470 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
471 // Check if the constant fits into an uint64_t.
472 if (CI->getValue().getActiveBits() > 64)
473 return nullptr;
474 return getAggregateElement(CI->getZExtValue());
476 return nullptr;
479 void Constant::destroyConstant() {
480 /// First call destroyConstantImpl on the subclass. This gives the subclass
481 /// a chance to remove the constant from any maps/pools it's contained in.
482 switch (getValueID()) {
483 default:
484 llvm_unreachable("Not a constant!");
485 #define HANDLE_CONSTANT(Name) \
486 case Value::Name##Val: \
487 cast<Name>(this)->destroyConstantImpl(); \
488 break;
489 #include "llvm/IR/Value.def"
492 // When a Constant is destroyed, there may be lingering
493 // references to the constant by other constants in the constant pool. These
494 // constants are implicitly dependent on the module that is being deleted,
495 // but they don't know that. Because we only find out when the CPV is
496 // deleted, we must now notify all of our users (that should only be
497 // Constants) that they are, in fact, invalid now and should be deleted.
499 while (!use_empty()) {
500 Value *V = user_back();
501 #ifndef NDEBUG // Only in -g mode...
502 if (!isa<Constant>(V)) {
503 dbgs() << "While deleting: " << *this
504 << "\n\nUse still stuck around after Def is destroyed: " << *V
505 << "\n\n";
507 #endif
508 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
509 cast<Constant>(V)->destroyConstant();
511 // The constant should remove itself from our use list...
512 assert((use_empty() || user_back() != V) && "Constant not removed!");
515 // Value has no outstanding references it is safe to delete it now...
516 deleteConstant(this);
519 void llvm::deleteConstant(Constant *C) {
520 switch (C->getValueID()) {
521 case Constant::ConstantIntVal:
522 delete static_cast<ConstantInt *>(C);
523 break;
524 case Constant::ConstantFPVal:
525 delete static_cast<ConstantFP *>(C);
526 break;
527 case Constant::ConstantAggregateZeroVal:
528 delete static_cast<ConstantAggregateZero *>(C);
529 break;
530 case Constant::ConstantArrayVal:
531 delete static_cast<ConstantArray *>(C);
532 break;
533 case Constant::ConstantStructVal:
534 delete static_cast<ConstantStruct *>(C);
535 break;
536 case Constant::ConstantVectorVal:
537 delete static_cast<ConstantVector *>(C);
538 break;
539 case Constant::ConstantPointerNullVal:
540 delete static_cast<ConstantPointerNull *>(C);
541 break;
542 case Constant::ConstantDataArrayVal:
543 delete static_cast<ConstantDataArray *>(C);
544 break;
545 case Constant::ConstantDataVectorVal:
546 delete static_cast<ConstantDataVector *>(C);
547 break;
548 case Constant::ConstantTokenNoneVal:
549 delete static_cast<ConstantTokenNone *>(C);
550 break;
551 case Constant::BlockAddressVal:
552 delete static_cast<BlockAddress *>(C);
553 break;
554 case Constant::DSOLocalEquivalentVal:
555 delete static_cast<DSOLocalEquivalent *>(C);
556 break;
557 case Constant::NoCFIValueVal:
558 delete static_cast<NoCFIValue *>(C);
559 break;
560 case Constant::ConstantPtrAuthVal:
561 delete static_cast<ConstantPtrAuth *>(C);
562 break;
563 case Constant::UndefValueVal:
564 delete static_cast<UndefValue *>(C);
565 break;
566 case Constant::PoisonValueVal:
567 delete static_cast<PoisonValue *>(C);
568 break;
569 case Constant::ConstantExprVal:
570 if (isa<CastConstantExpr>(C))
571 delete static_cast<CastConstantExpr *>(C);
572 else if (isa<BinaryConstantExpr>(C))
573 delete static_cast<BinaryConstantExpr *>(C);
574 else if (isa<ExtractElementConstantExpr>(C))
575 delete static_cast<ExtractElementConstantExpr *>(C);
576 else if (isa<InsertElementConstantExpr>(C))
577 delete static_cast<InsertElementConstantExpr *>(C);
578 else if (isa<ShuffleVectorConstantExpr>(C))
579 delete static_cast<ShuffleVectorConstantExpr *>(C);
580 else if (isa<GetElementPtrConstantExpr>(C))
581 delete static_cast<GetElementPtrConstantExpr *>(C);
582 else
583 llvm_unreachable("Unexpected constant expr");
584 break;
585 default:
586 llvm_unreachable("Unexpected constant");
590 /// Check if C contains a GlobalValue for which Predicate is true.
591 static bool
592 ConstHasGlobalValuePredicate(const Constant *C,
593 bool (*Predicate)(const GlobalValue *)) {
594 SmallPtrSet<const Constant *, 8> Visited;
595 SmallVector<const Constant *, 8> WorkList;
596 WorkList.push_back(C);
597 Visited.insert(C);
599 while (!WorkList.empty()) {
600 const Constant *WorkItem = WorkList.pop_back_val();
601 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
602 if (Predicate(GV))
603 return true;
604 for (const Value *Op : WorkItem->operands()) {
605 const Constant *ConstOp = dyn_cast<Constant>(Op);
606 if (!ConstOp)
607 continue;
608 if (Visited.insert(ConstOp).second)
609 WorkList.push_back(ConstOp);
612 return false;
615 bool Constant::isThreadDependent() const {
616 auto DLLImportPredicate = [](const GlobalValue *GV) {
617 return GV->isThreadLocal();
619 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
622 bool Constant::isDLLImportDependent() const {
623 auto DLLImportPredicate = [](const GlobalValue *GV) {
624 return GV->hasDLLImportStorageClass();
626 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
629 bool Constant::isConstantUsed() const {
630 for (const User *U : users()) {
631 const Constant *UC = dyn_cast<Constant>(U);
632 if (!UC || isa<GlobalValue>(UC))
633 return true;
635 if (UC->isConstantUsed())
636 return true;
638 return false;
641 bool Constant::needsDynamicRelocation() const {
642 return getRelocationInfo() == GlobalRelocation;
645 bool Constant::needsRelocation() const {
646 return getRelocationInfo() != NoRelocation;
649 Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
650 if (isa<GlobalValue>(this))
651 return GlobalRelocation; // Global reference.
653 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
654 return BA->getFunction()->getRelocationInfo();
656 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
657 if (CE->getOpcode() == Instruction::Sub) {
658 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
659 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
660 if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
661 RHS->getOpcode() == Instruction::PtrToInt) {
662 Constant *LHSOp0 = LHS->getOperand(0);
663 Constant *RHSOp0 = RHS->getOperand(0);
665 // While raw uses of blockaddress need to be relocated, differences
666 // between two of them don't when they are for labels in the same
667 // function. This is a common idiom when creating a table for the
668 // indirect goto extension, so we handle it efficiently here.
669 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
670 cast<BlockAddress>(LHSOp0)->getFunction() ==
671 cast<BlockAddress>(RHSOp0)->getFunction())
672 return NoRelocation;
674 // Relative pointers do not need to be dynamically relocated.
675 if (auto *RHSGV =
676 dyn_cast<GlobalValue>(RHSOp0->stripInBoundsConstantOffsets())) {
677 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
678 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
679 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
680 return LocalRelocation;
681 } else if (isa<DSOLocalEquivalent>(LHS)) {
682 if (RHSGV->isDSOLocal())
683 return LocalRelocation;
690 PossibleRelocationsTy Result = NoRelocation;
691 for (const Value *Op : operands())
692 Result = std::max(cast<Constant>(Op)->getRelocationInfo(), Result);
694 return Result;
697 /// Return true if the specified constantexpr is dead. This involves
698 /// recursively traversing users of the constantexpr.
699 /// If RemoveDeadUsers is true, also remove dead users at the same time.
700 static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
701 if (isa<GlobalValue>(C)) return false; // Cannot remove this
703 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
704 while (I != E) {
705 const Constant *User = dyn_cast<Constant>(*I);
706 if (!User) return false; // Non-constant usage;
707 if (!constantIsDead(User, RemoveDeadUsers))
708 return false; // Constant wasn't dead
710 // Just removed User, so the iterator was invalidated.
711 // Since we return immediately upon finding a live user, we can always
712 // restart from user_begin().
713 if (RemoveDeadUsers)
714 I = C->user_begin();
715 else
716 ++I;
719 if (RemoveDeadUsers) {
720 // If C is only used by metadata, it should not be preserved but should
721 // have its uses replaced.
722 ReplaceableMetadataImpl::SalvageDebugInfo(*C);
723 const_cast<Constant *>(C)->destroyConstant();
726 return true;
729 void Constant::removeDeadConstantUsers() const {
730 Value::const_user_iterator I = user_begin(), E = user_end();
731 Value::const_user_iterator LastNonDeadUser = E;
732 while (I != E) {
733 const Constant *User = dyn_cast<Constant>(*I);
734 if (!User) {
735 LastNonDeadUser = I;
736 ++I;
737 continue;
740 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
741 // If the constant wasn't dead, remember that this was the last live use
742 // and move on to the next constant.
743 LastNonDeadUser = I;
744 ++I;
745 continue;
748 // If the constant was dead, then the iterator is invalidated.
749 if (LastNonDeadUser == E)
750 I = user_begin();
751 else
752 I = std::next(LastNonDeadUser);
756 bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
758 bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
760 bool Constant::hasNLiveUses(unsigned N) const {
761 unsigned NumUses = 0;
762 for (const Use &U : uses()) {
763 const Constant *User = dyn_cast<Constant>(U.getUser());
764 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
765 ++NumUses;
767 if (NumUses > N)
768 return false;
771 return NumUses == N;
774 Constant *Constant::replaceUndefsWith(Constant *C, Constant *Replacement) {
775 assert(C && Replacement && "Expected non-nullptr constant arguments");
776 Type *Ty = C->getType();
777 if (match(C, m_Undef())) {
778 assert(Ty == Replacement->getType() && "Expected matching types");
779 return Replacement;
782 // Don't know how to deal with this constant.
783 auto *VTy = dyn_cast<FixedVectorType>(Ty);
784 if (!VTy)
785 return C;
787 unsigned NumElts = VTy->getNumElements();
788 SmallVector<Constant *, 32> NewC(NumElts);
789 for (unsigned i = 0; i != NumElts; ++i) {
790 Constant *EltC = C->getAggregateElement(i);
791 assert((!EltC || EltC->getType() == Replacement->getType()) &&
792 "Expected matching types");
793 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
795 return ConstantVector::get(NewC);
798 Constant *Constant::mergeUndefsWith(Constant *C, Constant *Other) {
799 assert(C && Other && "Expected non-nullptr constant arguments");
800 if (match(C, m_Undef()))
801 return C;
803 Type *Ty = C->getType();
804 if (match(Other, m_Undef()))
805 return UndefValue::get(Ty);
807 auto *VTy = dyn_cast<FixedVectorType>(Ty);
808 if (!VTy)
809 return C;
811 Type *EltTy = VTy->getElementType();
812 unsigned NumElts = VTy->getNumElements();
813 assert(isa<FixedVectorType>(Other->getType()) &&
814 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
815 "Type mismatch");
817 bool FoundExtraUndef = false;
818 SmallVector<Constant *, 32> NewC(NumElts);
819 for (unsigned I = 0; I != NumElts; ++I) {
820 NewC[I] = C->getAggregateElement(I);
821 Constant *OtherEltC = Other->getAggregateElement(I);
822 assert(NewC[I] && OtherEltC && "Unknown vector element");
823 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
824 NewC[I] = UndefValue::get(EltTy);
825 FoundExtraUndef = true;
828 if (FoundExtraUndef)
829 return ConstantVector::get(NewC);
830 return C;
833 bool Constant::isManifestConstant() const {
834 if (isa<ConstantData>(this))
835 return true;
836 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
837 for (const Value *Op : operand_values())
838 if (!cast<Constant>(Op)->isManifestConstant())
839 return false;
840 return true;
842 return false;
845 //===----------------------------------------------------------------------===//
846 // ConstantInt
847 //===----------------------------------------------------------------------===//
849 ConstantInt::ConstantInt(Type *Ty, const APInt &V)
850 : ConstantData(Ty, ConstantIntVal), Val(V) {
851 assert(V.getBitWidth() ==
852 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
853 "Invalid constant for type");
856 ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
857 LLVMContextImpl *pImpl = Context.pImpl;
858 if (!pImpl->TheTrueVal)
859 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
860 return pImpl->TheTrueVal;
863 ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
864 LLVMContextImpl *pImpl = Context.pImpl;
865 if (!pImpl->TheFalseVal)
866 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
867 return pImpl->TheFalseVal;
870 ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
871 return V ? getTrue(Context) : getFalse(Context);
874 Constant *ConstantInt::getTrue(Type *Ty) {
875 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
876 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
877 if (auto *VTy = dyn_cast<VectorType>(Ty))
878 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
879 return TrueC;
882 Constant *ConstantInt::getFalse(Type *Ty) {
883 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
884 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
885 if (auto *VTy = dyn_cast<VectorType>(Ty))
886 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
887 return FalseC;
890 Constant *ConstantInt::getBool(Type *Ty, bool V) {
891 return V ? getTrue(Ty) : getFalse(Ty);
894 // Get a ConstantInt from an APInt.
895 ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
896 // get an existing value or the insertion position
897 LLVMContextImpl *pImpl = Context.pImpl;
898 std::unique_ptr<ConstantInt> &Slot =
899 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
900 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
901 : pImpl->IntConstants[V];
902 if (!Slot) {
903 // Get the corresponding integer type for the bit width of the value.
904 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
905 Slot.reset(new ConstantInt(ITy, V));
907 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
908 return Slot.get();
911 // Get a ConstantInt vector with each lane set to the same APInt.
912 ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
913 const APInt &V) {
914 // Get an existing value or the insertion position.
915 std::unique_ptr<ConstantInt> &Slot =
916 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
917 if (!Slot) {
918 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
919 VectorType *VTy = VectorType::get(ITy, EC);
920 Slot.reset(new ConstantInt(VTy, V));
923 #ifndef NDEBUG
924 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
925 VectorType *VTy = VectorType::get(ITy, EC);
926 assert(Slot->getType() == VTy);
927 #endif
928 return Slot.get();
931 Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
932 Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
934 // For vectors, broadcast the value.
935 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
936 return ConstantVector::getSplat(VTy->getElementCount(), C);
938 return C;
941 ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
942 // TODO: Avoid implicit trunc?
943 // See https://github.com/llvm/llvm-project/issues/112510.
944 return get(Ty->getContext(),
945 APInt(Ty->getBitWidth(), V, isSigned, /*implicitTrunc=*/true));
948 Constant *ConstantInt::get(Type *Ty, const APInt& V) {
949 ConstantInt *C = get(Ty->getContext(), V);
950 assert(C->getType() == Ty->getScalarType() &&
951 "ConstantInt type doesn't match the type implied by its value!");
953 // For vectors, broadcast the value.
954 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
955 return ConstantVector::getSplat(VTy->getElementCount(), C);
957 return C;
960 ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
961 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
964 /// Remove the constant from the constant table.
965 void ConstantInt::destroyConstantImpl() {
966 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
969 //===----------------------------------------------------------------------===//
970 // ConstantFP
971 //===----------------------------------------------------------------------===//
973 Constant *ConstantFP::get(Type *Ty, double V) {
974 LLVMContext &Context = Ty->getContext();
976 APFloat FV(V);
977 bool ignored;
978 FV.convert(Ty->getScalarType()->getFltSemantics(),
979 APFloat::rmNearestTiesToEven, &ignored);
980 Constant *C = get(Context, FV);
982 // For vectors, broadcast the value.
983 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
984 return ConstantVector::getSplat(VTy->getElementCount(), C);
986 return C;
989 Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
990 ConstantFP *C = get(Ty->getContext(), V);
991 assert(C->getType() == Ty->getScalarType() &&
992 "ConstantFP type doesn't match the type implied by its value!");
994 // For vectors, broadcast the value.
995 if (auto *VTy = dyn_cast<VectorType>(Ty))
996 return ConstantVector::getSplat(VTy->getElementCount(), C);
998 return C;
1001 Constant *ConstantFP::get(Type *Ty, StringRef Str) {
1002 LLVMContext &Context = Ty->getContext();
1004 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1005 Constant *C = get(Context, FV);
1007 // For vectors, broadcast the value.
1008 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1009 return ConstantVector::getSplat(VTy->getElementCount(), C);
1011 return C;
1014 Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1015 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1016 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1017 Constant *C = get(Ty->getContext(), NaN);
1019 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1020 return ConstantVector::getSplat(VTy->getElementCount(), C);
1022 return C;
1025 Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1026 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1027 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1028 Constant *C = get(Ty->getContext(), NaN);
1030 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1031 return ConstantVector::getSplat(VTy->getElementCount(), C);
1033 return C;
1036 Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1037 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1038 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1039 Constant *C = get(Ty->getContext(), NaN);
1041 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1042 return ConstantVector::getSplat(VTy->getElementCount(), C);
1044 return C;
1047 Constant *ConstantFP::getZero(Type *Ty, bool Negative) {
1048 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1049 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1050 Constant *C = get(Ty->getContext(), NegZero);
1052 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1053 return ConstantVector::getSplat(VTy->getElementCount(), C);
1055 return C;
1059 // ConstantFP accessors.
1060 ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1061 LLVMContextImpl* pImpl = Context.pImpl;
1063 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1065 if (!Slot) {
1066 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1067 Slot.reset(new ConstantFP(Ty, V));
1070 return Slot.get();
1073 // Get a ConstantFP vector with each lane set to the same APFloat.
1074 ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1075 const APFloat &V) {
1076 // Get an existing value or the insertion position.
1077 std::unique_ptr<ConstantFP> &Slot =
1078 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1079 if (!Slot) {
1080 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1081 VectorType *VTy = VectorType::get(EltTy, EC);
1082 Slot.reset(new ConstantFP(VTy, V));
1085 #ifndef NDEBUG
1086 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1087 VectorType *VTy = VectorType::get(EltTy, EC);
1088 assert(Slot->getType() == VTy);
1089 #endif
1090 return Slot.get();
1093 Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1094 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1095 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
1097 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1098 return ConstantVector::getSplat(VTy->getElementCount(), C);
1100 return C;
1103 ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1104 : ConstantData(Ty, ConstantFPVal), Val(V) {
1105 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1106 "FP type Mismatch");
1109 bool ConstantFP::isExactlyValue(const APFloat &V) const {
1110 return Val.bitwiseIsEqual(V);
1113 /// Remove the constant from the constant table.
1114 void ConstantFP::destroyConstantImpl() {
1115 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1118 //===----------------------------------------------------------------------===//
1119 // ConstantAggregateZero Implementation
1120 //===----------------------------------------------------------------------===//
1122 Constant *ConstantAggregateZero::getSequentialElement() const {
1123 if (auto *AT = dyn_cast<ArrayType>(getType()))
1124 return Constant::getNullValue(AT->getElementType());
1125 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1128 Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
1129 return Constant::getNullValue(getType()->getStructElementType(Elt));
1132 Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
1133 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1134 return getSequentialElement();
1135 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1138 Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
1139 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1140 return getSequentialElement();
1141 return getStructElement(Idx);
1144 ElementCount ConstantAggregateZero::getElementCount() const {
1145 Type *Ty = getType();
1146 if (auto *AT = dyn_cast<ArrayType>(Ty))
1147 return ElementCount::getFixed(AT->getNumElements());
1148 if (auto *VT = dyn_cast<VectorType>(Ty))
1149 return VT->getElementCount();
1150 return ElementCount::getFixed(Ty->getStructNumElements());
1153 //===----------------------------------------------------------------------===//
1154 // UndefValue Implementation
1155 //===----------------------------------------------------------------------===//
1157 UndefValue *UndefValue::getSequentialElement() const {
1158 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1159 return UndefValue::get(ATy->getElementType());
1160 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1163 UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1164 return UndefValue::get(getType()->getStructElementType(Elt));
1167 UndefValue *UndefValue::getElementValue(Constant *C) const {
1168 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1169 return getSequentialElement();
1170 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1173 UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1174 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1175 return getSequentialElement();
1176 return getStructElement(Idx);
1179 unsigned UndefValue::getNumElements() const {
1180 Type *Ty = getType();
1181 if (auto *AT = dyn_cast<ArrayType>(Ty))
1182 return AT->getNumElements();
1183 if (auto *VT = dyn_cast<VectorType>(Ty))
1184 return cast<FixedVectorType>(VT)->getNumElements();
1185 return Ty->getStructNumElements();
1188 //===----------------------------------------------------------------------===//
1189 // PoisonValue Implementation
1190 //===----------------------------------------------------------------------===//
1192 PoisonValue *PoisonValue::getSequentialElement() const {
1193 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
1194 return PoisonValue::get(ATy->getElementType());
1195 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1198 PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1199 return PoisonValue::get(getType()->getStructElementType(Elt));
1202 PoisonValue *PoisonValue::getElementValue(Constant *C) const {
1203 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1204 return getSequentialElement();
1205 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1208 PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1209 if (isa<ArrayType>(getType()) || isa<VectorType>(getType()))
1210 return getSequentialElement();
1211 return getStructElement(Idx);
1214 //===----------------------------------------------------------------------===//
1215 // ConstantXXX Classes
1216 //===----------------------------------------------------------------------===//
1218 template <typename ItTy, typename EltTy>
1219 static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1220 for (; Start != End; ++Start)
1221 if (*Start != Elt)
1222 return false;
1223 return true;
1226 template <typename SequentialTy, typename ElementTy>
1227 static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1228 assert(!V.empty() && "Cannot get empty int sequence.");
1230 SmallVector<ElementTy, 16> Elts;
1231 for (Constant *C : V)
1232 if (auto *CI = dyn_cast<ConstantInt>(C))
1233 Elts.push_back(CI->getZExtValue());
1234 else
1235 return nullptr;
1236 return SequentialTy::get(V[0]->getContext(), Elts);
1239 template <typename SequentialTy, typename ElementTy>
1240 static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
1241 assert(!V.empty() && "Cannot get empty FP sequence.");
1243 SmallVector<ElementTy, 16> Elts;
1244 for (Constant *C : V)
1245 if (auto *CFP = dyn_cast<ConstantFP>(C))
1246 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1247 else
1248 return nullptr;
1249 return SequentialTy::getFP(V[0]->getType(), Elts);
1252 template <typename SequenceTy>
1253 static Constant *getSequenceIfElementsMatch(Constant *C,
1254 ArrayRef<Constant *> V) {
1255 // We speculatively build the elements here even if it turns out that there is
1256 // a constantexpr or something else weird, since it is so uncommon for that to
1257 // happen.
1258 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1259 if (CI->getType()->isIntegerTy(8))
1260 return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
1261 else if (CI->getType()->isIntegerTy(16))
1262 return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1263 else if (CI->getType()->isIntegerTy(32))
1264 return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1265 else if (CI->getType()->isIntegerTy(64))
1266 return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1267 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1268 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1269 return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
1270 else if (CFP->getType()->isFloatTy())
1271 return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
1272 else if (CFP->getType()->isDoubleTy())
1273 return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
1276 return nullptr;
1279 ConstantAggregate::ConstantAggregate(Type *T, ValueTy VT,
1280 ArrayRef<Constant *> V,
1281 AllocInfo AllocInfo)
1282 : Constant(T, VT, AllocInfo) {
1283 llvm::copy(V, op_begin());
1285 // Check that types match, unless this is an opaque struct.
1286 if (auto *ST = dyn_cast<StructType>(T)) {
1287 if (ST->isOpaque())
1288 return;
1289 for (unsigned I = 0, E = V.size(); I != E; ++I)
1290 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1291 "Initializer for struct element doesn't match!");
1295 ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1296 AllocInfo AllocInfo)
1297 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1298 assert(V.size() == T->getNumElements() &&
1299 "Invalid initializer for constant array");
1302 Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
1303 if (Constant *C = getImpl(Ty, V))
1304 return C;
1305 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1308 Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1309 // Empty arrays are canonicalized to ConstantAggregateZero.
1310 if (V.empty())
1311 return ConstantAggregateZero::get(Ty);
1313 for (Constant *C : V) {
1314 assert(C->getType() == Ty->getElementType() &&
1315 "Wrong type in array element initializer");
1316 (void)C;
1319 // If this is an all-zero array, return a ConstantAggregateZero object. If
1320 // all undef, return an UndefValue, if "all simple", then return a
1321 // ConstantDataArray.
1322 Constant *C = V[0];
1323 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1324 return PoisonValue::get(Ty);
1326 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1327 return UndefValue::get(Ty);
1329 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1330 return ConstantAggregateZero::get(Ty);
1332 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1333 // the element type is compatible with ConstantDataVector. If so, use it.
1334 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1335 return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
1337 // Otherwise, we really do want to create a ConstantArray.
1338 return nullptr;
1341 StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
1342 ArrayRef<Constant*> V,
1343 bool Packed) {
1344 unsigned VecSize = V.size();
1345 SmallVector<Type*, 16> EltTypes(VecSize);
1346 for (unsigned i = 0; i != VecSize; ++i)
1347 EltTypes[i] = V[i]->getType();
1349 return StructType::get(Context, EltTypes, Packed);
1353 StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
1354 bool Packed) {
1355 assert(!V.empty() &&
1356 "ConstantStruct::getTypeForElements cannot be called on empty list");
1357 return getTypeForElements(V[0]->getContext(), V, Packed);
1360 ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1361 AllocInfo AllocInfo)
1362 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1363 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1364 "Invalid initializer for constant struct");
1367 // ConstantStruct accessors.
1368 Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
1369 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1370 "Incorrect # elements specified to ConstantStruct::get");
1372 // Create a ConstantAggregateZero value if all elements are zeros.
1373 bool isZero = true;
1374 bool isUndef = false;
1375 bool isPoison = false;
1377 if (!V.empty()) {
1378 isUndef = isa<UndefValue>(V[0]);
1379 isPoison = isa<PoisonValue>(V[0]);
1380 isZero = V[0]->isNullValue();
1381 // PoisonValue inherits UndefValue, so its check is not necessary.
1382 if (isUndef || isZero) {
1383 for (Constant *C : V) {
1384 if (!C->isNullValue())
1385 isZero = false;
1386 if (!isa<PoisonValue>(C))
1387 isPoison = false;
1388 if (isa<PoisonValue>(C) || !isa<UndefValue>(C))
1389 isUndef = false;
1393 if (isZero)
1394 return ConstantAggregateZero::get(ST);
1395 if (isPoison)
1396 return PoisonValue::get(ST);
1397 if (isUndef)
1398 return UndefValue::get(ST);
1400 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1403 ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1404 AllocInfo AllocInfo)
1405 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1406 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1407 "Invalid initializer for constant vector");
1410 // ConstantVector accessors.
1411 Constant *ConstantVector::get(ArrayRef<Constant*> V) {
1412 if (Constant *C = getImpl(V))
1413 return C;
1414 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1415 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1418 Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1419 assert(!V.empty() && "Vectors can't be empty");
1420 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1422 // If this is an all-undef or all-zero vector, return a
1423 // ConstantAggregateZero or UndefValue.
1424 Constant *C = V[0];
1425 bool isZero = C->isNullValue();
1426 bool isUndef = isa<UndefValue>(C);
1427 bool isPoison = isa<PoisonValue>(C);
1428 bool isSplatFP = UseConstantFPForFixedLengthSplat && isa<ConstantFP>(C);
1429 bool isSplatInt = UseConstantIntForFixedLengthSplat && isa<ConstantInt>(C);
1431 if (isZero || isUndef || isSplatFP || isSplatInt) {
1432 for (unsigned i = 1, e = V.size(); i != e; ++i)
1433 if (V[i] != C) {
1434 isZero = isUndef = isPoison = isSplatFP = isSplatInt = false;
1435 break;
1439 if (isZero)
1440 return ConstantAggregateZero::get(T);
1441 if (isPoison)
1442 return PoisonValue::get(T);
1443 if (isUndef)
1444 return UndefValue::get(T);
1445 if (isSplatFP)
1446 return ConstantFP::get(C->getContext(), T->getElementCount(),
1447 cast<ConstantFP>(C)->getValue());
1448 if (isSplatInt)
1449 return ConstantInt::get(C->getContext(), T->getElementCount(),
1450 cast<ConstantInt>(C)->getValue());
1452 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1453 // the element type is compatible with ConstantDataVector. If so, use it.
1454 if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
1455 return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
1457 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1458 // the operand list contains a ConstantExpr or something else strange.
1459 return nullptr;
1462 Constant *ConstantVector::getSplat(ElementCount EC, Constant *V) {
1463 if (!EC.isScalable()) {
1464 // Maintain special handling of zero.
1465 if (!V->isNullValue()) {
1466 if (UseConstantIntForFixedLengthSplat && isa<ConstantInt>(V))
1467 return ConstantInt::get(V->getContext(), EC,
1468 cast<ConstantInt>(V)->getValue());
1469 if (UseConstantFPForFixedLengthSplat && isa<ConstantFP>(V))
1470 return ConstantFP::get(V->getContext(), EC,
1471 cast<ConstantFP>(V)->getValue());
1474 // If this splat is compatible with ConstantDataVector, use it instead of
1475 // ConstantVector.
1476 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1477 ConstantDataSequential::isElementTypeCompatible(V->getType()))
1478 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1480 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1481 return get(Elts);
1484 // Maintain special handling of zero.
1485 if (!V->isNullValue()) {
1486 if (UseConstantIntForScalableSplat && isa<ConstantInt>(V))
1487 return ConstantInt::get(V->getContext(), EC,
1488 cast<ConstantInt>(V)->getValue());
1489 if (UseConstantFPForScalableSplat && isa<ConstantFP>(V))
1490 return ConstantFP::get(V->getContext(), EC,
1491 cast<ConstantFP>(V)->getValue());
1494 Type *VTy = VectorType::get(V->getType(), EC);
1496 if (V->isNullValue())
1497 return ConstantAggregateZero::get(VTy);
1498 else if (isa<UndefValue>(V))
1499 return UndefValue::get(VTy);
1501 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1503 // Move scalar into vector.
1504 Constant *PoisonV = PoisonValue::get(VTy);
1505 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1506 // Build shuffle mask to perform the splat.
1507 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1508 // Splat.
1509 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1512 ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1513 LLVMContextImpl *pImpl = Context.pImpl;
1514 if (!pImpl->TheNoneToken)
1515 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1516 return pImpl->TheNoneToken.get();
1519 /// Remove the constant from the constant table.
1520 void ConstantTokenNone::destroyConstantImpl() {
1521 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1524 // Utility function for determining if a ConstantExpr is a CastOp or not. This
1525 // can't be inline because we don't want to #include Instruction.h into
1526 // Constant.h
1527 bool ConstantExpr::isCast() const { return Instruction::isCast(getOpcode()); }
1529 ArrayRef<int> ConstantExpr::getShuffleMask() const {
1530 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMask;
1533 Constant *ConstantExpr::getShuffleMaskForBitcode() const {
1534 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1537 Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1538 bool OnlyIfReduced, Type *SrcTy) const {
1539 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1541 // If no operands changed return self.
1542 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1543 return const_cast<ConstantExpr*>(this);
1545 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1546 switch (getOpcode()) {
1547 case Instruction::Trunc:
1548 case Instruction::ZExt:
1549 case Instruction::SExt:
1550 case Instruction::FPTrunc:
1551 case Instruction::FPExt:
1552 case Instruction::UIToFP:
1553 case Instruction::SIToFP:
1554 case Instruction::FPToUI:
1555 case Instruction::FPToSI:
1556 case Instruction::PtrToInt:
1557 case Instruction::IntToPtr:
1558 case Instruction::BitCast:
1559 case Instruction::AddrSpaceCast:
1560 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1561 case Instruction::InsertElement:
1562 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1563 OnlyIfReducedTy);
1564 case Instruction::ExtractElement:
1565 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1566 case Instruction::ShuffleVector:
1567 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], getShuffleMask(),
1568 OnlyIfReducedTy);
1569 case Instruction::GetElementPtr: {
1570 auto *GEPO = cast<GEPOperator>(this);
1571 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1572 return ConstantExpr::getGetElementPtr(
1573 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1574 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1576 default:
1577 assert(getNumOperands() == 2 && "Must be binary operator?");
1578 return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
1579 OnlyIfReducedTy);
1584 //===----------------------------------------------------------------------===//
1585 // isValueValidForType implementations
1587 bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
1588 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1589 if (Ty->isIntegerTy(1))
1590 return Val == 0 || Val == 1;
1591 return isUIntN(NumBits, Val);
1594 bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
1595 unsigned NumBits = Ty->getIntegerBitWidth();
1596 if (Ty->isIntegerTy(1))
1597 return Val == 0 || Val == 1 || Val == -1;
1598 return isIntN(NumBits, Val);
1601 bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
1602 // convert modifies in place, so make a copy.
1603 APFloat Val2 = APFloat(Val);
1604 bool losesInfo;
1605 switch (Ty->getTypeID()) {
1606 default:
1607 return false; // These can't be represented as floating point!
1609 // FIXME rounding mode needs to be more flexible
1610 case Type::HalfTyID: {
1611 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1612 return true;
1613 Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
1614 return !losesInfo;
1616 case Type::BFloatTyID: {
1617 if (&Val2.getSemantics() == &APFloat::BFloat())
1618 return true;
1619 Val2.convert(APFloat::BFloat(), APFloat::rmNearestTiesToEven, &losesInfo);
1620 return !losesInfo;
1622 case Type::FloatTyID: {
1623 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1624 return true;
1625 Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
1626 return !losesInfo;
1628 case Type::DoubleTyID: {
1629 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1630 &Val2.getSemantics() == &APFloat::BFloat() ||
1631 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1632 &Val2.getSemantics() == &APFloat::IEEEdouble())
1633 return true;
1634 Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
1635 return !losesInfo;
1637 case Type::X86_FP80TyID:
1638 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1639 &Val2.getSemantics() == &APFloat::BFloat() ||
1640 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1641 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1642 &Val2.getSemantics() == &APFloat::x87DoubleExtended();
1643 case Type::FP128TyID:
1644 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1645 &Val2.getSemantics() == &APFloat::BFloat() ||
1646 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1647 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1648 &Val2.getSemantics() == &APFloat::IEEEquad();
1649 case Type::PPC_FP128TyID:
1650 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1651 &Val2.getSemantics() == &APFloat::BFloat() ||
1652 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1653 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1654 &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
1659 //===----------------------------------------------------------------------===//
1660 // Factory Function Implementation
1662 ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1663 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1664 "Cannot create an aggregate zero of non-aggregate type!");
1666 std::unique_ptr<ConstantAggregateZero> &Entry =
1667 Ty->getContext().pImpl->CAZConstants[Ty];
1668 if (!Entry)
1669 Entry.reset(new ConstantAggregateZero(Ty));
1671 return Entry.get();
1674 /// Remove the constant from the constant table.
1675 void ConstantAggregateZero::destroyConstantImpl() {
1676 getContext().pImpl->CAZConstants.erase(getType());
1679 /// Remove the constant from the constant table.
1680 void ConstantArray::destroyConstantImpl() {
1681 getType()->getContext().pImpl->ArrayConstants.remove(this);
1685 //---- ConstantStruct::get() implementation...
1688 /// Remove the constant from the constant table.
1689 void ConstantStruct::destroyConstantImpl() {
1690 getType()->getContext().pImpl->StructConstants.remove(this);
1693 /// Remove the constant from the constant table.
1694 void ConstantVector::destroyConstantImpl() {
1695 getType()->getContext().pImpl->VectorConstants.remove(this);
1698 Constant *Constant::getSplatValue(bool AllowPoison) const {
1699 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1700 if (isa<ConstantAggregateZero>(this))
1701 return getNullValue(cast<VectorType>(getType())->getElementType());
1702 if (auto *CI = dyn_cast<ConstantInt>(this))
1703 return ConstantInt::get(getContext(), CI->getValue());
1704 if (auto *CFP = dyn_cast<ConstantFP>(this))
1705 return ConstantFP::get(getContext(), CFP->getValue());
1706 if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
1707 return CV->getSplatValue();
1708 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1709 return CV->getSplatValue(AllowPoison);
1711 // Check if this is a constant expression splat of the form returned by
1712 // ConstantVector::getSplat()
1713 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1714 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1715 isa<UndefValue>(Shuf->getOperand(1))) {
1717 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1718 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1719 isa<UndefValue>(IElt->getOperand(0))) {
1721 ArrayRef<int> Mask = Shuf->getShuffleMask();
1722 Constant *SplatVal = IElt->getOperand(1);
1723 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1725 if (Index && Index->getValue() == 0 &&
1726 llvm::all_of(Mask, [](int I) { return I == 0; }))
1727 return SplatVal;
1731 return nullptr;
1734 Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1735 // Check out first element.
1736 Constant *Elt = getOperand(0);
1737 // Then make sure all remaining elements point to the same value.
1738 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1739 Constant *OpC = getOperand(I);
1740 if (OpC == Elt)
1741 continue;
1743 // Strict mode: any mismatch is not a splat.
1744 if (!AllowPoison)
1745 return nullptr;
1747 // Allow poison mode: ignore poison elements.
1748 if (isa<PoisonValue>(OpC))
1749 continue;
1751 // If we do not have a defined element yet, use the current operand.
1752 if (isa<PoisonValue>(Elt))
1753 Elt = OpC;
1755 if (OpC != Elt)
1756 return nullptr;
1758 return Elt;
1761 const APInt &Constant::getUniqueInteger() const {
1762 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1763 return CI->getValue();
1764 // Scalable vectors can use a ConstantExpr to build a splat.
1765 if (isa<ConstantExpr>(this))
1766 return cast<ConstantInt>(this->getSplatValue())->getValue();
1767 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1768 // calling getSplatValue in release builds.
1769 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1770 const Constant *C = this->getAggregateElement(0U);
1771 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1772 return cast<ConstantInt>(C)->getValue();
1775 ConstantRange Constant::toConstantRange() const {
1776 if (auto *CI = dyn_cast<ConstantInt>(this))
1777 return ConstantRange(CI->getValue());
1779 unsigned BitWidth = getType()->getScalarSizeInBits();
1780 if (!getType()->isVectorTy())
1781 return ConstantRange::getFull(BitWidth);
1783 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1784 getSplatValue(/*AllowPoison=*/true)))
1785 return ConstantRange(CI->getValue());
1787 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1788 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1789 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1790 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1791 return CR;
1794 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1795 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1796 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1797 Constant *Elem = CV->getOperand(I);
1798 if (!Elem)
1799 return ConstantRange::getFull(BitWidth);
1800 if (isa<PoisonValue>(Elem))
1801 continue;
1802 auto *CI = dyn_cast<ConstantInt>(Elem);
1803 if (!CI)
1804 return ConstantRange::getFull(BitWidth);
1805 CR = CR.unionWith(CI->getValue());
1807 return CR;
1810 return ConstantRange::getFull(BitWidth);
1813 //---- ConstantPointerNull::get() implementation.
1816 ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1817 std::unique_ptr<ConstantPointerNull> &Entry =
1818 Ty->getContext().pImpl->CPNConstants[Ty];
1819 if (!Entry)
1820 Entry.reset(new ConstantPointerNull(Ty));
1822 return Entry.get();
1825 /// Remove the constant from the constant table.
1826 void ConstantPointerNull::destroyConstantImpl() {
1827 getContext().pImpl->CPNConstants.erase(getType());
1830 //---- ConstantTargetNone::get() implementation.
1833 ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
1834 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
1835 "Target extension type not allowed to have a zeroinitializer");
1836 std::unique_ptr<ConstantTargetNone> &Entry =
1837 Ty->getContext().pImpl->CTNConstants[Ty];
1838 if (!Entry)
1839 Entry.reset(new ConstantTargetNone(Ty));
1841 return Entry.get();
1844 /// Remove the constant from the constant table.
1845 void ConstantTargetNone::destroyConstantImpl() {
1846 getContext().pImpl->CTNConstants.erase(getType());
1849 UndefValue *UndefValue::get(Type *Ty) {
1850 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1851 if (!Entry)
1852 Entry.reset(new UndefValue(Ty));
1854 return Entry.get();
1857 /// Remove the constant from the constant table.
1858 void UndefValue::destroyConstantImpl() {
1859 // Free the constant and any dangling references to it.
1860 if (getValueID() == UndefValueVal) {
1861 getContext().pImpl->UVConstants.erase(getType());
1862 } else if (getValueID() == PoisonValueVal) {
1863 getContext().pImpl->PVConstants.erase(getType());
1865 llvm_unreachable("Not a undef or a poison!");
1868 PoisonValue *PoisonValue::get(Type *Ty) {
1869 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1870 if (!Entry)
1871 Entry.reset(new PoisonValue(Ty));
1873 return Entry.get();
1876 /// Remove the constant from the constant table.
1877 void PoisonValue::destroyConstantImpl() {
1878 // Free the constant and any dangling references to it.
1879 getContext().pImpl->PVConstants.erase(getType());
1882 BlockAddress *BlockAddress::get(BasicBlock *BB) {
1883 assert(BB->getParent() && "Block must have a parent");
1884 return get(BB->getParent(), BB);
1887 BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
1888 BlockAddress *&BA =
1889 F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
1890 if (!BA)
1891 BA = new BlockAddress(F, BB);
1893 assert(BA->getFunction() == F && "Basic block moved between functions");
1894 return BA;
1897 BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
1898 : Constant(PointerType::get(F->getContext(), F->getAddressSpace()),
1899 Value::BlockAddressVal, AllocMarker) {
1900 setOperand(0, F);
1901 setOperand(1, BB);
1902 BB->AdjustBlockAddressRefCount(1);
1905 BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1906 if (!BB->hasAddressTaken())
1907 return nullptr;
1909 const Function *F = BB->getParent();
1910 assert(F && "Block must have a parent");
1911 BlockAddress *BA =
1912 F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
1913 assert(BA && "Refcount and block address map disagree!");
1914 return BA;
1917 /// Remove the constant from the constant table.
1918 void BlockAddress::destroyConstantImpl() {
1919 getFunction()->getType()->getContext().pImpl
1920 ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
1921 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1924 Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1925 // This could be replacing either the Basic Block or the Function. In either
1926 // case, we have to remove the map entry.
1927 Function *NewF = getFunction();
1928 BasicBlock *NewBB = getBasicBlock();
1930 if (From == NewF)
1931 NewF = cast<Function>(To->stripPointerCasts());
1932 else {
1933 assert(From == NewBB && "From does not match any operand");
1934 NewBB = cast<BasicBlock>(To);
1937 // See if the 'new' entry already exists, if not, just update this in place
1938 // and return early.
1939 BlockAddress *&NewBA =
1940 getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
1941 if (NewBA)
1942 return NewBA;
1944 getBasicBlock()->AdjustBlockAddressRefCount(-1);
1946 // Remove the old entry, this can't cause the map to rehash (just a
1947 // tombstone will get added).
1948 getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
1949 getBasicBlock()));
1950 NewBA = this;
1951 setOperand(0, NewF);
1952 setOperand(1, NewBB);
1953 getBasicBlock()->AdjustBlockAddressRefCount(1);
1955 // If we just want to keep the existing value, then return null.
1956 // Callers know that this means we shouldn't delete this value.
1957 return nullptr;
1960 DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
1961 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
1962 if (!Equiv)
1963 Equiv = new DSOLocalEquivalent(GV);
1965 assert(Equiv->getGlobalValue() == GV &&
1966 "DSOLocalFunction does not match the expected global value");
1967 return Equiv;
1970 DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1971 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
1972 setOperand(0, GV);
1975 /// Remove the constant from the constant table.
1976 void DSOLocalEquivalent::destroyConstantImpl() {
1977 const GlobalValue *GV = getGlobalValue();
1978 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
1981 Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
1982 assert(From == getGlobalValue() && "Changing value does not match operand.");
1983 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
1985 // The replacement is with another global value.
1986 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
1987 DSOLocalEquivalent *&NewEquiv =
1988 getContext().pImpl->DSOLocalEquivalents[ToObj];
1989 if (NewEquiv)
1990 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1993 // If the argument is replaced with a null value, just replace this constant
1994 // with a null value.
1995 if (cast<Constant>(To)->isNullValue())
1996 return To;
1998 // The replacement could be a bitcast or an alias to another function. We can
1999 // replace it with a bitcast to the dso_local_equivalent of that function.
2000 auto *Func = cast<Function>(To->stripPointerCastsAndAliases());
2001 DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
2002 if (NewEquiv)
2003 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2005 // Replace this with the new one.
2006 getContext().pImpl->DSOLocalEquivalents.erase(getGlobalValue());
2007 NewEquiv = this;
2008 setOperand(0, Func);
2010 if (Func->getType() != getType()) {
2011 // It is ok to mutate the type here because this constant should always
2012 // reflect the type of the function it's holding.
2013 mutateType(Func->getType());
2015 return nullptr;
2018 NoCFIValue *NoCFIValue::get(GlobalValue *GV) {
2019 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2020 if (!NC)
2021 NC = new NoCFIValue(GV);
2023 assert(NC->getGlobalValue() == GV &&
2024 "NoCFIValue does not match the expected global value");
2025 return NC;
2028 NoCFIValue::NoCFIValue(GlobalValue *GV)
2029 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2030 setOperand(0, GV);
2033 /// Remove the constant from the constant table.
2034 void NoCFIValue::destroyConstantImpl() {
2035 const GlobalValue *GV = getGlobalValue();
2036 GV->getContext().pImpl->NoCFIValues.erase(GV);
2039 Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2040 assert(From == getGlobalValue() && "Changing value does not match operand.");
2042 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2043 assert(GV && "Can only replace the operands with a global value");
2045 NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
2046 if (NewNC)
2047 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2049 getContext().pImpl->NoCFIValues.erase(getGlobalValue());
2050 NewNC = this;
2051 setOperand(0, GV);
2053 if (GV->getType() != getType())
2054 mutateType(GV->getType());
2056 return nullptr;
2059 //---- ConstantPtrAuth::get() implementations.
2062 ConstantPtrAuth *ConstantPtrAuth::get(Constant *Ptr, ConstantInt *Key,
2063 ConstantInt *Disc, Constant *AddrDisc) {
2064 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc};
2065 ConstantPtrAuthKeyType MapKey(ArgVec);
2066 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2067 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2070 ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2071 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator());
2074 ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2075 ConstantInt *Disc, Constant *AddrDisc)
2076 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2077 assert(Ptr->getType()->isPointerTy());
2078 assert(Key->getBitWidth() == 32);
2079 assert(Disc->getBitWidth() == 64);
2080 assert(AddrDisc->getType()->isPointerTy());
2081 setOperand(0, Ptr);
2082 setOperand(1, Key);
2083 setOperand(2, Disc);
2084 setOperand(3, AddrDisc);
2087 /// Remove the constant from the constant table.
2088 void ConstantPtrAuth::destroyConstantImpl() {
2089 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2092 Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2093 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2094 Constant *To = cast<Constant>(ToV);
2096 SmallVector<Constant *, 4> Values;
2097 Values.reserve(getNumOperands());
2099 unsigned NumUpdated = 0;
2101 Use *OperandList = getOperandList();
2102 unsigned OperandNo = 0;
2103 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2104 Constant *Val = cast<Constant>(O->get());
2105 if (Val == From) {
2106 OperandNo = (O - OperandList);
2107 Val = To;
2108 ++NumUpdated;
2110 Values.push_back(Val);
2113 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2114 Values, this, From, To, NumUpdated, OperandNo);
2117 bool ConstantPtrAuth::hasSpecialAddressDiscriminator(uint64_t Value) const {
2118 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2119 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2120 return false;
2122 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2123 if (!IntVal)
2124 return false;
2126 return IntVal->getValue() == Value;
2129 bool ConstantPtrAuth::isKnownCompatibleWith(const Value *Key,
2130 const Value *Discriminator,
2131 const DataLayout &DL) const {
2132 // If the keys are different, there's no chance for this to be compatible.
2133 if (getKey() != Key)
2134 return false;
2136 // We can have 3 kinds of discriminators:
2137 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2138 // - address-only: `i64 0, ptr p` vs. `ptr p`
2139 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2141 // If this constant has a simple discriminator (integer, no address), easy:
2142 // it's compatible iff the provided full discriminator is also a simple
2143 // discriminator, identical to our integer discriminator.
2144 if (!hasAddressDiscriminator())
2145 return getDiscriminator() == Discriminator;
2147 // Otherwise, we can isolate address and integer discriminator components.
2148 const Value *AddrDiscriminator = nullptr;
2150 // This constant may or may not have an integer discriminator (instead of 0).
2151 if (!getDiscriminator()->isNullValue()) {
2152 // If it does, there's an implicit blend. We need to have a matching blend
2153 // intrinsic in the provided full discriminator.
2154 if (!match(Discriminator,
2155 m_Intrinsic<Intrinsic::ptrauth_blend>(
2156 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2157 return false;
2158 } else {
2159 // Otherwise, interpret the provided full discriminator as address-only.
2160 AddrDiscriminator = Discriminator;
2163 // Either way, we can now focus on comparing the address discriminators.
2165 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2166 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2167 AddrDiscriminator = Cast->getPointerOperand();
2169 // Beyond that, we're only interested in compatible pointers.
2170 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2171 return false;
2173 // These are often the same constant GEP, making them trivially equivalent.
2174 if (getAddrDiscriminator() == AddrDiscriminator)
2175 return true;
2177 // Finally, they may be equivalent base+offset expressions.
2178 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2179 auto *Base1 = getAddrDiscriminator()->stripAndAccumulateConstantOffsets(
2180 DL, Off1, /*AllowNonInbounds=*/true);
2182 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2183 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2184 DL, Off2, /*AllowNonInbounds=*/true);
2186 return Base1 == Base2 && Off1 == Off2;
2189 //---- ConstantExpr::get() implementations.
2192 /// This is a utility function to handle folding of casts and lookup of the
2193 /// cast in the ExprConstants map. It is used by the various get* methods below.
2194 static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
2195 bool OnlyIfReduced = false) {
2196 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2197 // Fold a few common cases
2198 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2199 return FC;
2201 if (OnlyIfReduced)
2202 return nullptr;
2204 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2206 // Look up the constant in the table first to ensure uniqueness.
2207 ConstantExprKeyType Key(opc, C);
2209 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2212 Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
2213 bool OnlyIfReduced) {
2214 Instruction::CastOps opc = Instruction::CastOps(oc);
2215 assert(Instruction::isCast(opc) && "opcode out of range");
2216 assert(isSupportedCastOp(opc) &&
2217 "Cast opcode not supported as constant expression");
2218 assert(C && Ty && "Null arguments to getCast");
2219 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2221 switch (opc) {
2222 default:
2223 llvm_unreachable("Invalid cast opcode");
2224 case Instruction::Trunc:
2225 return getTrunc(C, Ty, OnlyIfReduced);
2226 case Instruction::PtrToInt:
2227 return getPtrToInt(C, Ty, OnlyIfReduced);
2228 case Instruction::IntToPtr:
2229 return getIntToPtr(C, Ty, OnlyIfReduced);
2230 case Instruction::BitCast:
2231 return getBitCast(C, Ty, OnlyIfReduced);
2232 case Instruction::AddrSpaceCast:
2233 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2237 Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
2238 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2239 return getBitCast(C, Ty);
2240 return getTrunc(C, Ty);
2243 Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
2244 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2245 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2246 "Invalid cast");
2248 if (Ty->isIntOrIntVectorTy())
2249 return getPtrToInt(S, Ty);
2251 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2252 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2253 return getAddrSpaceCast(S, Ty);
2255 return getBitCast(S, Ty);
2258 Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
2259 Type *Ty) {
2260 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2261 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2263 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2264 return getAddrSpaceCast(S, Ty);
2266 return getBitCast(S, Ty);
2269 Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2270 #ifndef NDEBUG
2271 bool fromVec = isa<VectorType>(C->getType());
2272 bool toVec = isa<VectorType>(Ty);
2273 #endif
2274 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2275 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2276 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2277 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2278 "SrcTy must be larger than DestTy for Trunc!");
2280 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2283 Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
2284 bool OnlyIfReduced) {
2285 assert(C->getType()->isPtrOrPtrVectorTy() &&
2286 "PtrToInt source must be pointer or pointer vector");
2287 assert(DstTy->isIntOrIntVectorTy() &&
2288 "PtrToInt destination must be integer or integer vector");
2289 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2290 if (isa<VectorType>(C->getType()))
2291 assert(cast<VectorType>(C->getType())->getElementCount() ==
2292 cast<VectorType>(DstTy)->getElementCount() &&
2293 "Invalid cast between a different number of vector elements");
2294 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2297 Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
2298 bool OnlyIfReduced) {
2299 assert(C->getType()->isIntOrIntVectorTy() &&
2300 "IntToPtr source must be integer or integer vector");
2301 assert(DstTy->isPtrOrPtrVectorTy() &&
2302 "IntToPtr destination must be a pointer or pointer vector");
2303 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2304 if (isa<VectorType>(C->getType()))
2305 assert(cast<VectorType>(C->getType())->getElementCount() ==
2306 cast<VectorType>(DstTy)->getElementCount() &&
2307 "Invalid cast between a different number of vector elements");
2308 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2311 Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
2312 bool OnlyIfReduced) {
2313 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2314 "Invalid constantexpr bitcast!");
2316 // It is common to ask for a bitcast of a value to its own type, handle this
2317 // speedily.
2318 if (C->getType() == DstTy) return C;
2320 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2323 Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
2324 bool OnlyIfReduced) {
2325 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2326 "Invalid constantexpr addrspacecast!");
2327 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2330 Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2331 unsigned Flags, Type *OnlyIfReducedTy) {
2332 // Check the operands for consistency first.
2333 assert(Instruction::isBinaryOp(Opcode) &&
2334 "Invalid opcode in binary constant expression");
2335 assert(isSupportedBinOp(Opcode) &&
2336 "Binop not supported as constant expression");
2337 assert(C1->getType() == C2->getType() &&
2338 "Operand types in binary constant expression should match");
2340 #ifndef NDEBUG
2341 switch (Opcode) {
2342 case Instruction::Add:
2343 case Instruction::Sub:
2344 case Instruction::Mul:
2345 assert(C1->getType()->isIntOrIntVectorTy() &&
2346 "Tried to create an integer operation on a non-integer type!");
2347 break;
2348 case Instruction::And:
2349 case Instruction::Or:
2350 case Instruction::Xor:
2351 assert(C1->getType()->isIntOrIntVectorTy() &&
2352 "Tried to create a logical operation on a non-integral type!");
2353 break;
2354 default:
2355 break;
2357 #endif
2359 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2360 return FC;
2362 if (OnlyIfReducedTy == C1->getType())
2363 return nullptr;
2365 Constant *ArgVec[] = {C1, C2};
2366 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2368 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2369 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2372 bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2373 switch (Opcode) {
2374 case Instruction::UDiv:
2375 case Instruction::SDiv:
2376 case Instruction::URem:
2377 case Instruction::SRem:
2378 case Instruction::FAdd:
2379 case Instruction::FSub:
2380 case Instruction::FMul:
2381 case Instruction::FDiv:
2382 case Instruction::FRem:
2383 case Instruction::And:
2384 case Instruction::Or:
2385 case Instruction::LShr:
2386 case Instruction::AShr:
2387 case Instruction::Shl:
2388 return false;
2389 case Instruction::Add:
2390 case Instruction::Sub:
2391 case Instruction::Mul:
2392 case Instruction::Xor:
2393 return true;
2394 default:
2395 llvm_unreachable("Argument must be binop opcode");
2399 bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2400 switch (Opcode) {
2401 case Instruction::UDiv:
2402 case Instruction::SDiv:
2403 case Instruction::URem:
2404 case Instruction::SRem:
2405 case Instruction::FAdd:
2406 case Instruction::FSub:
2407 case Instruction::FMul:
2408 case Instruction::FDiv:
2409 case Instruction::FRem:
2410 case Instruction::And:
2411 case Instruction::Or:
2412 case Instruction::LShr:
2413 case Instruction::AShr:
2414 case Instruction::Shl:
2415 return false;
2416 case Instruction::Add:
2417 case Instruction::Sub:
2418 case Instruction::Mul:
2419 case Instruction::Xor:
2420 return true;
2421 default:
2422 llvm_unreachable("Argument must be binop opcode");
2426 bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2427 switch (Opcode) {
2428 case Instruction::ZExt:
2429 case Instruction::SExt:
2430 case Instruction::FPTrunc:
2431 case Instruction::FPExt:
2432 case Instruction::UIToFP:
2433 case Instruction::SIToFP:
2434 case Instruction::FPToUI:
2435 case Instruction::FPToSI:
2436 return false;
2437 case Instruction::Trunc:
2438 case Instruction::PtrToInt:
2439 case Instruction::IntToPtr:
2440 case Instruction::BitCast:
2441 case Instruction::AddrSpaceCast:
2442 return true;
2443 default:
2444 llvm_unreachable("Argument must be cast opcode");
2448 bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2449 switch (Opcode) {
2450 case Instruction::ZExt:
2451 case Instruction::SExt:
2452 case Instruction::FPTrunc:
2453 case Instruction::FPExt:
2454 case Instruction::UIToFP:
2455 case Instruction::SIToFP:
2456 case Instruction::FPToUI:
2457 case Instruction::FPToSI:
2458 return false;
2459 case Instruction::Trunc:
2460 case Instruction::PtrToInt:
2461 case Instruction::IntToPtr:
2462 case Instruction::BitCast:
2463 case Instruction::AddrSpaceCast:
2464 return true;
2465 default:
2466 llvm_unreachable("Argument must be cast opcode");
2470 Constant *ConstantExpr::getSizeOf(Type* Ty) {
2471 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2472 // Note that a non-inbounds gep is used, as null isn't within any object.
2473 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2474 Constant *GEP = getGetElementPtr(
2475 Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
2476 return getPtrToInt(GEP,
2477 Type::getInt64Ty(Ty->getContext()));
2480 Constant *ConstantExpr::getAlignOf(Type* Ty) {
2481 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2482 // Note that a non-inbounds gep is used, as null isn't within any object.
2483 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2484 Constant *NullPtr =
2485 Constant::getNullValue(PointerType::getUnqual(AligningTy->getContext()));
2486 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2487 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2488 Constant *Indices[2] = {Zero, One};
2489 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2490 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2493 Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
2494 ArrayRef<Value *> Idxs,
2495 GEPNoWrapFlags NW,
2496 std::optional<ConstantRange> InRange,
2497 Type *OnlyIfReducedTy) {
2498 assert(Ty && "Must specify element type");
2499 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2501 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2502 return FC; // Fold a few common cases.
2504 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2507 // Get the result type of the getelementptr!
2508 Type *ReqTy = GetElementPtrInst::getGEPReturnType(C, Idxs);
2509 if (OnlyIfReducedTy == ReqTy)
2510 return nullptr;
2512 auto EltCount = ElementCount::getFixed(0);
2513 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2514 EltCount = VecTy->getElementCount();
2516 // Look up the constant in the table first to ensure uniqueness
2517 std::vector<Constant*> ArgVec;
2518 ArgVec.reserve(1 + Idxs.size());
2519 ArgVec.push_back(C);
2520 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2521 for (; GTI != GTE; ++GTI) {
2522 auto *Idx = cast<Constant>(GTI.getOperand());
2523 assert(
2524 (!isa<VectorType>(Idx->getType()) ||
2525 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2526 "getelementptr index type missmatch");
2528 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2529 Idx = Idx->getSplatValue();
2530 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2531 !Idx->getType()->isVectorTy()) {
2532 Idx = ConstantVector::getSplat(EltCount, Idx);
2534 ArgVec.push_back(Idx);
2537 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2538 {}, Ty, InRange);
2540 LLVMContextImpl *pImpl = C->getContext().pImpl;
2541 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2544 Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
2545 Type *OnlyIfReducedTy) {
2546 assert(Val->getType()->isVectorTy() &&
2547 "Tried to create extractelement operation on non-vector type!");
2548 assert(Idx->getType()->isIntegerTy() &&
2549 "Extractelement index must be an integer type!");
2551 if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
2552 return FC; // Fold a few common cases.
2554 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2555 if (OnlyIfReducedTy == ReqTy)
2556 return nullptr;
2558 // Look up the constant in the table first to ensure uniqueness
2559 Constant *ArgVec[] = { Val, Idx };
2560 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2562 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2563 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2566 Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
2567 Constant *Idx, Type *OnlyIfReducedTy) {
2568 assert(Val->getType()->isVectorTy() &&
2569 "Tried to create insertelement operation on non-vector type!");
2570 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2571 "Insertelement types must match!");
2572 assert(Idx->getType()->isIntegerTy() &&
2573 "Insertelement index must be i32 type!");
2575 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2576 return FC; // Fold a few common cases.
2578 if (OnlyIfReducedTy == Val->getType())
2579 return nullptr;
2581 // Look up the constant in the table first to ensure uniqueness
2582 Constant *ArgVec[] = { Val, Elt, Idx };
2583 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2585 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2586 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2589 Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
2590 ArrayRef<int> Mask,
2591 Type *OnlyIfReducedTy) {
2592 assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
2593 "Invalid shuffle vector constant expr operands!");
2595 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2596 return FC; // Fold a few common cases.
2598 unsigned NElts = Mask.size();
2599 auto V1VTy = cast<VectorType>(V1->getType());
2600 Type *EltTy = V1VTy->getElementType();
2601 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2602 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2604 if (OnlyIfReducedTy == ShufTy)
2605 return nullptr;
2607 // Look up the constant in the table first to ensure uniqueness
2608 Constant *ArgVec[] = {V1, V2};
2609 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2611 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2612 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2615 Constant *ConstantExpr::getNeg(Constant *C, bool HasNSW) {
2616 assert(C->getType()->isIntOrIntVectorTy() &&
2617 "Cannot NEG a nonintegral value!");
2618 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2621 Constant *ConstantExpr::getNot(Constant *C) {
2622 assert(C->getType()->isIntOrIntVectorTy() &&
2623 "Cannot NOT a nonintegral value!");
2624 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2627 Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
2628 bool HasNUW, bool HasNSW) {
2629 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2630 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2631 return get(Instruction::Add, C1, C2, Flags);
2634 Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
2635 bool HasNUW, bool HasNSW) {
2636 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2637 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2638 return get(Instruction::Sub, C1, C2, Flags);
2641 Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
2642 bool HasNUW, bool HasNSW) {
2643 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2644 (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
2645 return get(Instruction::Mul, C1, C2, Flags);
2648 Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
2649 return get(Instruction::Xor, C1, C2);
2652 Constant *ConstantExpr::getExactLogBase2(Constant *C) {
2653 Type *Ty = C->getType();
2654 const APInt *IVal;
2655 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2656 return ConstantInt::get(Ty, IVal->logBase2());
2658 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2659 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2660 if (!VecTy)
2661 return nullptr;
2663 SmallVector<Constant *, 4> Elts;
2664 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2665 Constant *Elt = C->getAggregateElement(I);
2666 if (!Elt)
2667 return nullptr;
2668 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2669 if (isa<UndefValue>(Elt)) {
2670 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2671 continue;
2673 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2674 return nullptr;
2675 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2678 return ConstantVector::get(Elts);
2681 Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
2682 bool AllowRHSConstant, bool NSZ) {
2683 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2685 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2686 if (Instruction::isCommutative(Opcode)) {
2687 switch (Opcode) {
2688 case Instruction::Add: // X + 0 = X
2689 case Instruction::Or: // X | 0 = X
2690 case Instruction::Xor: // X ^ 0 = X
2691 return Constant::getNullValue(Ty);
2692 case Instruction::Mul: // X * 1 = X
2693 return ConstantInt::get(Ty, 1);
2694 case Instruction::And: // X & -1 = X
2695 return Constant::getAllOnesValue(Ty);
2696 case Instruction::FAdd: // X + -0.0 = X
2697 return ConstantFP::getZero(Ty, !NSZ);
2698 case Instruction::FMul: // X * 1.0 = X
2699 return ConstantFP::get(Ty, 1.0);
2700 default:
2701 llvm_unreachable("Every commutative binop has an identity constant");
2705 // Non-commutative opcodes: AllowRHSConstant must be set.
2706 if (!AllowRHSConstant)
2707 return nullptr;
2709 switch (Opcode) {
2710 case Instruction::Sub: // X - 0 = X
2711 case Instruction::Shl: // X << 0 = X
2712 case Instruction::LShr: // X >>u 0 = X
2713 case Instruction::AShr: // X >> 0 = X
2714 case Instruction::FSub: // X - 0.0 = X
2715 return Constant::getNullValue(Ty);
2716 case Instruction::SDiv: // X / 1 = X
2717 case Instruction::UDiv: // X /u 1 = X
2718 return ConstantInt::get(Ty, 1);
2719 case Instruction::FDiv: // X / 1.0 = X
2720 return ConstantFP::get(Ty, 1.0);
2721 default:
2722 return nullptr;
2726 Constant *ConstantExpr::getIntrinsicIdentity(Intrinsic::ID ID, Type *Ty) {
2727 switch (ID) {
2728 case Intrinsic::umax:
2729 return Constant::getNullValue(Ty);
2730 case Intrinsic::umin:
2731 return Constant::getAllOnesValue(Ty);
2732 case Intrinsic::smax:
2733 return Constant::getIntegerValue(
2734 Ty, APInt::getSignedMinValue(Ty->getIntegerBitWidth()));
2735 case Intrinsic::smin:
2736 return Constant::getIntegerValue(
2737 Ty, APInt::getSignedMaxValue(Ty->getIntegerBitWidth()));
2738 default:
2739 return nullptr;
2743 Constant *ConstantExpr::getIdentity(Instruction *I, Type *Ty,
2744 bool AllowRHSConstant, bool NSZ) {
2745 if (I->isBinaryOp())
2746 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2747 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2748 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2749 return nullptr;
2752 Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty,
2753 bool AllowLHSConstant) {
2754 switch (Opcode) {
2755 default:
2756 break;
2758 case Instruction::Or: // -1 | X = -1
2759 return Constant::getAllOnesValue(Ty);
2761 case Instruction::And: // 0 & X = 0
2762 case Instruction::Mul: // 0 * X = 0
2763 return Constant::getNullValue(Ty);
2766 // AllowLHSConstant must be set.
2767 if (!AllowLHSConstant)
2768 return nullptr;
2770 switch (Opcode) {
2771 default:
2772 return nullptr;
2773 case Instruction::Shl: // 0 << X = 0
2774 case Instruction::LShr: // 0 >>l X = 0
2775 case Instruction::AShr: // 0 >>a X = 0
2776 case Instruction::SDiv: // 0 /s X = 0
2777 case Instruction::UDiv: // 0 /u X = 0
2778 case Instruction::URem: // 0 %u X = 0
2779 case Instruction::SRem: // 0 %s X = 0
2780 return Constant::getNullValue(Ty);
2784 /// Remove the constant from the constant table.
2785 void ConstantExpr::destroyConstantImpl() {
2786 getType()->getContext().pImpl->ExprConstants.remove(this);
2789 const char *ConstantExpr::getOpcodeName() const {
2790 return Instruction::getOpcodeName(getOpcode());
2793 GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2794 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
2795 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
2796 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
2797 SrcElementTy(SrcElementTy),
2798 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
2799 InRange(std::move(InRange)) {
2800 Op<0>() = C;
2801 Use *OperandList = getOperandList();
2802 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2803 OperandList[i+1] = IdxList[i];
2806 Type *GetElementPtrConstantExpr::getSourceElementType() const {
2807 return SrcElementTy;
2810 Type *GetElementPtrConstantExpr::getResultElementType() const {
2811 return ResElementTy;
2814 std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
2815 return InRange;
2818 //===----------------------------------------------------------------------===//
2819 // ConstantData* implementations
2821 Type *ConstantDataSequential::getElementType() const {
2822 if (ArrayType *ATy = dyn_cast<ArrayType>(getType()))
2823 return ATy->getElementType();
2824 return cast<VectorType>(getType())->getElementType();
2827 StringRef ConstantDataSequential::getRawDataValues() const {
2828 return StringRef(DataElements, getNumElements()*getElementByteSize());
2831 bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
2832 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2833 return true;
2834 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2835 switch (IT->getBitWidth()) {
2836 case 8:
2837 case 16:
2838 case 32:
2839 case 64:
2840 return true;
2841 default: break;
2844 return false;
2847 unsigned ConstantDataSequential::getNumElements() const {
2848 if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
2849 return AT->getNumElements();
2850 return cast<FixedVectorType>(getType())->getNumElements();
2854 uint64_t ConstantDataSequential::getElementByteSize() const {
2855 return getElementType()->getPrimitiveSizeInBits()/8;
2858 /// Return the start of the specified element.
2859 const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
2860 assert(Elt < getNumElements() && "Invalid Elt");
2861 return DataElements+Elt*getElementByteSize();
2865 /// Return true if the array is empty or all zeros.
2866 static bool isAllZeros(StringRef Arr) {
2867 for (char I : Arr)
2868 if (I != 0)
2869 return false;
2870 return true;
2873 /// This is the underlying implementation of all of the
2874 /// ConstantDataSequential::get methods. They all thunk down to here, providing
2875 /// the correct element type. We take the bytes in as a StringRef because
2876 /// we *want* an underlying "char*" to avoid TBAA type punning violations.
2877 Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
2878 #ifndef NDEBUG
2879 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2880 assert(isElementTypeCompatible(ATy->getElementType()));
2881 else
2882 assert(isElementTypeCompatible(cast<VectorType>(Ty)->getElementType()));
2883 #endif
2884 // If the elements are all zero or there are no elements, return a CAZ, which
2885 // is more dense and canonical.
2886 if (isAllZeros(Elements))
2887 return ConstantAggregateZero::get(Ty);
2889 // Do a lookup to see if we have already formed one of these.
2890 auto &Slot =
2891 *Ty->getContext()
2892 .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
2893 .first;
2895 // The bucket can point to a linked list of different CDS's that have the same
2896 // body but different types. For example, 0,0,0,1 could be a 4 element array
2897 // of i8, or a 1-element array of i32. They'll both end up in the same
2898 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2899 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
2900 for (; *Entry; Entry = &(*Entry)->Next)
2901 if ((*Entry)->getType() == Ty)
2902 return Entry->get();
2904 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2905 // and return it.
2906 if (isa<ArrayType>(Ty)) {
2907 // Use reset because std::make_unique can't access the constructor.
2908 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
2909 return Entry->get();
2912 assert(isa<VectorType>(Ty));
2913 // Use reset because std::make_unique can't access the constructor.
2914 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
2915 return Entry->get();
2918 void ConstantDataSequential::destroyConstantImpl() {
2919 // Remove the constant from the StringMap.
2920 StringMap<std::unique_ptr<ConstantDataSequential>> &CDSConstants =
2921 getType()->getContext().pImpl->CDSConstants;
2923 auto Slot = CDSConstants.find(getRawDataValues());
2925 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2927 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
2929 // Remove the entry from the hash table.
2930 if (!(*Entry)->Next) {
2931 // If there is only one value in the bucket (common case) it must be this
2932 // entry, and removing the entry should remove the bucket completely.
2933 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
2934 getContext().pImpl->CDSConstants.erase(Slot);
2935 return;
2938 // Otherwise, there are multiple entries linked off the bucket, unlink the
2939 // node we care about but keep the bucket around.
2940 while (true) {
2941 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
2942 assert(Node && "Didn't find entry in its uniquing hash table!");
2943 // If we found our entry, unlink it from the list and we're done.
2944 if (Node.get() == this) {
2945 Node = std::move(Node->Next);
2946 return;
2949 Entry = &Node->Next;
2953 /// getFP() constructors - Return a constant of array type with a float
2954 /// element type taken from argument `ElementType', and count taken from
2955 /// argument `Elts'. The amount of bits of the contained type must match the
2956 /// number of bits of the type contained in the passed in ArrayRef.
2957 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2958 /// that this can return a ConstantAggregateZero object.
2959 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint16_t> Elts) {
2960 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2961 "Element type is not a 16-bit float type");
2962 Type *Ty = ArrayType::get(ElementType, Elts.size());
2963 const char *Data = reinterpret_cast<const char *>(Elts.data());
2964 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2966 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint32_t> Elts) {
2967 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2968 Type *Ty = ArrayType::get(ElementType, Elts.size());
2969 const char *Data = reinterpret_cast<const char *>(Elts.data());
2970 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2972 Constant *ConstantDataArray::getFP(Type *ElementType, ArrayRef<uint64_t> Elts) {
2973 assert(ElementType->isDoubleTy() &&
2974 "Element type is not a 64-bit float type");
2975 Type *Ty = ArrayType::get(ElementType, Elts.size());
2976 const char *Data = reinterpret_cast<const char *>(Elts.data());
2977 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
2980 Constant *ConstantDataArray::getString(LLVMContext &Context,
2981 StringRef Str, bool AddNull) {
2982 if (!AddNull) {
2983 const uint8_t *Data = Str.bytes_begin();
2984 return get(Context, ArrayRef(Data, Str.size()));
2987 SmallVector<uint8_t, 64> ElementVals;
2988 ElementVals.append(Str.begin(), Str.end());
2989 ElementVals.push_back(0);
2990 return get(Context, ElementVals);
2993 /// get() constructors - Return a constant with vector type with an element
2994 /// count and element type matching the ArrayRef passed in. Note that this
2995 /// can return a ConstantAggregateZero object.
2996 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
2997 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
2998 const char *Data = reinterpret_cast<const char *>(Elts.data());
2999 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3001 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
3002 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3003 const char *Data = reinterpret_cast<const char *>(Elts.data());
3004 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3006 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
3007 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3008 const char *Data = reinterpret_cast<const char *>(Elts.data());
3009 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3011 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
3012 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3013 const char *Data = reinterpret_cast<const char *>(Elts.data());
3014 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3016 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
3017 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3018 const char *Data = reinterpret_cast<const char *>(Elts.data());
3019 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3021 Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
3022 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3023 const char *Data = reinterpret_cast<const char *>(Elts.data());
3024 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3027 /// getFP() constructors - Return a constant of vector type with a float
3028 /// element type taken from argument `ElementType', and count taken from
3029 /// argument `Elts'. The amount of bits of the contained type must match the
3030 /// number of bits of the type contained in the passed in ArrayRef.
3031 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3032 /// that this can return a ConstantAggregateZero object.
3033 Constant *ConstantDataVector::getFP(Type *ElementType,
3034 ArrayRef<uint16_t> Elts) {
3035 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3036 "Element type is not a 16-bit float type");
3037 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3038 const char *Data = reinterpret_cast<const char *>(Elts.data());
3039 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3041 Constant *ConstantDataVector::getFP(Type *ElementType,
3042 ArrayRef<uint32_t> Elts) {
3043 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3044 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3045 const char *Data = reinterpret_cast<const char *>(Elts.data());
3046 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3048 Constant *ConstantDataVector::getFP(Type *ElementType,
3049 ArrayRef<uint64_t> Elts) {
3050 assert(ElementType->isDoubleTy() &&
3051 "Element type is not a 64-bit float type");
3052 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3053 const char *Data = reinterpret_cast<const char *>(Elts.data());
3054 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3057 Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
3058 assert(isElementTypeCompatible(V->getType()) &&
3059 "Element type not compatible with ConstantData");
3060 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3061 if (CI->getType()->isIntegerTy(8)) {
3062 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3063 return get(V->getContext(), Elts);
3065 if (CI->getType()->isIntegerTy(16)) {
3066 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3067 return get(V->getContext(), Elts);
3069 if (CI->getType()->isIntegerTy(32)) {
3070 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3071 return get(V->getContext(), Elts);
3073 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3074 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3075 return get(V->getContext(), Elts);
3078 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3079 if (CFP->getType()->isHalfTy()) {
3080 SmallVector<uint16_t, 16> Elts(
3081 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3082 return getFP(V->getType(), Elts);
3084 if (CFP->getType()->isBFloatTy()) {
3085 SmallVector<uint16_t, 16> Elts(
3086 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3087 return getFP(V->getType(), Elts);
3089 if (CFP->getType()->isFloatTy()) {
3090 SmallVector<uint32_t, 16> Elts(
3091 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3092 return getFP(V->getType(), Elts);
3094 if (CFP->getType()->isDoubleTy()) {
3095 SmallVector<uint64_t, 16> Elts(
3096 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3097 return getFP(V->getType(), Elts);
3100 return ConstantVector::getSplat(ElementCount::getFixed(NumElts), V);
3104 uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
3105 assert(isa<IntegerType>(getElementType()) &&
3106 "Accessor can only be used when element is an integer");
3107 const char *EltPtr = getElementPointer(Elt);
3109 // The data is stored in host byte order, make sure to cast back to the right
3110 // type to load with the right endianness.
3111 switch (getElementType()->getIntegerBitWidth()) {
3112 default: llvm_unreachable("Invalid bitwidth for CDS");
3113 case 8:
3114 return *reinterpret_cast<const uint8_t *>(EltPtr);
3115 case 16:
3116 return *reinterpret_cast<const uint16_t *>(EltPtr);
3117 case 32:
3118 return *reinterpret_cast<const uint32_t *>(EltPtr);
3119 case 64:
3120 return *reinterpret_cast<const uint64_t *>(EltPtr);
3124 APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
3125 assert(isa<IntegerType>(getElementType()) &&
3126 "Accessor can only be used when element is an integer");
3127 const char *EltPtr = getElementPointer(Elt);
3129 // The data is stored in host byte order, make sure to cast back to the right
3130 // type to load with the right endianness.
3131 switch (getElementType()->getIntegerBitWidth()) {
3132 default: llvm_unreachable("Invalid bitwidth for CDS");
3133 case 8: {
3134 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3135 return APInt(8, EltVal);
3137 case 16: {
3138 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3139 return APInt(16, EltVal);
3141 case 32: {
3142 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3143 return APInt(32, EltVal);
3145 case 64: {
3146 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3147 return APInt(64, EltVal);
3152 APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
3153 const char *EltPtr = getElementPointer(Elt);
3155 switch (getElementType()->getTypeID()) {
3156 default:
3157 llvm_unreachable("Accessor can only be used when element is float/double!");
3158 case Type::HalfTyID: {
3159 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3160 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3162 case Type::BFloatTyID: {
3163 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3164 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3166 case Type::FloatTyID: {
3167 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3168 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3170 case Type::DoubleTyID: {
3171 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3172 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3177 float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
3178 assert(getElementType()->isFloatTy() &&
3179 "Accessor can only be used when element is a 'float'");
3180 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3183 double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
3184 assert(getElementType()->isDoubleTy() &&
3185 "Accessor can only be used when element is a 'float'");
3186 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3189 Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
3190 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3191 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3192 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3194 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3197 bool ConstantDataSequential::isString(unsigned CharSize) const {
3198 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3201 bool ConstantDataSequential::isCString() const {
3202 if (!isString())
3203 return false;
3205 StringRef Str = getAsString();
3207 // The last value must be nul.
3208 if (Str.back() != 0) return false;
3210 // Other elements must be non-nul.
3211 return !Str.drop_back().contains(0);
3214 bool ConstantDataVector::isSplatData() const {
3215 const char *Base = getRawDataValues().data();
3217 // Compare elements 1+ to the 0'th element.
3218 unsigned EltSize = getElementByteSize();
3219 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3220 if (memcmp(Base, Base+i*EltSize, EltSize))
3221 return false;
3223 return true;
3226 bool ConstantDataVector::isSplat() const {
3227 if (!IsSplatSet) {
3228 IsSplatSet = true;
3229 IsSplat = isSplatData();
3231 return IsSplat;
3234 Constant *ConstantDataVector::getSplatValue() const {
3235 // If they're all the same, return the 0th one as a representative.
3236 return isSplat() ? getElementAsConstant(0) : nullptr;
3239 //===----------------------------------------------------------------------===//
3240 // handleOperandChange implementations
3242 /// Update this constant array to change uses of
3243 /// 'From' to be uses of 'To'. This must update the uniquing data structures
3244 /// etc.
3246 /// Note that we intentionally replace all uses of From with To here. Consider
3247 /// a large array that uses 'From' 1000 times. By handling this case all here,
3248 /// ConstantArray::handleOperandChange is only invoked once, and that
3249 /// single invocation handles all 1000 uses. Handling them one at a time would
3250 /// work, but would be really slow because it would have to unique each updated
3251 /// array instance.
3253 void Constant::handleOperandChange(Value *From, Value *To) {
3254 Value *Replacement = nullptr;
3255 switch (getValueID()) {
3256 default:
3257 llvm_unreachable("Not a constant!");
3258 #define HANDLE_CONSTANT(Name) \
3259 case Value::Name##Val: \
3260 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3261 break;
3262 #include "llvm/IR/Value.def"
3265 // If handleOperandChangeImpl returned nullptr, then it handled
3266 // replacing itself and we don't want to delete or replace anything else here.
3267 if (!Replacement)
3268 return;
3270 // I do need to replace this with an existing value.
3271 assert(Replacement != this && "I didn't contain From!");
3273 // Everyone using this now uses the replacement.
3274 replaceAllUsesWith(Replacement);
3276 // Delete the old constant!
3277 destroyConstant();
3280 Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3281 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3282 Constant *ToC = cast<Constant>(To);
3284 SmallVector<Constant*, 8> Values;
3285 Values.reserve(getNumOperands()); // Build replacement array.
3287 // Fill values with the modified operands of the constant array. Also,
3288 // compute whether this turns into an all-zeros array.
3289 unsigned NumUpdated = 0;
3291 // Keep track of whether all the values in the array are "ToC".
3292 bool AllSame = true;
3293 Use *OperandList = getOperandList();
3294 unsigned OperandNo = 0;
3295 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3296 Constant *Val = cast<Constant>(O->get());
3297 if (Val == From) {
3298 OperandNo = (O - OperandList);
3299 Val = ToC;
3300 ++NumUpdated;
3302 Values.push_back(Val);
3303 AllSame &= Val == ToC;
3306 if (AllSame && ToC->isNullValue())
3307 return ConstantAggregateZero::get(getType());
3309 if (AllSame && isa<UndefValue>(ToC))
3310 return UndefValue::get(getType());
3312 // Check for any other type of constant-folding.
3313 if (Constant *C = getImpl(getType(), Values))
3314 return C;
3316 // Update to the new value.
3317 return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
3318 Values, this, From, ToC, NumUpdated, OperandNo);
3321 Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3322 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3323 Constant *ToC = cast<Constant>(To);
3325 Use *OperandList = getOperandList();
3327 SmallVector<Constant*, 8> Values;
3328 Values.reserve(getNumOperands()); // Build replacement struct.
3330 // Fill values with the modified operands of the constant struct. Also,
3331 // compute whether this turns into an all-zeros struct.
3332 unsigned NumUpdated = 0;
3333 bool AllSame = true;
3334 unsigned OperandNo = 0;
3335 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3336 Constant *Val = cast<Constant>(O->get());
3337 if (Val == From) {
3338 OperandNo = (O - OperandList);
3339 Val = ToC;
3340 ++NumUpdated;
3342 Values.push_back(Val);
3343 AllSame &= Val == ToC;
3346 if (AllSame && ToC->isNullValue())
3347 return ConstantAggregateZero::get(getType());
3349 if (AllSame && isa<UndefValue>(ToC))
3350 return UndefValue::get(getType());
3352 // Update to the new value.
3353 return getContext().pImpl->StructConstants.replaceOperandsInPlace(
3354 Values, this, From, ToC, NumUpdated, OperandNo);
3357 Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3358 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3359 Constant *ToC = cast<Constant>(To);
3361 SmallVector<Constant*, 8> Values;
3362 Values.reserve(getNumOperands()); // Build replacement array...
3363 unsigned NumUpdated = 0;
3364 unsigned OperandNo = 0;
3365 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3366 Constant *Val = getOperand(i);
3367 if (Val == From) {
3368 OperandNo = i;
3369 ++NumUpdated;
3370 Val = ToC;
3372 Values.push_back(Val);
3375 if (Constant *C = getImpl(Values))
3376 return C;
3378 // Update to the new value.
3379 return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
3380 Values, this, From, ToC, NumUpdated, OperandNo);
3383 Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3384 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3385 Constant *To = cast<Constant>(ToV);
3387 SmallVector<Constant*, 8> NewOps;
3388 unsigned NumUpdated = 0;
3389 unsigned OperandNo = 0;
3390 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3391 Constant *Op = getOperand(i);
3392 if (Op == From) {
3393 OperandNo = i;
3394 ++NumUpdated;
3395 Op = To;
3397 NewOps.push_back(Op);
3399 assert(NumUpdated && "I didn't contain From!");
3401 if (Constant *C = getWithOperands(NewOps, getType(), true))
3402 return C;
3404 // Update to the new value.
3405 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3406 NewOps, this, From, To, NumUpdated, OperandNo);
3409 Instruction *ConstantExpr::getAsInstruction() const {
3410 SmallVector<Value *, 4> ValueOperands(operands());
3411 ArrayRef<Value*> Ops(ValueOperands);
3413 switch (getOpcode()) {
3414 case Instruction::Trunc:
3415 case Instruction::PtrToInt:
3416 case Instruction::IntToPtr:
3417 case Instruction::BitCast:
3418 case Instruction::AddrSpaceCast:
3419 return CastInst::Create((Instruction::CastOps)getOpcode(), Ops[0],
3420 getType(), "");
3421 case Instruction::InsertElement:
3422 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3423 case Instruction::ExtractElement:
3424 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3425 case Instruction::ShuffleVector:
3426 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3428 case Instruction::GetElementPtr: {
3429 const auto *GO = cast<GEPOperator>(this);
3430 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3431 Ops.slice(1), GO->getNoWrapFlags(), "");
3433 default:
3434 assert(getNumOperands() == 2 && "Must be binary operator?");
3435 BinaryOperator *BO = BinaryOperator::Create(
3436 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3437 if (isa<OverflowingBinaryOperator>(BO)) {
3438 BO->setHasNoUnsignedWrap(SubclassOptionalData &
3439 OverflowingBinaryOperator::NoUnsignedWrap);
3440 BO->setHasNoSignedWrap(SubclassOptionalData &
3441 OverflowingBinaryOperator::NoSignedWrap);
3443 if (isa<PossiblyExactOperator>(BO))
3444 BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
3445 return BO;