LLVM 23.0.0git
Constants.cpp
Go to the documentation of this file.
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.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/IR/Constants.h"
14#include "LLVMContextImpl.h"
15#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/IR/BasicBlock.h"
21#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalAlias.h"
24#include "llvm/IR/GlobalIFunc.h"
25#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Operator.h"
33#include <algorithm>
34
35using namespace llvm;
36using namespace PatternMatch;
37
38// As set of temporary options to help migrate how splats are represented.
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."));
43 "use-constant-int-for-scalable-splat", cl::init(false), cl::Hidden,
44 cl::desc("Use ConstantInt's native scalable vector splat support."));
45
46//===----------------------------------------------------------------------===//
47// Constant Class
48//===----------------------------------------------------------------------===//
49
51 // Floating point values have an explicit -0.0 value.
52 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
53 return CFP->isZero() && CFP->isNegative();
54
55 // Equivalent for a vector of -0.0's.
56 if (getType()->isVectorTy())
57 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
58 return SplatCFP->isNegativeZeroValue();
59
60 // We've already handled true FP case; any other FP vectors can't represent -0.0.
61 if (getType()->isFPOrFPVectorTy())
62 return false;
63
64 // Otherwise, just use +0.0.
65 return isNullValue();
66}
67
69 // Check for -1 integers
70 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
71 return CI->isMinusOne();
72
73 // Check for MaxValue bytes
74 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
75 return CB->isMinusOne();
76
77 // Check for FP which are bitcasted from -1 integers
78 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
79 return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
80
81 // Check for constant splat vectors of 1 values.
82 if (getType()->isVectorTy())
83 if (const auto *SplatVal = getSplatValue())
84 return SplatVal->isAllOnesValue();
85
86 return false;
87}
88
90 // Check for 1 integers
91 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
92 return CI->isOne();
93
94 // Check for 1 bytes
95 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
96 return CB->isOne();
97
98 // Check for FP which are bitcasted from 1 integers
99 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
100 return CFP->getValueAPF().bitcastToAPInt().isOne();
101
102 // Check for constant splat vectors of 1 values.
103 if (getType()->isVectorTy())
104 if (const auto *SplatVal = getSplatValue())
105 return SplatVal->isOneValue();
106
107 return false;
108}
109
111 // Check for 1 integers
112 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
113 return !CI->isOneValue();
114
115 // Check for 1 bytes
116 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
117 return !CB->isOneValue();
118
119 // Check for FP which are bitcasted from 1 integers
120 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
121 return !CFP->getValueAPF().bitcastToAPInt().isOne();
122
123 // Check that vectors don't contain 1
124 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
125 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
127 if (!Elt || !Elt->isNotOneValue())
128 return false;
129 }
130 return true;
131 }
132
133 // Check for splats that don't contain 1
134 if (getType()->isVectorTy())
135 if (const auto *SplatVal = getSplatValue())
136 return SplatVal->isNotOneValue();
137
138 // It *may* contain 1, we can't tell.
139 return false;
140}
141
143 // Check for INT_MIN integers
144 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
145 return CI->isMinValue(/*isSigned=*/true);
146
147 // Check for FP which are bitcasted from INT_MIN integers
148 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
149 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
150
151 // Check for splats of INT_MIN values.
152 if (getType()->isVectorTy())
153 if (const auto *SplatVal = getSplatValue())
154 return SplatVal->isMinSignedValue();
155
156 return false;
157}
158
160 // Check for INT_MAX integers
161 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
162 return CI->isMaxValue(/*isSigned=*/true);
163
164 // Check for FP which are bitcasted from INT_MAX integers
165 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
166 return CFP->getValueAPF().bitcastToAPInt().isMaxSignedValue();
167
168 // Check for splats of INT_MAX values.
169 if (getType()->isVectorTy())
170 if (const auto *SplatVal = getSplatValue())
171 return SplatVal->isMaxSignedValue();
172
173 return false;
174}
175
177 // Check for INT_MIN integers
178 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
179 return !CI->isMinValue(/*isSigned=*/true);
180
181 // Check for FP which are bitcasted from INT_MIN integers
182 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
183 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
184
185 // Check that vectors don't contain INT_MIN
186 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
187 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
189 if (!Elt || !Elt->isNotMinSignedValue())
190 return false;
191 }
192 return true;
193 }
194
195 // Check for splats that aren't INT_MIN
196 if (getType()->isVectorTy())
197 if (const auto *SplatVal = getSplatValue())
198 return SplatVal->isNotMinSignedValue();
199
200 // It *may* contain INT_MIN, we can't tell.
201 return false;
202}
203
205 if (auto *CFP = dyn_cast<ConstantFP>(this))
206 return CFP->getValueAPF().isFiniteNonZero();
207
208 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
209 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
211 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
212 return false;
213 }
214 return true;
215 }
216
217 if (getType()->isVectorTy())
218 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
219 return SplatCFP->isFiniteNonZeroFP();
220
221 // It *may* contain finite non-zero, we can't tell.
222 return false;
223}
224
226 if (auto *CFP = dyn_cast<ConstantFP>(this))
227 return CFP->getValueAPF().isNormal();
228
229 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
230 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
232 if (!CFP || !CFP->getValueAPF().isNormal())
233 return false;
234 }
235 return true;
236 }
237
238 if (getType()->isVectorTy())
239 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
240 return SplatCFP->isNormalFP();
241
242 // It *may* contain a normal fp value, we can't tell.
243 return false;
244}
245
247 if (auto *CFP = dyn_cast<ConstantFP>(this))
248 return CFP->getValueAPF().getExactInverse(nullptr);
249
250 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
251 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
253 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
254 return false;
255 }
256 return true;
257 }
258
259 if (getType()->isVectorTy())
260 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
261 return SplatCFP->hasExactInverseFP();
262
263 // It *may* have an exact inverse fp value, we can't tell.
264 return false;
265}
266
267bool Constant::isNaN() const {
268 if (auto *CFP = dyn_cast<ConstantFP>(this))
269 return CFP->isNaN();
270
271 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
272 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
274 if (!CFP || !CFP->isNaN())
275 return false;
276 }
277 return true;
278 }
279
280 if (getType()->isVectorTy())
281 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
282 return SplatCFP->isNaN();
283
284 // It *may* be NaN, we can't tell.
285 return false;
286}
287
289 // Are they fully identical?
290 if (this == Y)
291 return true;
292
293 // The input value must be a vector constant with the same type.
294 auto *VTy = dyn_cast<VectorType>(getType());
295 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
296 return false;
297
298 // TODO: Compare pointer constants?
299 if (!(VTy->getElementType()->isIntegerTy() ||
300 VTy->getElementType()->isFloatingPointTy()))
301 return false;
302
303 // They may still be identical element-wise (if they have `undef`s).
304 // Bitcast to integer to allow exact bitwise comparison for all types.
305 Type *IntTy = VectorType::getInteger(VTy);
306 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
309 return CmpEq && (isa<PoisonValue>(CmpEq) || match(CmpEq, m_One()));
310}
311
312static bool
314 function_ref<bool(const Constant *)> HasFn) {
315 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
316 if (HasFn(C))
317 return true;
319 return false;
320 if (isa<ScalableVectorType>(C->getType()))
321 return false;
322
323 for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
324 i != e; ++i) {
325 if (Constant *Elem = C->getAggregateElement(i))
326 if (HasFn(Elem))
327 return true;
328 }
329 }
330
331 return false;
332}
333
336 this, [&](const auto *C) { return isa<UndefValue>(C); });
337}
338
341 this, [&](const auto *C) { return isa<PoisonValue>(C); });
342}
343
345 return containsUndefinedElement(this, [&](const auto *C) {
346 return isa<UndefValue>(C) && !isa<PoisonValue>(C);
347 });
348}
349
351 if (isa<ConstantInt>(this) || isa<ConstantFP>(this))
352 return false;
353
354 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
355 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
357 return true;
358 }
359 return false;
360}
361
362/// Constructor to create a '0' constant of arbitrary type.
364 switch (Ty->getTypeID()) {
365 case Type::ByteTyID:
366 return ConstantByte::get(Ty, 0);
368 return ConstantInt::get(Ty, 0);
369 case Type::HalfTyID:
370 case Type::BFloatTyID:
371 case Type::FloatTyID:
372 case Type::DoubleTyID:
374 case Type::FP128TyID:
376 return ConstantFP::get(Ty->getContext(),
377 APFloat::getZero(Ty->getFltSemantics()));
382 Type *EltTy = cast<VectorType>(Ty)->getElementType();
383 if (EltTy->isFloatingPointTy())
384 return ConstantFP::get(Ty, APFloat::getZero(EltTy->getFltSemantics()));
385 if (EltTy->isPointerTy())
386 return ConstantPointerNull::get(Ty);
388 }
389 case Type::StructTyID:
390 case Type::ArrayTyID:
392 case Type::TokenTyID:
393 return ConstantTokenNone::get(Ty->getContext());
396 default:
397 // Function, Label, or Opaque type?
398 llvm_unreachable("Cannot create a null constant of that type!");
399 }
400}
401
403 Type *ScalarTy = Ty->getScalarType();
404
405 // Create the base integer constant.
406 Constant *C = ConstantInt::get(Ty->getContext(), V);
407
408 // Convert an integer to a pointer, if necessary.
409 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
411
412 // Convert an integer to a byte, if necessary.
413 if (ByteType *BTy = dyn_cast<ByteType>(ScalarTy))
415
416 // Broadcast a scalar to a vector, if necessary.
417 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
418 C = ConstantVector::getSplat(VTy->getElementCount(), C);
419
420 return C;
421}
422
424 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
425 return ConstantInt::get(Ty->getContext(),
426 APInt::getAllOnes(ITy->getBitWidth()));
427
428 if (Ty->isFloatingPointTy()) {
429 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
430 return ConstantFP::get(Ty->getContext(), FL);
431 }
432
433 if (ByteType *BTy = dyn_cast<ByteType>(Ty))
434 return ConstantByte::get(Ty->getContext(),
435 APInt::getAllOnes(BTy->getBitWidth()));
436
437 VectorType *VTy = cast<VectorType>(Ty);
438 return ConstantVector::getSplat(VTy->getElementCount(),
439 getAllOnesValue(VTy->getElementType()));
440}
441
443 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
444 "Must be an aggregate/vector constant");
445
446 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
447 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
448
449 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
450 return Elt < CAZ->getElementCount().getKnownMinValue()
451 ? CAZ->getElementValue(Elt)
452 : nullptr;
453
454 if (const auto *CI = dyn_cast<ConstantInt>(this))
455 return Elt < cast<VectorType>(getType())
456 ->getElementCount()
457 .getKnownMinValue()
458 ? ConstantInt::get(getContext(), CI->getValue())
459 : nullptr;
460
461 if (const auto *CB = dyn_cast<ConstantByte>(this))
462 return Elt < cast<VectorType>(getType())
463 ->getElementCount()
464 .getKnownMinValue()
465 ? ConstantByte::get(getContext(), CB->getValue())
466 : nullptr;
467
468 if (const auto *CFP = dyn_cast<ConstantFP>(this))
469 return Elt < cast<VectorType>(getType())
470 ->getElementCount()
471 .getKnownMinValue()
472 ? ConstantFP::get(getContext(), CFP->getValue())
473 : nullptr;
474
475 if (isa<ConstantPointerNull>(this)) {
476 auto *VT = cast<VectorType>(getType());
477 return Elt < VT->getElementCount().getKnownMinValue()
478 ? ConstantPointerNull::get(VT->getElementType())
479 : nullptr;
480 }
481
482 // FIXME: getNumElements() will fail for non-fixed vector types.
484 return nullptr;
485
486 if (const auto *PV = dyn_cast<PoisonValue>(this))
487 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
488
489 if (const auto *UV = dyn_cast<UndefValue>(this))
490 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
491
492 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
493 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
494 : nullptr;
495
496 return nullptr;
497}
498
500 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
501 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
502 // Check if the constant fits into an uint64_t.
503 if (CI->getValue().getActiveBits() > 64)
504 return nullptr;
505 return getAggregateElement(CI->getZExtValue());
506 }
507 return nullptr;
508}
509
511 /// First call destroyConstantImpl on the subclass. This gives the subclass
512 /// a chance to remove the constant from any maps/pools it's contained in.
513 switch (getValueID()) {
514 default:
515 llvm_unreachable("Not a constant!");
516#define HANDLE_CONSTANT(Name) \
517 case Value::Name##Val: \
518 cast<Name>(this)->destroyConstantImpl(); \
519 break;
520#include "llvm/IR/Value.def"
521 }
522
523 // When a Constant is destroyed, there may be lingering
524 // references to the constant by other constants in the constant pool. These
525 // constants are implicitly dependent on the module that is being deleted,
526 // but they don't know that. Because we only find out when the CPV is
527 // deleted, we must now notify all of our users (that should only be
528 // Constants) that they are, in fact, invalid now and should be deleted.
529 //
530 while (!use_empty()) {
531 Value *V = user_back();
532#ifndef NDEBUG // Only in -g mode...
533 if (!isa<Constant>(V)) {
534 dbgs() << "While deleting: " << *this
535 << "\n\nUse still stuck around after Def is destroyed: " << *V
536 << "\n\n";
537 }
538#endif
539 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
540 cast<Constant>(V)->destroyConstant();
541
542 // The constant should remove itself from our use list...
543 assert((use_empty() || user_back() != V) && "Constant not removed!");
544 }
545
546 // Value has no outstanding references it is safe to delete it now...
547 deleteConstant(this);
548}
549
551 switch (C->getValueID()) {
552 case Constant::ConstantIntVal:
553 delete static_cast<ConstantInt *>(C);
554 break;
555 case Constant::ConstantByteVal:
556 delete static_cast<ConstantByte *>(C);
557 break;
558 case Constant::ConstantFPVal:
559 delete static_cast<ConstantFP *>(C);
560 break;
561 case Constant::ConstantAggregateZeroVal:
562 delete static_cast<ConstantAggregateZero *>(C);
563 break;
564 case Constant::ConstantArrayVal:
565 delete static_cast<ConstantArray *>(C);
566 break;
567 case Constant::ConstantStructVal:
568 delete static_cast<ConstantStruct *>(C);
569 break;
570 case Constant::ConstantVectorVal:
571 delete static_cast<ConstantVector *>(C);
572 break;
573 case Constant::ConstantPointerNullVal:
574 delete static_cast<ConstantPointerNull *>(C);
575 break;
576 case Constant::ConstantDataArrayVal:
577 delete static_cast<ConstantDataArray *>(C);
578 break;
579 case Constant::ConstantDataVectorVal:
580 delete static_cast<ConstantDataVector *>(C);
581 break;
582 case Constant::ConstantTokenNoneVal:
583 delete static_cast<ConstantTokenNone *>(C);
584 break;
585 case Constant::BlockAddressVal:
586 delete static_cast<BlockAddress *>(C);
587 break;
588 case Constant::DSOLocalEquivalentVal:
589 delete static_cast<DSOLocalEquivalent *>(C);
590 break;
591 case Constant::NoCFIValueVal:
592 delete static_cast<NoCFIValue *>(C);
593 break;
594 case Constant::ConstantPtrAuthVal:
595 delete static_cast<ConstantPtrAuth *>(C);
596 break;
597 case Constant::UndefValueVal:
598 delete static_cast<UndefValue *>(C);
599 break;
600 case Constant::PoisonValueVal:
601 delete static_cast<PoisonValue *>(C);
602 break;
603 case Constant::ConstantExprVal:
605 delete static_cast<CastConstantExpr *>(C);
606 else if (isa<BinaryConstantExpr>(C))
607 delete static_cast<BinaryConstantExpr *>(C);
609 delete static_cast<ExtractElementConstantExpr *>(C);
611 delete static_cast<InsertElementConstantExpr *>(C);
613 delete static_cast<ShuffleVectorConstantExpr *>(C);
615 delete static_cast<GetElementPtrConstantExpr *>(C);
616 else
617 llvm_unreachable("Unexpected constant expr");
618 break;
619 default:
620 llvm_unreachable("Unexpected constant");
621 }
622}
623
624/// Check if C contains a GlobalValue for which Predicate is true.
625static bool
627 bool (*Predicate)(const GlobalValue *)) {
630 WorkList.push_back(C);
631 Visited.insert(C);
632
633 while (!WorkList.empty()) {
634 const Constant *WorkItem = WorkList.pop_back_val();
635 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
636 if (Predicate(GV))
637 return true;
638 for (const Value *Op : WorkItem->operands()) {
639 const Constant *ConstOp = dyn_cast<Constant>(Op);
640 if (!ConstOp)
641 continue;
642 if (Visited.insert(ConstOp).second)
643 WorkList.push_back(ConstOp);
644 }
645 }
646 return false;
647}
648
650 auto DLLImportPredicate = [](const GlobalValue *GV) {
651 return GV->isThreadLocal();
652 };
653 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
654}
655
657 auto DLLImportPredicate = [](const GlobalValue *GV) {
658 return GV->hasDLLImportStorageClass();
659 };
660 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
661}
662
664 for (const User *U : users()) {
665 const Constant *UC = dyn_cast<Constant>(U);
666 if (!UC || isa<GlobalValue>(UC))
667 return true;
668
669 if (UC->isConstantUsed())
670 return true;
671 }
672 return false;
673}
674
676 return getRelocationInfo() == GlobalRelocation;
677}
678
680 return getRelocationInfo() != NoRelocation;
681}
682
683Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
684 if (isa<GlobalValue>(this))
685 return GlobalRelocation; // Global reference.
686
687 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
688 return BA->getFunction()->getRelocationInfo();
689
690 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
691 if (CE->getOpcode() == Instruction::Sub) {
692 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
693 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
694 if (LHS && RHS &&
695 (LHS->getOpcode() == Instruction::PtrToInt ||
696 LHS->getOpcode() == Instruction::PtrToAddr) &&
697 (RHS->getOpcode() == Instruction::PtrToInt ||
698 RHS->getOpcode() == Instruction::PtrToAddr)) {
699 Constant *LHSOp0 = LHS->getOperand(0);
700 Constant *RHSOp0 = RHS->getOperand(0);
701
702 // While raw uses of blockaddress need to be relocated, differences
703 // between two of them don't when they are for labels in the same
704 // function. This is a common idiom when creating a table for the
705 // indirect goto extension, so we handle it efficiently here.
706 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
707 cast<BlockAddress>(LHSOp0)->getFunction() ==
709 return NoRelocation;
710
711 // Relative pointers do not need to be dynamically relocated.
712 if (auto *RHSGV =
714 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
715 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
716 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
717 return LocalRelocation;
718 } else if (isa<DSOLocalEquivalent>(LHS)) {
719 if (RHSGV->isDSOLocal())
720 return LocalRelocation;
721 }
722 }
723 }
724 }
725 }
726
727 PossibleRelocationsTy Result = NoRelocation;
728 for (const Value *Op : operands())
729 Result = std::max(cast<Constant>(Op)->getRelocationInfo(), Result);
730
731 return Result;
732}
733
734/// Return true if the specified constantexpr is dead. This involves
735/// recursively traversing users of the constantexpr.
736/// If RemoveDeadUsers is true, also remove dead users at the same time.
737static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
738 if (isa<GlobalValue>(C)) return false; // Cannot remove this
739
740 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
741 while (I != E) {
743 if (!User) return false; // Non-constant usage;
744 if (!constantIsDead(User, RemoveDeadUsers))
745 return false; // Constant wasn't dead
746
747 // Just removed User, so the iterator was invalidated.
748 // Since we return immediately upon finding a live user, we can always
749 // restart from user_begin().
750 if (RemoveDeadUsers)
751 I = C->user_begin();
752 else
753 ++I;
754 }
755
756 if (RemoveDeadUsers) {
757 // If C is only used by metadata, it should not be preserved but should
758 // have its uses replaced.
760 const_cast<Constant *>(C)->destroyConstant();
761 }
762
763 return true;
764}
765
768 Value::const_user_iterator LastNonDeadUser = E;
769 while (I != E) {
771 if (!User) {
772 LastNonDeadUser = I;
773 ++I;
774 continue;
775 }
776
777 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
778 // If the constant wasn't dead, remember that this was the last live use
779 // and move on to the next constant.
780 LastNonDeadUser = I;
781 ++I;
782 continue;
783 }
784
785 // If the constant was dead, then the iterator is invalidated.
786 if (LastNonDeadUser == E)
787 I = user_begin();
788 else
789 I = std::next(LastNonDeadUser);
790 }
791}
792
793bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
794
795bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
796
797bool Constant::hasNLiveUses(unsigned N) const {
798 unsigned NumUses = 0;
799 for (const Use &U : uses()) {
800 const Constant *User = dyn_cast<Constant>(U.getUser());
801 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
802 ++NumUses;
803
804 if (NumUses > N)
805 return false;
806 }
807 }
808 return NumUses == N;
809}
810
812 assert(C && Replacement && "Expected non-nullptr constant arguments");
813 Type *Ty = C->getType();
814 if (match(C, m_Undef())) {
815 assert(Ty == Replacement->getType() && "Expected matching types");
816 return Replacement;
817 }
818
819 // Don't know how to deal with this constant.
820 auto *VTy = dyn_cast<FixedVectorType>(Ty);
821 if (!VTy)
822 return C;
823
824 unsigned NumElts = VTy->getNumElements();
825 SmallVector<Constant *, 32> NewC(NumElts);
826 for (unsigned i = 0; i != NumElts; ++i) {
827 Constant *EltC = C->getAggregateElement(i);
828 assert((!EltC || EltC->getType() == Replacement->getType()) &&
829 "Expected matching types");
830 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
831 }
832 return ConstantVector::get(NewC);
833}
834
836 assert(C && Other && "Expected non-nullptr constant arguments");
837 if (match(C, m_Undef()))
838 return C;
839
840 Type *Ty = C->getType();
841 if (match(Other, m_Undef()))
842 return UndefValue::get(Ty);
843
844 auto *VTy = dyn_cast<FixedVectorType>(Ty);
845 if (!VTy)
846 return C;
847
848 Type *EltTy = VTy->getElementType();
849 unsigned NumElts = VTy->getNumElements();
850 assert(isa<FixedVectorType>(Other->getType()) &&
851 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
852 "Type mismatch");
853
854 bool FoundExtraUndef = false;
855 SmallVector<Constant *, 32> NewC(NumElts);
856 for (unsigned I = 0; I != NumElts; ++I) {
857 NewC[I] = C->getAggregateElement(I);
858 Constant *OtherEltC = Other->getAggregateElement(I);
859 assert(NewC[I] && OtherEltC && "Unknown vector element");
860 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
861 NewC[I] = UndefValue::get(EltTy);
862 FoundExtraUndef = true;
863 }
864 }
865 if (FoundExtraUndef)
866 return ConstantVector::get(NewC);
867 return C;
868}
869
871 if (isa<UndefValue>(this))
872 return false;
873 if (isa<ConstantData>(this))
874 return true;
875 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
876 for (const Value *Op : operand_values())
878 return false;
879 return true;
880 }
881 return false;
882}
883
884//===----------------------------------------------------------------------===//
885// ConstantInt
886//===----------------------------------------------------------------------===//
887
888ConstantInt::ConstantInt(Type *Ty, const APInt &V)
889 : ConstantData(Ty, ConstantIntVal), Val(V) {
890 assert(V.getBitWidth() ==
891 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
892 "Invalid constant for type");
893 if (V.isZero())
895}
896
897ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
898 LLVMContextImpl *pImpl = Context.pImpl;
899 if (!pImpl->TheTrueVal)
900 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
901 return pImpl->TheTrueVal;
902}
903
904ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
905 LLVMContextImpl *pImpl = Context.pImpl;
906 if (!pImpl->TheFalseVal)
907 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
908 return pImpl->TheFalseVal;
909}
910
911ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
912 return V ? getTrue(Context) : getFalse(Context);
913}
914
916 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
917 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
918 if (auto *VTy = dyn_cast<VectorType>(Ty))
919 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
920 return TrueC;
921}
922
924 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
925 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
926 if (auto *VTy = dyn_cast<VectorType>(Ty))
927 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
928 return FalseC;
929}
930
932 return V ? getTrue(Ty) : getFalse(Ty);
933}
934
935// Get a ConstantInt from an APInt.
936ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
937 // get an existing value or the insertion position
938 LLVMContextImpl *pImpl = Context.pImpl;
939 std::unique_ptr<ConstantInt> &Slot =
940 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
941 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
942 : pImpl->IntConstants[V];
943 if (!Slot) {
944 // Get the corresponding integer type for the bit width of the value.
945 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
946 Slot.reset(new ConstantInt(ITy, V));
947 }
948 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
949 return Slot.get();
950}
951
952// Get a ConstantInt vector with each lane set to the same APInt.
953ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
954 const APInt &V) {
955 // Get an existing value or the insertion position.
956 std::unique_ptr<ConstantInt> &Slot =
957 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
958 if (!Slot) {
959 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
960 VectorType *VTy = VectorType::get(ITy, EC);
961 Slot.reset(new ConstantInt(VTy, V));
962 }
963
964#ifndef NDEBUG
965 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
966 VectorType *VTy = VectorType::get(ITy, EC);
967 assert(Slot->getType() == VTy);
968#endif
969 return Slot.get();
970}
971
972Constant *ConstantInt::get(Type *Ty, uint64_t V, bool IsSigned,
973 bool ImplicitTrunc) {
974 Constant *C =
975 get(cast<IntegerType>(Ty->getScalarType()), V, IsSigned, ImplicitTrunc);
976
977 // For vectors, broadcast the value.
978 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
979 return ConstantVector::getSplat(VTy->getElementCount(), C);
980
981 return C;
982}
983
984ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool IsSigned,
985 bool ImplicitTrunc) {
986 return get(Ty->getContext(),
987 APInt(Ty->getBitWidth(), V, IsSigned, ImplicitTrunc));
988}
989
990Constant *ConstantInt::get(Type *Ty, const APInt& V) {
991 ConstantInt *C = get(Ty->getContext(), V);
992 assert(C->getType() == Ty->getScalarType() &&
993 "ConstantInt type doesn't match the type implied by its value!");
994
995 // For vectors, broadcast the value.
996 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
997 return ConstantVector::getSplat(VTy->getElementCount(), C);
998
999 return C;
1000}
1001
1002ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
1003 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1004}
1005
1006/// Remove the constant from the constant table.
1007void ConstantInt::destroyConstantImpl() {
1008 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
1009}
1010
1011//===----------------------------------------------------------------------===//
1012// ConstantByte
1013//===----------------------------------------------------------------------===//
1014
1015ConstantByte::ConstantByte(Type *Ty, const APInt &V)
1016 : ConstantData(Ty, ConstantByteVal), Val(V) {
1017 assert(V.getBitWidth() ==
1018 cast<ByteType>(Ty->getScalarType())->getBitWidth() &&
1019 "Invalid constant for type");
1020 if (V.isZero())
1022}
1023
1024// Get a ConstantByte from an APInt.
1025ConstantByte *ConstantByte::get(LLVMContext &Context, const APInt &V) {
1026 // get an existing value or the insertion position
1027 LLVMContextImpl *pImpl = Context.pImpl;
1028 std::unique_ptr<ConstantByte> &Slot =
1029 V.isZero() ? pImpl->ByteZeroConstants[V.getBitWidth()]
1030 : V.isOne() ? pImpl->ByteOneConstants[V.getBitWidth()]
1031 : pImpl->ByteConstants[V];
1032 if (!Slot) {
1033 // Get the corresponding byte type for the bit width of the value.
1034 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1035 Slot.reset(new ConstantByte(BTy, V));
1036 }
1037 assert(Slot->getType() == ByteType::get(Context, V.getBitWidth()));
1038 return Slot.get();
1039}
1040
1041// Get a ConstantByte vector with each lane set to the same APInt.
1042ConstantByte *ConstantByte::get(LLVMContext &Context, ElementCount EC,
1043 const APInt &V) {
1044 // Get an existing value or the insertion position.
1045 std::unique_ptr<ConstantByte> &Slot =
1046 Context.pImpl->ByteSplatConstants[std::make_pair(EC, V)];
1047 if (!Slot) {
1048 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1049 VectorType *VTy = VectorType::get(BTy, EC);
1050 Slot.reset(new ConstantByte(VTy, V));
1051 }
1052
1053#ifndef NDEBUG
1054 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1055 VectorType *VTy = VectorType::get(BTy, EC);
1056 assert(Slot->getType() == VTy);
1057#endif
1058 return Slot.get();
1059}
1060
1061Constant *ConstantByte::get(Type *Ty, uint64_t V, bool isSigned,
1062 bool ImplicitTrunc) {
1063 Constant *C =
1064 get(cast<ByteType>(Ty->getScalarType()), V, isSigned, ImplicitTrunc);
1065
1066 // For vectors, broadcast the value.
1067 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1068 return ConstantVector::getSplat(VTy->getElementCount(), C);
1069
1070 return C;
1071}
1072
1073ConstantByte *ConstantByte::get(ByteType *Ty, uint64_t V, bool isSigned,
1074 bool ImplicitTrunc) {
1075 return get(Ty->getContext(),
1076 APInt(Ty->getBitWidth(), V, isSigned, ImplicitTrunc));
1077}
1078
1079Constant *ConstantByte::get(Type *Ty, const APInt &V) {
1080 ConstantByte *C = get(Ty->getContext(), V);
1081 assert(C->getType() == Ty->getScalarType() &&
1082 "ConstantByte type doesn't match the type implied by its value!");
1083
1084 // For vectors, broadcast the value.
1085 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1086 return ConstantVector::getSplat(VTy->getElementCount(), C);
1087
1088 return C;
1089}
1090
1091ConstantByte *ConstantByte::get(ByteType *Ty, StringRef Str, uint8_t radix) {
1092 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1093}
1094
1095/// Remove the constant from the constant table.
1096void ConstantByte::destroyConstantImpl() {
1097 llvm_unreachable("You can't ConstantByte->destroyConstantImpl()!");
1098}
1099
1100//===----------------------------------------------------------------------===//
1101// ConstantFP
1102//===----------------------------------------------------------------------===//
1103
1104ConstantFP *ConstantFP::get(Type *Ty, double V) {
1105 LLVMContext &Context = Ty->getContext();
1106
1107 APFloat FV(V);
1108 bool ignored;
1109 FV.convert(Ty->getScalarType()->getFltSemantics(),
1111
1112 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1113 return get(Context, VTy->getElementCount(), FV);
1114
1115 return get(Context, FV);
1116}
1117
1118ConstantFP *ConstantFP::get(Type *Ty, const APFloat &V) {
1119 LLVMContext &Context = Ty->getContext();
1120 assert(Ty->getScalarType() ==
1121 Type::getFloatingPointTy(Context, V.getSemantics()) &&
1122 "ConstantFP type doesn't match the type implied by its value!");
1123
1124 if (auto *VTy = dyn_cast<VectorType>(Ty))
1125 return get(Context, VTy->getElementCount(), V);
1126
1127 return get(Ty->getContext(), V);
1128}
1129
1130ConstantFP *ConstantFP::get(Type *Ty, StringRef Str) {
1131 LLVMContext &Context = Ty->getContext();
1132 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1133
1134 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1135 return get(Context, VTy->getElementCount(), FV);
1136
1137 return get(Context, FV);
1138}
1139
1140ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1141 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1142 return get(Ty, APFloat::getInf(Semantics, Negative));
1143}
1144
1145ConstantFP *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1146 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1147 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1148 return get(Ty, NaN);
1149}
1150
1151ConstantFP *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1152 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1153 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1154 return get(Ty, NaN);
1155}
1156
1157ConstantFP *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1158 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1159 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1160 return get(Ty, NaN);
1161}
1162
1163ConstantFP *ConstantFP::getZero(Type *Ty, bool Negative) {
1164 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1165 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1166 return get(Ty, NegZero);
1167}
1168
1169// ConstantFP accessors.
1170ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1171 LLVMContextImpl* pImpl = Context.pImpl;
1172
1173 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1174
1175 if (!Slot) {
1176 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1177 Slot.reset(new ConstantFP(Ty, V));
1178 }
1179
1180 return Slot.get();
1181}
1182
1183// Get a ConstantFP vector with each lane set to the same APFloat.
1184ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1185 const APFloat &V) {
1186 // Get an existing value or the insertion position.
1187 std::unique_ptr<ConstantFP> &Slot =
1188 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1189 if (!Slot) {
1190 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1191 VectorType *VTy = VectorType::get(EltTy, EC);
1192 Slot.reset(new ConstantFP(VTy, V));
1193 }
1194
1195#ifndef NDEBUG
1196 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1197 VectorType *VTy = VectorType::get(EltTy, EC);
1198 assert(Slot->getType() == VTy);
1199#endif
1200 return Slot.get();
1201}
1202
1203ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1204 : ConstantData(Ty, ConstantFPVal), Val(V) {
1205 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1206 "FP type Mismatch");
1207 // ppc_fp128 determine isZero using high order double only
1208 // so check the bitwise value to make sure all bits are zero.
1209 if (V.bitcastToAPInt().isZero())
1211}
1212
1214 return Val.bitwiseIsEqual(V);
1215}
1216
1217/// Remove the constant from the constant table.
1218void ConstantFP::destroyConstantImpl() {
1219 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1220}
1221
1222//===----------------------------------------------------------------------===//
1223// ConstantAggregateZero Implementation
1224//===----------------------------------------------------------------------===//
1225
1227 if (auto *AT = dyn_cast<ArrayType>(getType()))
1228 return Constant::getNullValue(AT->getElementType());
1229 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1230}
1231
1233 return Constant::getNullValue(getType()->getStructElementType(Elt));
1234}
1235
1241
1244 return getSequentialElement();
1245 return getStructElement(Idx);
1246}
1247
1249 Type *Ty = getType();
1250 if (auto *AT = dyn_cast<ArrayType>(Ty))
1251 return ElementCount::getFixed(AT->getNumElements());
1252 if (auto *VT = dyn_cast<VectorType>(Ty))
1253 return VT->getElementCount();
1254 return ElementCount::getFixed(Ty->getStructNumElements());
1255}
1256
1257//===----------------------------------------------------------------------===//
1258// UndefValue Implementation
1259//===----------------------------------------------------------------------===//
1260
1263 return UndefValue::get(ATy->getElementType());
1264 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1265}
1266
1267UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1268 return UndefValue::get(getType()->getStructElementType(Elt));
1269}
1270
1273 return getSequentialElement();
1274 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1275}
1276
1277UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1279 return getSequentialElement();
1280 return getStructElement(Idx);
1281}
1282
1284 Type *Ty = getType();
1285 if (auto *AT = dyn_cast<ArrayType>(Ty))
1286 return AT->getNumElements();
1287 if (auto *VT = dyn_cast<VectorType>(Ty))
1288 return cast<FixedVectorType>(VT)->getNumElements();
1289 return Ty->getStructNumElements();
1290}
1291
1292//===----------------------------------------------------------------------===//
1293// PoisonValue Implementation
1294//===----------------------------------------------------------------------===//
1295
1298 return PoisonValue::get(ATy->getElementType());
1299 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1300}
1301
1302PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1303 return PoisonValue::get(getType()->getStructElementType(Elt));
1304}
1305
1308 return getSequentialElement();
1309 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1310}
1311
1312PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1314 return getSequentialElement();
1315 return getStructElement(Idx);
1316}
1317
1318//===----------------------------------------------------------------------===//
1319// ConstantXXX Classes
1320//===----------------------------------------------------------------------===//
1321
1322template <typename ItTy, typename EltTy>
1323static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1324 for (; Start != End; ++Start)
1325 if (*Start != Elt)
1326 return false;
1327 return true;
1328}
1329
1330template <typename SequentialTy, typename ElementTy>
1332 assert(!V.empty() && "Cannot get empty int sequence.");
1333
1335 for (Constant *C : V)
1336 if (auto *CI = dyn_cast<ConstantInt>(C))
1337 Elts.push_back(CI->getZExtValue());
1338 else
1339 return nullptr;
1340 return SequentialTy::get(V[0]->getContext(), Elts);
1341}
1342
1343template <typename SequentialTy, typename ElementTy>
1345 assert(!V.empty() && "Cannot get empty byte sequence.");
1346
1348 for (Constant *C : V)
1349 if (auto *CI = dyn_cast<ConstantByte>(C))
1350 Elts.push_back(CI->getZExtValue());
1351 else
1352 return nullptr;
1353 return SequentialTy::getByte(V[0]->getType(), Elts);
1354}
1355
1356template <typename SequentialTy, typename ElementTy>
1358 assert(!V.empty() && "Cannot get empty FP sequence.");
1359
1361 for (Constant *C : V)
1362 if (auto *CFP = dyn_cast<ConstantFP>(C))
1363 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1364 else
1365 return nullptr;
1366 return SequentialTy::getFP(V[0]->getType(), Elts);
1367}
1368
1369template <typename SequenceTy>
1372 // We speculatively build the elements here even if it turns out that there is
1373 // a constantexpr or something else weird, since it is so uncommon for that to
1374 // happen.
1375 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1376 if (CI->getType()->isIntegerTy(8))
1378 else if (CI->getType()->isIntegerTy(16))
1380 else if (CI->getType()->isIntegerTy(32))
1382 else if (CI->getType()->isIntegerTy(64))
1384 } else if (ConstantByte *CB = dyn_cast<ConstantByte>(C)) {
1385 if (CB->getType()->isByteTy(8))
1387 else if (CB->getType()->isByteTy(16))
1389 else if (CB->getType()->isByteTy(32))
1391 else if (CB->getType()->isByteTy(64))
1393 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1394 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1396 else if (CFP->getType()->isFloatTy())
1398 else if (CFP->getType()->isDoubleTy())
1400 }
1401
1402 return nullptr;
1403}
1404
1408 : Constant(T, VT, AllocInfo) {
1409 llvm::copy(V, op_begin());
1410
1411 // Check that types match, unless this is an opaque struct.
1412 if (auto *ST = dyn_cast<StructType>(T)) {
1413 if (ST->isOpaque())
1414 return;
1415 for (unsigned I = 0, E = V.size(); I != E; ++I)
1416 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1417 "Initializer for struct element doesn't match!");
1418 }
1419}
1420
1421ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1423 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1424 assert(V.size() == T->getNumElements() &&
1425 "Invalid initializer for constant array");
1426}
1427
1429 if (Constant *C = getImpl(Ty, V))
1430 return C;
1431 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1432}
1433
1434Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1435 // Empty arrays are canonicalized to ConstantAggregateZero.
1436 if (V.empty())
1437 return ConstantAggregateZero::get(Ty);
1438
1439 for (Constant *C : V) {
1440 assert(C->getType() == Ty->getElementType() &&
1441 "Wrong type in array element initializer");
1442 (void)C;
1443 }
1444
1445 // If this is an all-zero array, return a ConstantAggregateZero object. If
1446 // all undef, return an UndefValue, if "all simple", then return a
1447 // ConstantDataArray.
1448 Constant *C = V[0];
1449 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1450 return PoisonValue::get(Ty);
1451
1452 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1453 return UndefValue::get(Ty);
1454
1455 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1456 return ConstantAggregateZero::get(Ty);
1457
1458 // Check to see if all of the elements are ConstantFP or ConstantInt or
1459 // ConstantByte and if the element type is compatible with ConstantDataVector.
1460 // If so, use it.
1463
1464 // Otherwise, we really do want to create a ConstantArray.
1465 return nullptr;
1466}
1467
1470 bool Packed) {
1471 unsigned VecSize = V.size();
1472 SmallVector<Type*, 16> EltTypes(VecSize);
1473 for (unsigned i = 0; i != VecSize; ++i)
1474 EltTypes[i] = V[i]->getType();
1475
1476 return StructType::get(Context, EltTypes, Packed);
1477}
1478
1479
1481 bool Packed) {
1482 assert(!V.empty() &&
1483 "ConstantStruct::getTypeForElements cannot be called on empty list");
1484 return getTypeForElements(V[0]->getContext(), V, Packed);
1485}
1486
1487ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1489 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1490 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1491 "Invalid initializer for constant struct");
1492}
1493
1494// ConstantStruct accessors.
1496 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1497 "Incorrect # elements specified to ConstantStruct::get");
1498
1499 // Create a ConstantAggregateZero value if all elements are zeros.
1500 bool isZero = true;
1501 bool isUndef = false;
1502 bool isPoison = false;
1503
1504 if (!V.empty()) {
1505 isUndef = isa<UndefValue>(V[0]);
1506 isPoison = isa<PoisonValue>(V[0]);
1507 isZero = V[0]->isNullValue();
1508 // PoisonValue inherits UndefValue, so its check is not necessary.
1509 if (isUndef || isZero) {
1510 for (Constant *C : V) {
1511 if (!C->isNullValue())
1512 isZero = false;
1513 if (!isa<PoisonValue>(C))
1514 isPoison = false;
1516 isUndef = false;
1517 }
1518 }
1519 }
1520 if (isZero)
1521 return ConstantAggregateZero::get(ST);
1522 if (isPoison)
1523 return PoisonValue::get(ST);
1524 if (isUndef)
1525 return UndefValue::get(ST);
1526
1527 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1528}
1529
1530ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1532 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1533 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1534 "Invalid initializer for constant vector");
1535}
1536
1537// ConstantVector accessors.
1539 if (Constant *C = getImpl(V))
1540 return C;
1541 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1542 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1543}
1544
1545Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1546 assert(!V.empty() && "Vectors can't be empty");
1547 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1548
1549 // If this is an all-undef or all-zero vector, return a
1550 // ConstantAggregateZero or UndefValue.
1551 Constant *C = V[0];
1552 bool isZero = C->isNullValue();
1553 bool isUndef = isa<UndefValue>(C);
1554 bool isPoison = isa<PoisonValue>(C);
1555 bool isSplatFP = isa<ConstantFP>(C);
1557 bool isSplatByte = isa<ConstantByte>(C);
1558 bool isSplatPtrNull = isa<ConstantPointerNull>(C);
1559
1560 if (isZero || isUndef || isSplatFP || isSplatInt || isSplatByte ||
1561 isSplatPtrNull) {
1562 for (unsigned i = 1, e = V.size(); i != e; ++i)
1563 if (V[i] != C) {
1564 isZero = isUndef = isPoison = isSplatFP = isSplatInt = isSplatByte =
1565 isSplatPtrNull = false;
1566 break;
1567 }
1568 }
1569
1570 if (isSplatPtrNull)
1572 if (isZero)
1574 if (isPoison)
1575 return PoisonValue::get(T);
1576 if (isUndef)
1577 return UndefValue::get(T);
1578 if (isSplatFP)
1579 return ConstantFP::get(C->getContext(), T->getElementCount(),
1580 cast<ConstantFP>(C)->getValue());
1581 if (isSplatInt)
1582 return ConstantInt::get(C->getContext(), T->getElementCount(),
1583 cast<ConstantInt>(C)->getValue());
1584 if (isSplatByte)
1585 return ConstantByte::get(C->getContext(), T->getElementCount(),
1586 cast<ConstantByte>(C)->getValue());
1587
1588 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1589 // the element type is compatible with ConstantDataVector. If so, use it.
1592
1593 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1594 // the operand list contains a ConstantExpr or something else strange.
1595 return nullptr;
1596}
1597
1599 if (isa<ConstantPointerNull>(V)) {
1600 VectorType *VTy = VectorType::get(V->getType(), EC);
1601 return ConstantPointerNull::get(VTy);
1602 }
1603
1604 if (auto *CB = dyn_cast<ConstantByte>(V))
1605 return ConstantByte::get(V->getContext(), EC, CB->getValue());
1606
1607 if (auto *CFP = dyn_cast<ConstantFP>(V))
1608 return ConstantFP::get(V->getContext(), EC, CFP->getValue());
1609
1610 if (!EC.isScalable()) {
1611 // Maintain special handling of zero.
1612 if (!V->isNullValue()) {
1614 return ConstantInt::get(V->getContext(), EC,
1615 cast<ConstantInt>(V)->getValue());
1616 }
1617
1618 // If this splat is compatible with ConstantDataVector, use it instead of
1619 // ConstantVector.
1620 if (isa<ConstantInt>(V) &&
1622 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1623
1624 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1625 return get(Elts);
1626 }
1627
1628 // Maintain special handling of zero.
1629 if (!V->isNullValue()) {
1631 return ConstantInt::get(V->getContext(), EC,
1632 cast<ConstantInt>(V)->getValue());
1633 }
1634
1635 Type *VTy = VectorType::get(V->getType(), EC);
1636
1637 if (V->isNullValue())
1638 return ConstantAggregateZero::get(VTy);
1639 if (isa<PoisonValue>(V))
1640 return PoisonValue::get(VTy);
1641 if (isa<UndefValue>(V))
1642 return UndefValue::get(VTy);
1643
1644 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1645
1646 // Move scalar into vector.
1647 Constant *PoisonV = PoisonValue::get(VTy);
1648 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1649 // Build shuffle mask to perform the splat.
1650 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1651 // Splat.
1652 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1653}
1654
1655ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1656 LLVMContextImpl *pImpl = Context.pImpl;
1657 if (!pImpl->TheNoneToken)
1658 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1659 return pImpl->TheNoneToken.get();
1660}
1661
1662/// Remove the constant from the constant table.
1663void ConstantTokenNone::destroyConstantImpl() {
1664 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1665}
1666
1667// Utility function for determining if a ConstantExpr is a CastOp or not. This
1668// can't be inline because we don't want to #include Instruction.h into
1669// Constant.h
1671
1675
1677 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1678}
1679
1681 bool OnlyIfReduced, Type *SrcTy) const {
1682 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1683
1684 // If no operands changed return self.
1685 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1686 return const_cast<ConstantExpr*>(this);
1687
1688 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1689 switch (getOpcode()) {
1690 case Instruction::Trunc:
1691 case Instruction::ZExt:
1692 case Instruction::SExt:
1693 case Instruction::FPTrunc:
1694 case Instruction::FPExt:
1695 case Instruction::UIToFP:
1696 case Instruction::SIToFP:
1697 case Instruction::FPToUI:
1698 case Instruction::FPToSI:
1699 case Instruction::PtrToAddr:
1700 case Instruction::PtrToInt:
1701 case Instruction::IntToPtr:
1702 case Instruction::BitCast:
1703 case Instruction::AddrSpaceCast:
1704 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1705 case Instruction::InsertElement:
1706 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1707 OnlyIfReducedTy);
1708 case Instruction::ExtractElement:
1709 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1710 case Instruction::ShuffleVector:
1712 OnlyIfReducedTy);
1713 case Instruction::GetElementPtr: {
1714 auto *GEPO = cast<GEPOperator>(this);
1715 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1717 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1718 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1719 }
1720 default:
1721 assert(getNumOperands() == 2 && "Must be binary operator?");
1723 OnlyIfReducedTy);
1724 }
1725}
1726
1727
1728//===----------------------------------------------------------------------===//
1729// isValueValidForType implementations
1730
1732 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1733 if (Ty->isIntegerTy(1))
1734 return Val == 0 || Val == 1;
1735 return isUIntN(NumBits, Val);
1736}
1737
1739 unsigned NumBits = Ty->getIntegerBitWidth();
1740 if (Ty->isIntegerTy(1))
1741 return Val == 0 || Val == 1 || Val == -1;
1742 return isIntN(NumBits, Val);
1743}
1744
1746 // convert modifies in place, so make a copy.
1747 APFloat Val2 = APFloat(Val);
1748 bool losesInfo;
1749 switch (Ty->getTypeID()) {
1750 default:
1751 return false; // These can't be represented as floating point!
1752
1753 // FIXME rounding mode needs to be more flexible
1754 case Type::HalfTyID: {
1755 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1756 return true;
1758 return !losesInfo;
1759 }
1760 case Type::BFloatTyID: {
1761 if (&Val2.getSemantics() == &APFloat::BFloat())
1762 return true;
1764 return !losesInfo;
1765 }
1766 case Type::FloatTyID: {
1767 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1768 return true;
1770 return !losesInfo;
1771 }
1772 case Type::DoubleTyID: {
1773 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1774 &Val2.getSemantics() == &APFloat::BFloat() ||
1775 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1776 &Val2.getSemantics() == &APFloat::IEEEdouble())
1777 return true;
1779 return !losesInfo;
1780 }
1781 case Type::X86_FP80TyID:
1782 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1783 &Val2.getSemantics() == &APFloat::BFloat() ||
1784 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1785 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1787 case Type::FP128TyID:
1788 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1789 &Val2.getSemantics() == &APFloat::BFloat() ||
1790 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1791 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1792 &Val2.getSemantics() == &APFloat::IEEEquad();
1794 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1795 &Val2.getSemantics() == &APFloat::BFloat() ||
1796 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1797 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1799 }
1800}
1801
1802
1803//===----------------------------------------------------------------------===//
1804// Factory Function Implementation
1805
1806ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1807 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1808 "Cannot create an aggregate zero of non-aggregate type!");
1809
1810 std::unique_ptr<ConstantAggregateZero> &Entry =
1811 Ty->getContext().pImpl->CAZConstants[Ty];
1812 if (!Entry)
1813 Entry.reset(new ConstantAggregateZero(Ty));
1814
1815 return Entry.get();
1816}
1817
1818/// Remove the constant from the constant table.
1819void ConstantAggregateZero::destroyConstantImpl() {
1821}
1822
1823/// Remove the constant from the constant table.
1824void ConstantArray::destroyConstantImpl() {
1826}
1827
1828
1829//---- ConstantStruct::get() implementation...
1830//
1831
1832/// Remove the constant from the constant table.
1833void ConstantStruct::destroyConstantImpl() {
1835}
1836
1837/// Remove the constant from the constant table.
1838void ConstantVector::destroyConstantImpl() {
1840}
1841
1842Constant *Constant::getSplatValue(bool AllowPoison) const {
1843 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1844 if (isa<PoisonValue>(this))
1845 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1847 return getNullValue(cast<VectorType>(getType())->getElementType());
1848 if (auto *CI = dyn_cast<ConstantInt>(this))
1849 return ConstantInt::get(getContext(), CI->getValue());
1850 if (auto *CB = dyn_cast<ConstantByte>(this))
1851 return ConstantByte::get(getContext(), CB->getValue());
1852 if (auto *CFP = dyn_cast<ConstantFP>(this))
1853 return ConstantFP::get(getContext(), CFP->getValue());
1854 if (auto *CPN = dyn_cast<ConstantPointerNull>(this))
1855 return ConstantPointerNull::get(CPN->getPointerType());
1857 return CV->getSplatValue();
1858 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1859 return CV->getSplatValue(AllowPoison);
1860
1861 // Check if this is a constant expression splat of the form returned by
1862 // ConstantVector::getSplat()
1863 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1864 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1865 isa<UndefValue>(Shuf->getOperand(1))) {
1866
1867 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1868 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1869 isa<UndefValue>(IElt->getOperand(0))) {
1870
1871 ArrayRef<int> Mask = Shuf->getShuffleMask();
1872 Constant *SplatVal = IElt->getOperand(1);
1873 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1874
1875 if (Index && Index->getValue() == 0 && llvm::all_of(Mask, equal_to(0)))
1876 return SplatVal;
1877 }
1878 }
1879
1880 return nullptr;
1881}
1882
1883Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1884 // Check out first element.
1885 Constant *Elt = getOperand(0);
1886 // Then make sure all remaining elements point to the same value.
1887 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1888 Constant *OpC = getOperand(I);
1889 if (OpC == Elt)
1890 continue;
1891
1892 // Strict mode: any mismatch is not a splat.
1893 if (!AllowPoison)
1894 return nullptr;
1895
1896 // Allow poison mode: ignore poison elements.
1897 if (isa<PoisonValue>(OpC))
1898 continue;
1899
1900 // If we do not have a defined element yet, use the current operand.
1901 if (isa<PoisonValue>(Elt))
1902 Elt = OpC;
1903
1904 if (OpC != Elt)
1905 return nullptr;
1906 }
1907 return Elt;
1908}
1909
1911 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1912 return CI->getValue();
1913 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
1914 return CB->getValue();
1915 // Scalable vectors can use a ConstantExpr to build a splat.
1916 if (isa<ConstantExpr>(this))
1917 return cast<ConstantInt>(this->getSplatValue())->getValue();
1918 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1919 // calling getSplatValue in release builds.
1920 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1921 const Constant *C = this->getAggregateElement(0U);
1922 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1923 return cast<ConstantInt>(C)->getValue();
1924}
1925
1927 if (auto *CI = dyn_cast<ConstantInt>(this))
1928 return ConstantRange(CI->getValue());
1929
1930 unsigned BitWidth = getType()->getScalarSizeInBits();
1931 if (!getType()->isVectorTy())
1932 return ConstantRange::getFull(BitWidth);
1933
1934 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1935 getSplatValue(/*AllowPoison=*/true)))
1936 return ConstantRange(CI->getValue());
1937
1938 if (auto *CB =
1939 dyn_cast_or_null<ConstantByte>(getSplatValue(/*AllowPoison=*/true)))
1940 return ConstantRange(CB->getValue());
1941
1942 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1943 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1944 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1945 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1946 return CR;
1947 }
1948
1949 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1950 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1951 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1952 Constant *Elem = CV->getOperand(I);
1953 if (!Elem)
1954 return ConstantRange::getFull(BitWidth);
1955 if (isa<PoisonValue>(Elem))
1956 continue;
1957 auto *CI = dyn_cast<ConstantInt>(Elem);
1958 auto *CB = dyn_cast<ConstantByte>(Elem);
1959 if (!CI && !CB)
1960 return ConstantRange::getFull(BitWidth);
1961 CR = CR.unionWith(CI ? CI->getValue() : CB->getValue());
1962 }
1963 return CR;
1964 }
1965
1966 return ConstantRange::getFull(BitWidth);
1967}
1968
1969//---- ConstantPointerNull::get() implementation.
1970//
1971
1972ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1973 return get(static_cast<Type *>(Ty));
1974}
1975
1976ConstantPointerNull *ConstantPointerNull::get(Type *Ty) {
1977 assert(Ty->isPtrOrPtrVectorTy() && "invalid type for null pointer constant");
1978 std::unique_ptr<ConstantPointerNull> &Entry =
1979 Ty->getContext().pImpl->CPNConstants[Ty];
1980 if (!Entry)
1981 Entry.reset(new ConstantPointerNull(Ty));
1982
1983 assert(Entry->getType() == Ty);
1984 return Entry.get();
1985}
1986
1987/// Remove the constant from the constant table.
1988void ConstantPointerNull::destroyConstantImpl() {
1990}
1991
1992//---- ConstantTargetNone::get() implementation.
1993//
1994
1995ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
1996 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
1997 "Target extension type not allowed to have a zeroinitializer");
1998 std::unique_ptr<ConstantTargetNone> &Entry =
1999 Ty->getContext().pImpl->CTNConstants[Ty];
2000 if (!Entry)
2001 Entry.reset(new ConstantTargetNone(Ty));
2002
2003 return Entry.get();
2004}
2005
2006/// Remove the constant from the constant table.
2007void ConstantTargetNone::destroyConstantImpl() {
2009}
2010
2011UndefValue *UndefValue::get(Type *Ty) {
2012 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
2013 if (!Entry)
2014 Entry.reset(new UndefValue(Ty));
2015
2016 return Entry.get();
2017}
2018
2019/// Remove the constant from the constant table.
2020void UndefValue::destroyConstantImpl() {
2021 // Free the constant and any dangling references to it.
2022 if (getValueID() == UndefValueVal) {
2023 getContext().pImpl->UVConstants.erase(getType());
2024 } else if (getValueID() == PoisonValueVal) {
2025 getContext().pImpl->PVConstants.erase(getType());
2026 }
2027 llvm_unreachable("Not a undef or a poison!");
2028}
2029
2030PoisonValue *PoisonValue::get(Type *Ty) {
2031 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
2032 if (!Entry)
2033 Entry.reset(new PoisonValue(Ty));
2034
2035 return Entry.get();
2036}
2037
2038/// Remove the constant from the constant table.
2039void PoisonValue::destroyConstantImpl() {
2040 // Free the constant and any dangling references to it.
2041 getContext().pImpl->PVConstants.erase(getType());
2042}
2043
2044BlockAddress *BlockAddress::get(Type *Ty, BasicBlock *BB) {
2045 BlockAddress *&BA = BB->getContext().pImpl->BlockAddresses[BB];
2046 if (!BA)
2047 BA = new BlockAddress(Ty, BB);
2048 return BA;
2049}
2050
2051BlockAddress *BlockAddress::get(BasicBlock *BB) {
2052 assert(BB->getParent() && "Block must have a parent");
2053 return get(BB->getParent()->getType(), BB);
2054}
2055
2057 assert(BB->getParent() == F && "Block not part of specified function");
2058 return get(BB->getParent()->getType(), BB);
2059}
2060
2061BlockAddress::BlockAddress(Type *Ty, BasicBlock *BB)
2062 : Constant(Ty, Value::BlockAddressVal, AllocMarker) {
2063 Block = BB;
2064 BB->setHasAddressTaken(true);
2065}
2066
2067BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
2068 if (!BB->hasAddressTaken())
2069 return nullptr;
2070
2071 BlockAddress *BA = BB->getContext().pImpl->BlockAddresses.lookup(BB);
2072 assert(BA && "Refcount and block address map disagree!");
2073 return BA;
2074}
2075
2076/// Remove the constant from the constant table.
2077void BlockAddress::destroyConstantImpl() {
2079 getBasicBlock()->setHasAddressTaken(false);
2080}
2081
2082Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
2083 assert(From == getBasicBlock());
2084 BasicBlock *NewBB = cast<BasicBlock>(To);
2085
2086 // See if the 'new' entry already exists, if not, just update this in place
2087 // and return early.
2088 if (BlockAddress *NewBA = getContext().pImpl->BlockAddresses.lookup(NewBB))
2089 return NewBA;
2090
2091 getBasicBlock()->setHasAddressTaken(false);
2092
2093 // erase invalidates iterators/references, hence the duplicate NewBB lookup.
2095 getContext().pImpl->BlockAddresses[NewBB] = this;
2096 Block = NewBB;
2097 getBasicBlock()->setHasAddressTaken(true);
2098
2099 // If we just want to keep the existing value, then return null.
2100 // Callers know that this means we shouldn't delete this value.
2101 return nullptr;
2102}
2103
2104DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
2105 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
2106 if (!Equiv)
2107 Equiv = new DSOLocalEquivalent(GV);
2108
2109 assert(Equiv->getGlobalValue() == GV &&
2110 "DSOLocalFunction does not match the expected global value");
2111 return Equiv;
2112}
2113
2114DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
2115 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
2116 setOperand(0, GV);
2117}
2118
2119/// Remove the constant from the constant table.
2120void DSOLocalEquivalent::destroyConstantImpl() {
2121 const GlobalValue *GV = getGlobalValue();
2122 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
2123}
2124
2125Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
2126 assert(From == getGlobalValue() && "Changing value does not match operand.");
2127 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
2128
2129 // The replacement is with another global value.
2130 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
2131 if (DSOLocalEquivalent *NewEquiv =
2132 getContext().pImpl->DSOLocalEquivalents.lookup(ToObj))
2133 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2134 }
2135
2136 // If the argument is replaced with a null value, just replace this constant
2137 // with a null value.
2139 return To;
2140
2141 // The replacement could be a bitcast or an alias to another function. We can
2142 // replace it with a bitcast to the dso_local_equivalent of that function.
2144 if (DSOLocalEquivalent *NewEquiv =
2145 getContext().pImpl->DSOLocalEquivalents.lookup(Func))
2146 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2147
2148 // erase invalidates iterators/references, hence the duplicate Func lookup.
2151 setOperand(0, Func);
2152
2153 if (Func->getType() != getType()) {
2154 // It is ok to mutate the type here because this constant should always
2155 // reflect the type of the function it's holding.
2156 mutateType(Func->getType());
2157 }
2158 return nullptr;
2159}
2160
2162 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2163 if (!NC)
2164 NC = new NoCFIValue(GV);
2165
2166 assert(NC->getGlobalValue() == GV &&
2167 "NoCFIValue does not match the expected global value");
2168 return NC;
2169}
2170
2171NoCFIValue::NoCFIValue(GlobalValue *GV)
2172 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2173 setOperand(0, GV);
2174}
2175
2176/// Remove the constant from the constant table.
2177void NoCFIValue::destroyConstantImpl() {
2178 const GlobalValue *GV = getGlobalValue();
2179 GV->getContext().pImpl->NoCFIValues.erase(GV);
2180}
2181
2182Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2183 assert(From == getGlobalValue() && "Changing value does not match operand.");
2184
2185 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2186 assert(GV && "Can only replace the operands with a global value");
2187
2188 if (NoCFIValue *NewNC = getContext().pImpl->NoCFIValues.lookup(GV))
2189 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2190
2191 // erase invalidates iterators/references, hence the duplicate GV lookup.
2193 getContext().pImpl->NoCFIValues[GV] = this;
2194 setOperand(0, GV);
2195
2196 if (GV->getType() != getType())
2197 mutateType(GV->getType());
2198
2199 return nullptr;
2200}
2201
2202//---- ConstantPtrAuth::get() implementations.
2203//
2204
2206 ConstantInt *Disc, Constant *AddrDisc,
2207 Constant *DeactivationSymbol) {
2208 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc, DeactivationSymbol};
2209 ConstantPtrAuthKeyType MapKey(ArgVec);
2210 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2211 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2212}
2213
2214ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2215 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator(),
2217}
2218
2219ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2220 ConstantInt *Disc, Constant *AddrDisc,
2221 Constant *DeactivationSymbol)
2222 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2223 assert(Ptr->getType()->isPointerTy());
2224 assert(Key->getBitWidth() == 32);
2225 assert(Disc->getBitWidth() == 64);
2226 assert(AddrDisc->getType()->isPointerTy());
2227 assert(DeactivationSymbol->getType()->isPointerTy());
2228 setOperand(0, Ptr);
2229 setOperand(1, Key);
2230 setOperand(2, Disc);
2231 setOperand(3, AddrDisc);
2232 setOperand(4, DeactivationSymbol);
2233}
2234
2235/// Remove the constant from the constant table.
2236void ConstantPtrAuth::destroyConstantImpl() {
2237 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2238}
2239
2240Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2241 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2242 Constant *To = cast<Constant>(ToV);
2243
2244 SmallVector<Constant *, 4> Values;
2245 Values.reserve(getNumOperands());
2246
2247 unsigned NumUpdated = 0;
2248
2249 Use *OperandList = getOperandList();
2250 unsigned OperandNo = 0;
2251 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2252 Constant *Val = cast<Constant>(O->get());
2253 if (Val == From) {
2254 OperandNo = (O - OperandList);
2255 Val = To;
2256 ++NumUpdated;
2257 }
2258 Values.push_back(Val);
2259 }
2260
2261 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2262 Values, this, From, To, NumUpdated, OperandNo);
2263}
2264
2266 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2267 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2268 return false;
2269
2270 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2271 if (!IntVal)
2272 return false;
2273
2274 return IntVal->getValue() == Value;
2275}
2276
2278 const Value *Discriminator,
2279 const DataLayout &DL) const {
2280 // This function may only be validly called to analyze a ptrauth operation
2281 // with no deactivation symbol, so if we have one it isn't compatible.
2283 return false;
2284
2285 // If the keys are different, there's no chance for this to be compatible.
2286 if (getKey() != Key)
2287 return false;
2288
2289 // We can have 3 kinds of discriminators:
2290 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2291 // - address-only: `i64 0, ptr p` vs. `ptr p`
2292 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2293
2294 // If this constant has a simple discriminator (integer, no address), easy:
2295 // it's compatible iff the provided full discriminator is also a simple
2296 // discriminator, identical to our integer discriminator.
2298 return getDiscriminator() == Discriminator;
2299
2300 // Otherwise, we can isolate address and integer discriminator components.
2301 const Value *AddrDiscriminator = nullptr;
2302
2303 // This constant may or may not have an integer discriminator (instead of 0).
2304 if (!getDiscriminator()->isNullValue()) {
2305 // If it does, there's an implicit blend. We need to have a matching blend
2306 // intrinsic in the provided full discriminator.
2307 if (!match(Discriminator,
2309 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2310 return false;
2311 } else {
2312 // Otherwise, interpret the provided full discriminator as address-only.
2313 AddrDiscriminator = Discriminator;
2314 }
2315
2316 // Either way, we can now focus on comparing the address discriminators.
2317
2318 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2319 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2320 AddrDiscriminator = Cast->getPointerOperand();
2321
2322 // Beyond that, we're only interested in compatible pointers.
2323 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2324 return false;
2325
2326 // These are often the same constant GEP, making them trivially equivalent.
2327 if (getAddrDiscriminator() == AddrDiscriminator)
2328 return true;
2329
2330 // Finally, they may be equivalent base+offset expressions.
2331 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2333 DL, Off1, /*AllowNonInbounds=*/true);
2334
2335 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2336 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2337 DL, Off2, /*AllowNonInbounds=*/true);
2338
2339 return Base1 == Base2 && Off1 == Off2;
2340}
2341
2342//---- ConstantExpr::get() implementations.
2343//
2344
2345/// This is a utility function to handle folding of casts and lookup of the
2346/// cast in the ExprConstants map. It is used by the various get* methods below.
2348 bool OnlyIfReduced = false) {
2349 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2350 // Fold a few common cases
2351 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2352 return FC;
2353
2354 if (OnlyIfReduced)
2355 return nullptr;
2356
2357 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2358
2359 // Look up the constant in the table first to ensure uniqueness.
2361
2362 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2363}
2364
2366 bool OnlyIfReduced) {
2368 assert(Instruction::isCast(opc) && "opcode out of range");
2370 "Cast opcode not supported as constant expression");
2371 assert(C && Ty && "Null arguments to getCast");
2372 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2373
2374 switch (opc) {
2375 default:
2376 llvm_unreachable("Invalid cast opcode");
2377 case Instruction::Trunc:
2378 return getTrunc(C, Ty, OnlyIfReduced);
2379 case Instruction::PtrToAddr:
2380 return getPtrToAddr(C, Ty, OnlyIfReduced);
2381 case Instruction::PtrToInt:
2382 return getPtrToInt(C, Ty, OnlyIfReduced);
2383 case Instruction::IntToPtr:
2384 return getIntToPtr(C, Ty, OnlyIfReduced);
2385 case Instruction::BitCast:
2386 return getBitCast(C, Ty, OnlyIfReduced);
2387 case Instruction::AddrSpaceCast:
2388 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2389 }
2390}
2391
2393 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2394 return getBitCast(C, Ty);
2395 return getTrunc(C, Ty);
2396}
2397
2399 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2400 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2401 "Invalid cast");
2402
2403 if (Ty->isIntOrIntVectorTy())
2404 return getPtrToInt(S, Ty);
2405
2406 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2407 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2408 return getAddrSpaceCast(S, Ty);
2409
2410 return getBitCast(S, Ty);
2411}
2412
2414 Type *Ty) {
2415 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2416 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2417
2418 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2419 return getAddrSpaceCast(S, Ty);
2420
2421 return getBitCast(S, Ty);
2422}
2423
2424Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2425#ifndef NDEBUG
2426 bool fromVec = isa<VectorType>(C->getType());
2427 bool toVec = isa<VectorType>(Ty);
2428#endif
2429 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2430 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2431 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2432 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2433 "SrcTy must be larger than DestTy for Trunc!");
2434
2435 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2436}
2437
2439 bool OnlyIfReduced) {
2440 assert(C->getType()->isPtrOrPtrVectorTy() &&
2441 "PtrToAddr source must be pointer or pointer vector");
2442 assert(DstTy->isIntOrIntVectorTy() &&
2443 "PtrToAddr destination must be integer or integer vector");
2444 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2445 if (isa<VectorType>(C->getType()))
2446 assert(cast<VectorType>(C->getType())->getElementCount() ==
2447 cast<VectorType>(DstTy)->getElementCount() &&
2448 "Invalid cast between a different number of vector elements");
2449 return getFoldedCast(Instruction::PtrToAddr, C, DstTy, OnlyIfReduced);
2450}
2451
2453 bool OnlyIfReduced) {
2454 assert(C->getType()->isPtrOrPtrVectorTy() &&
2455 "PtrToInt source must be pointer or pointer vector");
2456 assert(DstTy->isIntOrIntVectorTy() &&
2457 "PtrToInt destination must be integer or integer vector");
2458 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2459 if (isa<VectorType>(C->getType()))
2460 assert(cast<VectorType>(C->getType())->getElementCount() ==
2461 cast<VectorType>(DstTy)->getElementCount() &&
2462 "Invalid cast between a different number of vector elements");
2463 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2464}
2465
2467 bool OnlyIfReduced) {
2468 assert(C->getType()->isIntOrIntVectorTy() &&
2469 "IntToPtr source must be integer or integer vector");
2470 assert(DstTy->isPtrOrPtrVectorTy() &&
2471 "IntToPtr destination must be a pointer or pointer vector");
2472 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2473 if (isa<VectorType>(C->getType()))
2474 assert(cast<VectorType>(C->getType())->getElementCount() ==
2475 cast<VectorType>(DstTy)->getElementCount() &&
2476 "Invalid cast between a different number of vector elements");
2477 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2478}
2479
2481 bool OnlyIfReduced) {
2482 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2483 "Invalid constantexpr bitcast!");
2484
2485 // It is common to ask for a bitcast of a value to its own type, handle this
2486 // speedily.
2487 if (C->getType() == DstTy) return C;
2488
2489 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2490}
2491
2493 bool OnlyIfReduced) {
2494 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2495 "Invalid constantexpr addrspacecast!");
2496 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2497}
2498
2499Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2500 unsigned Flags, Type *OnlyIfReducedTy) {
2501 // Check the operands for consistency first.
2503 "Invalid opcode in binary constant expression");
2504 assert(isSupportedBinOp(Opcode) &&
2505 "Binop not supported as constant expression");
2506 assert(C1->getType() == C2->getType() &&
2507 "Operand types in binary constant expression should match");
2508
2509#ifndef NDEBUG
2510 switch (Opcode) {
2511 case Instruction::Add:
2512 case Instruction::Sub:
2513 case Instruction::Mul:
2515 "Tried to create an integer operation on a non-integer type!");
2516 break;
2517 case Instruction::And:
2518 case Instruction::Or:
2519 case Instruction::Xor:
2521 "Tried to create a logical operation on a non-integral type!");
2522 break;
2523 default:
2524 break;
2525 }
2526#endif
2527
2528 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2529 return FC;
2530
2531 if (OnlyIfReducedTy == C1->getType())
2532 return nullptr;
2533
2534 Constant *ArgVec[] = {C1, C2};
2535 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2536
2537 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2538 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2539}
2540
2541bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2542 switch (Opcode) {
2543 case Instruction::UDiv:
2544 case Instruction::SDiv:
2545 case Instruction::URem:
2546 case Instruction::SRem:
2547 case Instruction::FAdd:
2548 case Instruction::FSub:
2549 case Instruction::FMul:
2550 case Instruction::FDiv:
2551 case Instruction::FRem:
2552 case Instruction::And:
2553 case Instruction::Or:
2554 case Instruction::LShr:
2555 case Instruction::AShr:
2556 case Instruction::Shl:
2557 case Instruction::Mul:
2558 return false;
2559 case Instruction::Add:
2560 case Instruction::Sub:
2561 case Instruction::Xor:
2562 return true;
2563 default:
2564 llvm_unreachable("Argument must be binop opcode");
2565 }
2566}
2567
2568bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2569 switch (Opcode) {
2570 case Instruction::UDiv:
2571 case Instruction::SDiv:
2572 case Instruction::URem:
2573 case Instruction::SRem:
2574 case Instruction::FAdd:
2575 case Instruction::FSub:
2576 case Instruction::FMul:
2577 case Instruction::FDiv:
2578 case Instruction::FRem:
2579 case Instruction::And:
2580 case Instruction::Or:
2581 case Instruction::LShr:
2582 case Instruction::AShr:
2583 case Instruction::Shl:
2584 case Instruction::Mul:
2585 return false;
2586 case Instruction::Add:
2587 case Instruction::Sub:
2588 case Instruction::Xor:
2589 return true;
2590 default:
2591 llvm_unreachable("Argument must be binop opcode");
2592 }
2593}
2594
2595bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2596 switch (Opcode) {
2597 case Instruction::ZExt:
2598 case Instruction::SExt:
2599 case Instruction::FPTrunc:
2600 case Instruction::FPExt:
2601 case Instruction::UIToFP:
2602 case Instruction::SIToFP:
2603 case Instruction::FPToUI:
2604 case Instruction::FPToSI:
2605 return false;
2606 case Instruction::Trunc:
2607 case Instruction::PtrToAddr:
2608 case Instruction::PtrToInt:
2609 case Instruction::IntToPtr:
2610 case Instruction::BitCast:
2611 case Instruction::AddrSpaceCast:
2612 return true;
2613 default:
2614 llvm_unreachable("Argument must be cast opcode");
2615 }
2616}
2617
2618bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2619 switch (Opcode) {
2620 case Instruction::ZExt:
2621 case Instruction::SExt:
2622 case Instruction::FPTrunc:
2623 case Instruction::FPExt:
2624 case Instruction::UIToFP:
2625 case Instruction::SIToFP:
2626 case Instruction::FPToUI:
2627 case Instruction::FPToSI:
2628 return false;
2629 case Instruction::Trunc:
2630 case Instruction::PtrToAddr:
2631 case Instruction::PtrToInt:
2632 case Instruction::IntToPtr:
2633 case Instruction::BitCast:
2634 case Instruction::AddrSpaceCast:
2635 return true;
2636 default:
2637 llvm_unreachable("Argument must be cast opcode");
2638 }
2639}
2640
2642 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2643 // Note that a non-inbounds gep is used, as null isn't within any object.
2644 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2646 Ty, Constant::getNullValue(PointerType::getUnqual(Ty->getContext())),
2647 GEPIdx);
2648 return getPtrToInt(GEP,
2649 Type::getInt64Ty(Ty->getContext()));
2650}
2651
2653 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2654 // Note that a non-inbounds gep is used, as null isn't within any object.
2655 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2656 Constant *NullPtr =
2658 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2659 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2660 Constant *Indices[2] = {Zero, One};
2661 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2662 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2663}
2664
2666 ArrayRef<Value *> Idxs,
2667 GEPNoWrapFlags NW,
2668 std::optional<ConstantRange> InRange,
2669 Type *OnlyIfReducedTy) {
2670 assert(Ty && "Must specify element type");
2671 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2672
2673 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2674 return FC; // Fold a few common cases.
2675
2676 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2677 ;
2678
2679 // Get the result type of the getelementptr!
2681 if (OnlyIfReducedTy == ReqTy)
2682 return nullptr;
2683
2684 auto EltCount = ElementCount::getFixed(0);
2685 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2686 EltCount = VecTy->getElementCount();
2687
2688 // Look up the constant in the table first to ensure uniqueness
2689 std::vector<Constant*> ArgVec;
2690 ArgVec.reserve(1 + Idxs.size());
2691 ArgVec.push_back(C);
2692 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2693 for (; GTI != GTE; ++GTI) {
2694 auto *Idx = cast<Constant>(GTI.getOperand());
2695 assert(
2696 (!isa<VectorType>(Idx->getType()) ||
2697 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2698 "getelementptr index type missmatch");
2699
2700 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2701 Idx = Idx->getSplatValue();
2702 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2703 !Idx->getType()->isVectorTy()) {
2704 Idx = ConstantVector::getSplat(EltCount, Idx);
2705 }
2706 ArgVec.push_back(Idx);
2707 }
2708
2709 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2710 {}, Ty, InRange);
2711
2712 LLVMContextImpl *pImpl = C->getContext().pImpl;
2713 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2714}
2715
2717 Type *OnlyIfReducedTy) {
2718 assert(Val->getType()->isVectorTy() &&
2719 "Tried to create extractelement operation on non-vector type!");
2720 assert(Idx->getType()->isIntegerTy() &&
2721 "Extractelement index must be an integer type!");
2722
2724 return FC; // Fold a few common cases.
2725
2726 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2727 if (OnlyIfReducedTy == ReqTy)
2728 return nullptr;
2729
2730 // Look up the constant in the table first to ensure uniqueness
2731 Constant *ArgVec[] = { Val, Idx };
2732 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2733
2734 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2735 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2736}
2737
2739 Constant *Idx, Type *OnlyIfReducedTy) {
2740 assert(Val->getType()->isVectorTy() &&
2741 "Tried to create insertelement operation on non-vector type!");
2742 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2743 "Insertelement types must match!");
2744 assert(Idx->getType()->isIntegerTy() &&
2745 "Insertelement index must be i32 type!");
2746
2747 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2748 return FC; // Fold a few common cases.
2749
2750 if (OnlyIfReducedTy == Val->getType())
2751 return nullptr;
2752
2753 // Look up the constant in the table first to ensure uniqueness
2754 Constant *ArgVec[] = { Val, Elt, Idx };
2755 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2756
2757 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2758 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2759}
2760
2762 ArrayRef<int> Mask,
2763 Type *OnlyIfReducedTy) {
2765 "Invalid shuffle vector constant expr operands!");
2766
2768 return FC; // Fold a few common cases.
2769
2770 unsigned NElts = Mask.size();
2771 auto V1VTy = cast<VectorType>(V1->getType());
2772 Type *EltTy = V1VTy->getElementType();
2773 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2774 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2775
2776 if (OnlyIfReducedTy == ShufTy)
2777 return nullptr;
2778
2779 // Look up the constant in the table first to ensure uniqueness
2780 Constant *ArgVec[] = {V1, V2};
2781 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2782
2783 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2784 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2785}
2786
2788 assert(C->getType()->isIntOrIntVectorTy() &&
2789 "Cannot NEG a nonintegral value!");
2790 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2791}
2792
2794 assert(C->getType()->isIntOrIntVectorTy() &&
2795 "Cannot NOT a nonintegral value!");
2796 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2797}
2798
2800 bool HasNUW, bool HasNSW) {
2801 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2803 return get(Instruction::Add, C1, C2, Flags);
2804}
2805
2807 bool HasNUW, bool HasNSW) {
2808 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2810 return get(Instruction::Sub, C1, C2, Flags);
2811}
2812
2814 return get(Instruction::Xor, C1, C2);
2815}
2816
2818 Type *Ty = C->getType();
2819 const APInt *IVal;
2820 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2821 return ConstantInt::get(Ty, IVal->logBase2());
2822
2823 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2824 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2825 if (!VecTy)
2826 return nullptr;
2827
2829 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2830 Constant *Elt = C->getAggregateElement(I);
2831 if (!Elt)
2832 return nullptr;
2833 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2834 if (isa<UndefValue>(Elt)) {
2835 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2836 continue;
2837 }
2838 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2839 return nullptr;
2840 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2841 }
2842
2843 return ConstantVector::get(Elts);
2844}
2845
2847 bool AllowRHSConstant, bool NSZ) {
2848 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2849
2850 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2851 if (Instruction::isCommutative(Opcode)) {
2852 switch (Opcode) {
2853 case Instruction::Add: // X + 0 = X
2854 case Instruction::Or: // X | 0 = X
2855 case Instruction::Xor: // X ^ 0 = X
2856 return Constant::getNullValue(Ty);
2857 case Instruction::Mul: // X * 1 = X
2858 return ConstantInt::get(Ty, 1);
2859 case Instruction::And: // X & -1 = X
2860 return Constant::getAllOnesValue(Ty);
2861 case Instruction::FAdd: // X + -0.0 = X
2862 return ConstantFP::getZero(Ty, !NSZ);
2863 case Instruction::FMul: // X * 1.0 = X
2864 return ConstantFP::get(Ty, 1.0);
2865 default:
2866 llvm_unreachable("Every commutative binop has an identity constant");
2867 }
2868 }
2869
2870 // Non-commutative opcodes: AllowRHSConstant must be set.
2871 if (!AllowRHSConstant)
2872 return nullptr;
2873
2874 switch (Opcode) {
2875 case Instruction::Sub: // X - 0 = X
2876 case Instruction::Shl: // X << 0 = X
2877 case Instruction::LShr: // X >>u 0 = X
2878 case Instruction::AShr: // X >> 0 = X
2879 case Instruction::FSub: // X - 0.0 = X
2880 return Constant::getNullValue(Ty);
2881 case Instruction::SDiv: // X / 1 = X
2882 case Instruction::UDiv: // X /u 1 = X
2883 return ConstantInt::get(Ty, 1);
2884 case Instruction::FDiv: // X / 1.0 = X
2885 return ConstantFP::get(Ty, 1.0);
2886 default:
2887 return nullptr;
2888 }
2889}
2890
2892 switch (ID) {
2893 case Intrinsic::umax:
2894 return Constant::getNullValue(Ty);
2895 case Intrinsic::umin:
2896 return Constant::getAllOnesValue(Ty);
2897 case Intrinsic::smax:
2899 Ty, APInt::getSignedMinValue(Ty->getIntegerBitWidth()));
2900 case Intrinsic::smin:
2902 Ty, APInt::getSignedMaxValue(Ty->getIntegerBitWidth()));
2903 default:
2904 return nullptr;
2905 }
2906}
2907
2909 bool AllowRHSConstant, bool NSZ) {
2910 if (I->isBinaryOp())
2911 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2913 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2914 return nullptr;
2915}
2916
2918 bool AllowLHSConstant) {
2919 switch (Opcode) {
2920 default:
2921 break;
2922
2923 case Instruction::Or: // -1 | X = -1
2924 return Constant::getAllOnesValue(Ty);
2925
2926 case Instruction::And: // 0 & X = 0
2927 case Instruction::Mul: // 0 * X = 0
2928 return Constant::getNullValue(Ty);
2929 }
2930
2931 // AllowLHSConstant must be set.
2932 if (!AllowLHSConstant)
2933 return nullptr;
2934
2935 switch (Opcode) {
2936 default:
2937 return nullptr;
2938 case Instruction::Shl: // 0 << X = 0
2939 case Instruction::LShr: // 0 >>l X = 0
2940 case Instruction::AShr: // 0 >>a X = 0
2941 case Instruction::SDiv: // 0 /s X = 0
2942 case Instruction::UDiv: // 0 /u X = 0
2943 case Instruction::URem: // 0 %u X = 0
2944 case Instruction::SRem: // 0 %s X = 0
2945 return Constant::getNullValue(Ty);
2946 }
2947}
2948
2949/// Remove the constant from the constant table.
2950void ConstantExpr::destroyConstantImpl() {
2951 getType()->getContext().pImpl->ExprConstants.remove(this);
2952}
2953
2954const char *ConstantExpr::getOpcodeName() const {
2956}
2957
2958GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2959 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
2960 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
2961 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
2962 SrcElementTy(SrcElementTy),
2963 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
2964 InRange(std::move(InRange)) {
2965 Op<0>() = C;
2966 Use *OperandList = getOperandList();
2967 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2968 OperandList[i+1] = IdxList[i];
2969}
2970
2972 return SrcElementTy;
2973}
2974
2976 return ResElementTy;
2977}
2978
2979std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
2980 return InRange;
2981}
2982
2983//===----------------------------------------------------------------------===//
2984// ConstantData* implementations
2985
2988 return ATy->getElementType();
2989 return cast<VectorType>(getType())->getElementType();
2990}
2991
2995
2997 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2998 return true;
2999 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
3000 switch (IT->getBitWidth()) {
3001 case 8:
3002 case 16:
3003 case 32:
3004 case 64:
3005 return true;
3006 default: break;
3007 }
3008 }
3009 if (auto *IT = dyn_cast<ByteType>(Ty)) {
3010 switch (IT->getBitWidth()) {
3011 case 8:
3012 case 16:
3013 case 32:
3014 case 64:
3015 return true;
3016 default:
3017 break;
3018 }
3019 }
3020 return false;
3021}
3022
3025 return AT->getNumElements();
3026 return cast<FixedVectorType>(getType())->getNumElements();
3027}
3028
3032
3033/// Return the start of the specified element.
3034const char *ConstantDataSequential::getElementPointer(uint64_t Elt) const {
3035 assert(Elt < getNumElements() && "Invalid Elt");
3036 return DataElements + Elt * getElementByteSize();
3037}
3038
3039/// Return true if the array is empty or all zeros.
3040static bool isAllZeros(StringRef Arr) {
3041 for (char I : Arr)
3042 if (I != 0)
3043 return false;
3044 return true;
3045}
3046
3047/// This is the underlying implementation of all of the
3048/// ConstantDataSequential::get methods. They all thunk down to here, providing
3049/// the correct element type. We take the bytes in as a StringRef because
3050/// we *want* an underlying "char*" to avoid TBAA type punning violations.
3052#ifndef NDEBUG
3053 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
3054 assert(isElementTypeCompatible(ATy->getElementType()));
3055 else
3057#endif
3058 // If the elements are all zero or there are no elements, return a CAZ, which
3059 // is more dense and canonical.
3060 if (isAllZeros(Elements))
3061 return ConstantAggregateZero::get(Ty);
3062
3063 // Do a lookup to see if we have already formed one of these.
3064 auto &Slot =
3065 *Ty->getContext().pImpl->CDSConstants.try_emplace(Elements).first;
3066
3067 // The bucket can point to a linked list of different CDS's that have the same
3068 // body but different types. For example, 0,0,0,1 could be a 4 element array
3069 // of i8, or a 1-element array of i32. They'll both end up in the same
3070 /// StringMap bucket, linked up by their Next pointers. Walk the list.
3071 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
3072 for (; *Entry; Entry = &(*Entry)->Next)
3073 if ((*Entry)->getType() == Ty)
3074 return Entry->get();
3075
3076 // Okay, we didn't get a hit. Create a node of the right class, link it in,
3077 // and return it.
3078 if (isa<ArrayType>(Ty)) {
3079 // Use reset because std::make_unique can't access the constructor.
3080 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
3081 return Entry->get();
3082 }
3083
3085 // Use reset because std::make_unique can't access the constructor.
3086 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
3087 return Entry->get();
3088}
3089
3090void ConstantDataSequential::destroyConstantImpl() {
3091 // Remove the constant from the StringMap.
3094
3095 auto Slot = CDSConstants.find(getRawDataValues());
3096
3097 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
3098
3099 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
3100
3101 // Remove the entry from the hash table.
3102 if (!(*Entry)->Next) {
3103 // If there is only one value in the bucket (common case) it must be this
3104 // entry, and removing the entry should remove the bucket completely.
3105 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
3106 getContext().pImpl->CDSConstants.erase(Slot);
3107 return;
3108 }
3109
3110 // Otherwise, there are multiple entries linked off the bucket, unlink the
3111 // node we care about but keep the bucket around.
3112 while (true) {
3113 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
3114 assert(Node && "Didn't find entry in its uniquing hash table!");
3115 // If we found our entry, unlink it from the list and we're done.
3116 if (Node.get() == this) {
3117 Node = std::move(Node->Next);
3118 return;
3119 }
3120
3121 Entry = &Node->Next;
3122 }
3123}
3124
3125/// getFP() constructors - Return a constant of array type with a float
3126/// element type taken from argument `ElementType', and count taken from
3127/// argument `Elts'. The amount of bits of the contained type must match the
3128/// number of bits of the type contained in the passed in ArrayRef.
3129/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3130/// that this can return a ConstantAggregateZero object.
3132 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3133 "Element type is not a 16-bit float type");
3134 Type *Ty = ArrayType::get(ElementType, Elts.size());
3135 const char *Data = reinterpret_cast<const char *>(Elts.data());
3136 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3137}
3139 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3140 Type *Ty = ArrayType::get(ElementType, Elts.size());
3141 const char *Data = reinterpret_cast<const char *>(Elts.data());
3142 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3143}
3145 assert(ElementType->isDoubleTy() &&
3146 "Element type is not a 64-bit float type");
3147 Type *Ty = ArrayType::get(ElementType, Elts.size());
3148 const char *Data = reinterpret_cast<const char *>(Elts.data());
3149 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3150}
3151
3152/// getByte() constructors - Return a constant of array type with a byte
3153/// element type taken from argument `ElementType', and count taken from
3154/// argument `Elts'. The amount of bits of the contained type must match the
3155/// number of bits of the type contained in the passed in ArrayRef.
3156/// Note that this can return a ConstantAggregateZero object.
3158 ArrayRef<uint8_t> Elts) {
3159 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte type");
3160 Type *Ty = ArrayType::get(ElementType, Elts.size());
3161 const char *Data = reinterpret_cast<const char *>(Elts.data());
3162 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3163}
3165 ArrayRef<uint16_t> Elts) {
3166 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte type");
3167 Type *Ty = ArrayType::get(ElementType, Elts.size());
3168 const char *Data = reinterpret_cast<const char *>(Elts.data());
3169 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3170}
3172 ArrayRef<uint32_t> Elts) {
3173 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte type");
3174 Type *Ty = ArrayType::get(ElementType, Elts.size());
3175 const char *Data = reinterpret_cast<const char *>(Elts.data());
3176 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3177}
3179 ArrayRef<uint64_t> Elts) {
3180 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte type");
3181 Type *Ty = ArrayType::get(ElementType, Elts.size());
3182 const char *Data = reinterpret_cast<const char *>(Elts.data());
3183 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3184}
3185
3187 bool AddNull, bool ByteString) {
3188 if (!AddNull) {
3189 const uint8_t *Data = Str.bytes_begin();
3190 return ByteString
3191 ? getByte(Type::getByte8Ty(Context), ArrayRef(Data, Str.size()))
3192 : get(Context, ArrayRef(Data, Str.size()));
3193 }
3194
3195 SmallVector<uint8_t, 64> ElementVals;
3196 ElementVals.append(Str.begin(), Str.end());
3197 ElementVals.push_back(0);
3198 return ByteString ? getByte(Type::getByte8Ty(Context), ElementVals)
3199 : get(Context, ElementVals);
3200}
3201
3202/// get() constructors - Return a constant with vector type with an element
3203/// count and element type matching the ArrayRef passed in. Note that this
3204/// can return a ConstantAggregateZero object.
3206 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3207 const char *Data = reinterpret_cast<const char *>(Elts.data());
3208 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3209}
3211 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3212 const char *Data = reinterpret_cast<const char *>(Elts.data());
3213 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3214}
3216 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3217 const char *Data = reinterpret_cast<const char *>(Elts.data());
3218 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3219}
3221 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3222 const char *Data = reinterpret_cast<const char *>(Elts.data());
3223 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3224}
3226 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3227 const char *Data = reinterpret_cast<const char *>(Elts.data());
3228 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3229}
3231 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3232 const char *Data = reinterpret_cast<const char *>(Elts.data());
3233 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3234}
3235
3236/// getByte() constructors - Return a constant of vector type with a byte
3237/// element type taken from argument `ElementType', and count taken from
3238/// argument `Elts'. The amount of bits of the contained type must match the
3239/// number of bits of the type contained in the passed in ArrayRef.
3240/// Note that this can return a ConstantAggregateZero object.
3242 ArrayRef<uint8_t> Elts) {
3243 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte");
3244 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3245 const char *Data = reinterpret_cast<const char *>(Elts.data());
3246 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3247}
3249 ArrayRef<uint16_t> Elts) {
3250 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte");
3251 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3252 const char *Data = reinterpret_cast<const char *>(Elts.data());
3253 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3254}
3256 ArrayRef<uint32_t> Elts) {
3257 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte");
3258 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3259 const char *Data = reinterpret_cast<const char *>(Elts.data());
3260 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3261}
3263 ArrayRef<uint64_t> Elts) {
3264 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte");
3265 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3266 const char *Data = reinterpret_cast<const char *>(Elts.data());
3267 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3268}
3269
3270/// getFP() constructors - Return a constant of vector type with a float
3271/// element type taken from argument `ElementType', and count taken from
3272/// argument `Elts'. The amount of bits of the contained type must match the
3273/// number of bits of the type contained in the passed in ArrayRef.
3274/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3275/// that this can return a ConstantAggregateZero object.
3277 ArrayRef<uint16_t> Elts) {
3278 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3279 "Element type is not a 16-bit float type");
3280 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3281 const char *Data = reinterpret_cast<const char *>(Elts.data());
3282 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3283}
3285 ArrayRef<uint32_t> Elts) {
3286 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3287 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3288 const char *Data = reinterpret_cast<const char *>(Elts.data());
3289 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3290}
3292 ArrayRef<uint64_t> Elts) {
3293 assert(ElementType->isDoubleTy() &&
3294 "Element type is not a 64-bit float type");
3295 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3296 const char *Data = reinterpret_cast<const char *>(Elts.data());
3297 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3298}
3299
3301 assert(isElementTypeCompatible(V->getType()) &&
3302 "Element type not compatible with ConstantData");
3303 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3304 if (CI->getType()->isIntegerTy(8)) {
3305 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3306 return get(V->getContext(), Elts);
3307 }
3308 if (CI->getType()->isIntegerTy(16)) {
3309 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3310 return get(V->getContext(), Elts);
3311 }
3312 if (CI->getType()->isIntegerTy(32)) {
3313 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3314 return get(V->getContext(), Elts);
3315 }
3316 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3317 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3318 return get(V->getContext(), Elts);
3319 }
3320
3321 if (ConstantByte *CB = dyn_cast<ConstantByte>(V)) {
3322 if (CB->getType()->isByteTy(8)) {
3323 SmallVector<uint8_t, 16> Elts(NumElts, CB->getZExtValue());
3324 return getByte(V->getType(), Elts);
3325 }
3326 if (CB->getType()->isByteTy(16)) {
3327 SmallVector<uint16_t, 16> Elts(NumElts, CB->getZExtValue());
3328 return getByte(V->getType(), Elts);
3329 }
3330 if (CB->getType()->isByteTy(32)) {
3331 SmallVector<uint32_t, 16> Elts(NumElts, CB->getZExtValue());
3332 return getByte(V->getType(), Elts);
3333 }
3334 assert(CB->getType()->isByteTy(64) && "Unsupported ConstantData type");
3335 SmallVector<uint64_t, 16> Elts(NumElts, CB->getZExtValue());
3336 return getByte(V->getType(), Elts);
3337 }
3338
3339 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3340 if (CFP->getType()->isHalfTy()) {
3342 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3343 return getFP(V->getType(), Elts);
3344 }
3345 if (CFP->getType()->isBFloatTy()) {
3347 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3348 return getFP(V->getType(), Elts);
3349 }
3350 if (CFP->getType()->isFloatTy()) {
3352 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3353 return getFP(V->getType(), Elts);
3354 }
3355 if (CFP->getType()->isDoubleTy()) {
3357 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3358 return getFP(V->getType(), Elts);
3359 }
3360 }
3362}
3363
3365 assert(
3367 "Accessor can only be used when element is an integer or byte");
3368 const char *EltPtr = getElementPointer(Elt);
3369
3370 // The data is stored in host byte order, make sure to cast back to the right
3371 // type to load with the right endianness.
3372 switch (getElementType()->getScalarSizeInBits()) {
3373 default: llvm_unreachable("Invalid bitwidth for CDS");
3374 case 8:
3375 return *reinterpret_cast<const uint8_t *>(EltPtr);
3376 case 16:
3377 return *reinterpret_cast<const uint16_t *>(EltPtr);
3378 case 32:
3379 return *reinterpret_cast<const uint32_t *>(EltPtr);
3380 case 64:
3381 return *reinterpret_cast<const uint64_t *>(EltPtr);
3382 }
3383}
3384
3386 assert(
3388 "Accessor can only be used when element is an integer or byte");
3389 const char *EltPtr = getElementPointer(Elt);
3390
3391 // The data is stored in host byte order, make sure to cast back to the right
3392 // type to load with the right endianness.
3393 switch (getElementType()->getScalarSizeInBits()) {
3394 default: llvm_unreachable("Invalid bitwidth for CDS");
3395 case 8: {
3396 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3397 return APInt(8, EltVal);
3398 }
3399 case 16: {
3400 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3401 return APInt(16, EltVal);
3402 }
3403 case 32: {
3404 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3405 return APInt(32, EltVal);
3406 }
3407 case 64: {
3408 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3409 return APInt(64, EltVal);
3410 }
3411 }
3412}
3413
3415 const char *EltPtr = getElementPointer(Elt);
3416
3417 switch (getElementType()->getTypeID()) {
3418 default:
3419 llvm_unreachable("Accessor can only be used when element is float/double!");
3420 case Type::HalfTyID: {
3421 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3422 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3423 }
3424 case Type::BFloatTyID: {
3425 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3426 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3427 }
3428 case Type::FloatTyID: {
3429 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3430 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3431 }
3432 case Type::DoubleTyID: {
3433 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3434 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3435 }
3436 }
3437}
3438
3440 assert(getElementType()->isFloatTy() &&
3441 "Accessor can only be used when element is a 'float'");
3442 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3443}
3444
3446 assert(getElementType()->isDoubleTy() &&
3447 "Accessor can only be used when element is a 'float'");
3448 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3449}
3450
3452 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3453 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3454 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3455
3456 if (getElementType()->isByteTy())
3457 return ConstantByte::get(getElementType(), getElementAsInteger(Elt));
3458
3459 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3460}
3461
3462bool ConstantDataSequential::isString(unsigned CharSize) const {
3463 return isa<ArrayType>(getType()) &&
3464 (getElementType()->isIntegerTy(CharSize) ||
3465 getElementType()->isByteTy(CharSize));
3466}
3467
3469 if (!isString())
3470 return false;
3471
3472 StringRef Str = getAsString();
3473
3474 // The last value must be nul.
3475 if (Str.back() != 0) return false;
3476
3477 // Other elements must be non-nul.
3478 return !Str.drop_back().contains(0);
3479}
3480
3481bool ConstantDataVector::isSplatData() const {
3482 const char *Base = getRawDataValues().data();
3483
3484 // Compare elements 1+ to the 0'th element.
3485 unsigned EltSize = getElementByteSize();
3486 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3487 if (memcmp(Base, Base+i*EltSize, EltSize))
3488 return false;
3489
3490 return true;
3491}
3492
3494 if (!IsSplatSet) {
3495 IsSplatSet = true;
3496 IsSplat = isSplatData();
3497 }
3498 return IsSplat;
3499}
3500
3502 // If they're all the same, return the 0th one as a representative.
3503 return isSplat() ? getElementAsConstant(0) : nullptr;
3504}
3505
3506//===----------------------------------------------------------------------===//
3507// handleOperandChange implementations
3508
3509/// Update this constant array to change uses of
3510/// 'From' to be uses of 'To'. This must update the uniquing data structures
3511/// etc.
3512///
3513/// Note that we intentionally replace all uses of From with To here. Consider
3514/// a large array that uses 'From' 1000 times. By handling this case all here,
3515/// ConstantArray::handleOperandChange is only invoked once, and that
3516/// single invocation handles all 1000 uses. Handling them one at a time would
3517/// work, but would be really slow because it would have to unique each updated
3518/// array instance.
3519///
3521 Value *Replacement = nullptr;
3522 switch (getValueID()) {
3523 default:
3524 llvm_unreachable("Not a constant!");
3525#define HANDLE_CONSTANT(Name) \
3526 case Value::Name##Val: \
3527 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3528 break;
3529#include "llvm/IR/Value.def"
3530 }
3531
3532 // If handleOperandChangeImpl returned nullptr, then it handled
3533 // replacing itself and we don't want to delete or replace anything else here.
3534 if (!Replacement)
3535 return;
3536
3537 // I do need to replace this with an existing value.
3538 assert(Replacement != this && "I didn't contain From!");
3539
3540 // Everyone using this now uses the replacement.
3541 replaceAllUsesWith(Replacement);
3542
3543 // Delete the old constant!
3545}
3546
3547Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3548 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3549 Constant *ToC = cast<Constant>(To);
3550
3552 Values.reserve(getNumOperands()); // Build replacement array.
3553
3554 // Fill values with the modified operands of the constant array. Also,
3555 // compute whether this turns into an all-zeros array.
3556 unsigned NumUpdated = 0;
3557
3558 // Keep track of whether all the values in the array are "ToC".
3559 bool AllSame = true;
3560 Use *OperandList = getOperandList();
3561 unsigned OperandNo = 0;
3562 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3563 Constant *Val = cast<Constant>(O->get());
3564 if (Val == From) {
3565 OperandNo = (O - OperandList);
3566 Val = ToC;
3567 ++NumUpdated;
3568 }
3569 Values.push_back(Val);
3570 AllSame &= Val == ToC;
3571 }
3572
3573 if (AllSame && ToC->isNullValue())
3575
3576 if (AllSame && isa<UndefValue>(ToC))
3577 return UndefValue::get(getType());
3578
3579 // Check for any other type of constant-folding.
3580 if (Constant *C = getImpl(getType(), Values))
3581 return C;
3582
3583 // Update to the new value.
3585 Values, this, From, ToC, NumUpdated, OperandNo);
3586}
3587
3588Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3589 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3590 Constant *ToC = cast<Constant>(To);
3591
3592 Use *OperandList = getOperandList();
3593
3595 Values.reserve(getNumOperands()); // Build replacement struct.
3596
3597 // Fill values with the modified operands of the constant struct. Also,
3598 // compute whether this turns into an all-zeros struct.
3599 unsigned NumUpdated = 0;
3600 bool AllSame = true;
3601 unsigned OperandNo = 0;
3602 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3603 Constant *Val = cast<Constant>(O->get());
3604 if (Val == From) {
3605 OperandNo = (O - OperandList);
3606 Val = ToC;
3607 ++NumUpdated;
3608 }
3609 Values.push_back(Val);
3610 AllSame &= Val == ToC;
3611 }
3612
3613 if (AllSame && ToC->isNullValue())
3615
3616 if (AllSame && isa<UndefValue>(ToC))
3617 return UndefValue::get(getType());
3618
3619 // Update to the new value.
3621 Values, this, From, ToC, NumUpdated, OperandNo);
3622}
3623
3624Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3625 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3626 Constant *ToC = cast<Constant>(To);
3627
3629 Values.reserve(getNumOperands()); // Build replacement array...
3630 unsigned NumUpdated = 0;
3631 unsigned OperandNo = 0;
3632 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3633 Constant *Val = getOperand(i);
3634 if (Val == From) {
3635 OperandNo = i;
3636 ++NumUpdated;
3637 Val = ToC;
3638 }
3639 Values.push_back(Val);
3640 }
3641
3642 if (Constant *C = getImpl(Values))
3643 return C;
3644
3645 // Update to the new value.
3647 Values, this, From, ToC, NumUpdated, OperandNo);
3648}
3649
3650Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3651 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3652 Constant *To = cast<Constant>(ToV);
3653
3655 unsigned NumUpdated = 0;
3656 unsigned OperandNo = 0;
3657 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3658 Constant *Op = getOperand(i);
3659 if (Op == From) {
3660 OperandNo = i;
3661 ++NumUpdated;
3662 Op = To;
3663 }
3664 NewOps.push_back(Op);
3665 }
3666 assert(NumUpdated && "I didn't contain From!");
3667
3668 if (Constant *C = getWithOperands(NewOps, getType(), true))
3669 return C;
3670
3671 // Update to the new value.
3672 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3673 NewOps, this, From, To, NumUpdated, OperandNo);
3674}
3675
3677 SmallVector<Value *, 4> ValueOperands(operands());
3678 ArrayRef<Value*> Ops(ValueOperands);
3679
3680 switch (getOpcode()) {
3681 case Instruction::Trunc:
3682 case Instruction::PtrToAddr:
3683 case Instruction::PtrToInt:
3684 case Instruction::IntToPtr:
3685 case Instruction::BitCast:
3686 case Instruction::AddrSpaceCast:
3688 getType(), "");
3689 case Instruction::InsertElement:
3690 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3691 case Instruction::ExtractElement:
3692 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3693 case Instruction::ShuffleVector:
3694 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3695
3696 case Instruction::GetElementPtr: {
3697 const auto *GO = cast<GEPOperator>(this);
3698 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3699 Ops.slice(1), GO->getNoWrapFlags(), "");
3700 }
3701 default:
3702 assert(getNumOperands() == 2 && "Must be binary operator?");
3704 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3710 }
3713 return BO;
3714 }
3715}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::values(clEnumValN(DefaultIT, "arm-default-it", "Generate any type of IT block"), clEnumValN(RestrictedIT, "arm-restrict-it", "Disallow complex IT blocks")))
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool isAllZeros(StringRef Arr)
Return true if the array is empty or all zeros.
static cl::opt< bool > UseConstantIntForScalableSplat("use-constant-int-for-scalable-splat", cl::init(false), cl::Hidden, cl::desc("Use ConstantInt's native scalable vector splat support."))
static Constant * getByteSequenceIfElementsMatch(ArrayRef< Constant * > V)
static cl::opt< bool > UseConstantIntForFixedLengthSplat("use-constant-int-for-fixed-length-splat", cl::init(false), cl::Hidden, cl::desc("Use ConstantInt's native fixed-length vector splat support."))
static Constant * getFPSequenceIfElementsMatch(ArrayRef< Constant * > V)
static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt)
static Constant * getIntSequenceIfElementsMatch(ArrayRef< Constant * > V)
static Constant * getSequenceIfElementsMatch(Constant *C, ArrayRef< Constant * > V)
static bool ConstHasGlobalValuePredicate(const Constant *C, bool(*Predicate)(const GlobalValue *))
Check if C contains a GlobalValue for which Predicate is true.
static bool constantIsDead(const Constant *C, bool RemoveDeadUsers)
Return true if the specified constantexpr is dead.
static bool containsUndefinedElement(const Constant *C, function_ref< bool(const Constant *)> HasFn)
static Constant * getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is a utility function to handle folding of casts and lookup of the cast in the ExprConstants map...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isSigned(unsigned Opcode)
static char getTypeID(Type *Ty)
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Hexagon Common GEP
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:539
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static bool isUndef(const MachineInstr &MI)
static bool InRange(int64_t Value, unsigned short Shift, int LBound, int HBound)
#define T
uint64_t IntrinsicInst * II
static unsigned getNumElements(Type *Ty)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static Function * getFunction(FunctionType *Ty, const Twine &Name, Module *M)
Value * LHS
static const fltSemantics & IEEEsingle()
Definition APFloat.h:297
static const fltSemantics & BFloat()
Definition APFloat.h:296
static const fltSemantics & IEEEquad()
Definition APFloat.h:299
static const fltSemantics & IEEEdouble()
Definition APFloat.h:298
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:318
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:345
static const fltSemantics & IEEEhalf()
Definition APFloat.h:295
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:300
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1180
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1188
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5913
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:5939
const fltSemantics & getSemantics() const
Definition APFloat.h:1547
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1158
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1169
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1139
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:210
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:220
unsigned logBase2() const
Definition APInt.h:1784
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
const T * data() const
Definition ArrayRef.h:138
Class to represent array types.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:687
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
BinaryConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to impleme...
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
The address of a basic block.
Definition Constants.h:1082
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
BasicBlock * getBasicBlock() const
Definition Constants.h:1119
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Class to represent byte types.
static LLVM_ABI ByteType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing a ByteType.
Definition Type.cpp:380
CastConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to implement...
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
static LLVM_ABI bool castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy)
This method can be used to determine if a cast from SrcTy to DstTy using Opcode op is valid or not.
All zero aggregate value.
Definition Constants.h:508
LLVM_ABI ElementCount getElementCount() const
Return the number of elements in the array, vector, or struct.
LLVM_ABI Constant * getSequentialElement() const
If this CAZ has array or vector type, return a zero with the right element type.
LLVM_ABI Constant * getElementValue(Constant *C) const
Return a zero of the right value for the specified GEP index if we can, otherwise return null (e....
LLVM_ABI Constant * getStructElement(unsigned Elt) const
If this CAZ has struct type, return a zero with the right element type for the specified element.
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
Base class for aggregate constants (with operands).
Definition Constants.h:559
LLVM_ABI ConstantAggregate(Type *T, ValueTy VT, ArrayRef< Constant * > V, AllocInfo AllocInfo)
ConstantArray - Constant Array Declarations.
Definition Constants.h:584
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
friend class Constant
Definition Constants.h:586
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition Constants.h:603
Class for constant bytes.
Definition Constants.h:281
friend class Constant
Definition Constants.h:282
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:859
static Constant * get(LLVMContext &Context, ArrayRef< ElementTy > Elts)
get() constructor - Return a constant with array type with an element count and element type matching...
Definition Constants.h:872
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of array type with a float element type taken from argument ...
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true, bool ByteString=false)
This method constructs a CDS and initializes it with a text string.
static LLVM_ABI Constant * getByte(Type *ElementType, ArrayRef< uint8_t > Elts)
getByte() constructors - Return a constant of array type with a byte element type taken from argument...
LLVM_ABI APFloat getElementAsAPFloat(uint64_t i) const
If this is a sequential container of floating point type, return the specified element as an APFloat.
LLVM_ABI uint64_t getElementAsInteger(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element in the low ...
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:825
LLVM_ABI Constant * getElementAsConstant(uint64_t i) const
Return a Constant for a specified index's element.
LLVM_ABI uint64_t getElementByteSize() const
Return the size (in bytes) of each element in the array/vector.
LLVM_ABI float getElementAsFloat(uint64_t i) const
If this is an sequential container of floats, return the specified element as a float.
LLVM_ABI bool isString(unsigned CharSize=8) const
This method returns true if this is an array of CharSize integers or bytes.
LLVM_ABI uint64_t getNumElements() const
Return the number of elements in the array or vector.
LLVM_ABI APInt getElementAsAPInt(uint64_t i) const
If this is a sequential container of integers (of any size), return the specified element as an APInt...
static LLVM_ABI Constant * getImpl(StringRef Bytes, Type *Ty)
This is the underlying implementation of all of the ConstantDataSequential::get methods.
LLVM_ABI double getElementAsDouble(uint64_t i) const
If this is an sequential container of doubles, return the specified element as a double.
LLVM_ABI Type * getElementType() const
Return the element type of the array/vector.
LLVM_ABI bool isCString() const
This method returns true if the array "isString", ends with a null byte, and does not contains any ot...
LLVM_ABI StringRef getRawDataValues() const
Return the raw, underlying, bytes of this data.
static LLVM_ABI bool isElementTypeCompatible(Type *Ty)
Return true if a ConstantDataSequential can be formed with a vector or array of the specified element...
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:945
LLVM_ABI Constant * getSplatValue() const
If this is a splat constant, meaning that all of the elements have the same value,...
static LLVM_ABI Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
LLVM_ABI bool isSplat() const
Returns true if this is a splat constant, meaning that all elements have the same value.
static LLVM_ABI Constant * get(LLVMContext &Context, ArrayRef< uint8_t > Elts)
get() constructors - Return a constant with vector type with an element count and element type matchi...
static LLVM_ABI Constant * getFP(Type *ElementType, ArrayRef< uint16_t > Elts)
getFP() constructors - Return a constant of vector type with a float element type taken from argument...
static LLVM_ABI Constant * getByte(Type *ElementType, ArrayRef< uint8_t > Elts)
getByte() constructors - Return a constant of vector type with a byte element type taken from argumen...
Base class for constants with no operands.
Definition Constants.h:56
A constant value that is initialized with an expression using other constant values.
Definition Constants.h:1310
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
ConstantExpr(Type *ty, unsigned Opcode, AllocInfo AllocInfo)
Definition Constants.h:1318
static LLVM_ABI Constant * getAlignOf(Type *Ty)
getAlignOf constant expr - computes the alignment of a type in a target independent way (Note: the re...
friend struct ConstantExprKeyType
Definition Constants.h:1311
static LLVM_ABI Constant * getPointerCast(Constant *C, Type *Ty)
Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant expression.
static LLVM_ABI Constant * getTruncOrBitCast(Constant *C, Type *Ty)
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
LLVM_ABI bool isCast() const
Return true if this is a convert constant expression.
static LLVM_ABI Constant * getIdentity(Instruction *I, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary or intrinsic Instruction.
static LLVM_ABI bool isDesirableCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is desirable.
LLVM_ABI Constant * getShuffleMaskForBitcode() const
Assert that this is a shufflevector and return the mask.
static LLVM_ABI Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty, bool AllowLHSConstant=false)
Return the absorbing element for the given binary operation, i.e.
static LLVM_ABI Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getNot(Constant *C)
friend class Constant
Definition Constants.h:1312
LLVM_ABI const char * getOpcodeName() const
Return a string representation for an opcode.
static LLVM_ABI Constant * getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getPtrToAddr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getSizeOf(Type *Ty)
getSizeOf constant expr - computes the (alloc) size of a type (in address-units, not bits) in a targe...
static bool isSupportedGetElementPtr(const Type *SrcElemTy)
Whether creating a constant expression for this getelementptr type is supported.
Definition Constants.h:1592
static LLVM_ABI Constant * getIntrinsicIdentity(Intrinsic::ID, Type *Ty)
static LLVM_ABI Constant * getXor(Constant *C1, Constant *C2)
static LLVM_ABI Constant * get(unsigned Opcode, Constant *C1, Constant *C2, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a binary or shift operator constant expression, folding if possible.
static LLVM_ABI bool isDesirableBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is desirable.
LLVM_ABI ArrayRef< int > getShuffleMask() const
Assert that this is a shufflevector and return the mask.
static LLVM_ABI bool isSupportedBinOp(unsigned Opcode)
Whether creating a constant expression for this binary operator is supported.
static LLVM_ABI Constant * getAddrSpaceCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
unsigned getOpcode() const
Return the opcode at the root of this constant expression.
Definition Constants.h:1532
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, GEPNoWrapFlags NW=GEPNoWrapFlags::none(), std::optional< ConstantRange > InRange=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition Constants.h:1464
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI bool isSupportedCastOp(unsigned Opcode)
Whether creating a constant expression for this cast is supported.
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getExactLogBase2(Constant *C)
If C is a scalar/fixed width vector of known powers of 2, then this function returns a new scalar/fix...
Constant * getWithOperands(ArrayRef< Constant * > Ops) const
This returns the current constant expression with the operands replaced with the specified values.
Definition Constants.h:1550
LLVM_ABI Instruction * getAsInstruction() const
Returns an Instruction which implements the same operation as this ConstantExpr.
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
static LLVM_ABI ConstantFP * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI ConstantFP * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
static LLVM_ABI ConstantFP * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
LLVM_ABI bool isExactlyValue(const APFloat &V) const
We don't rely on operator== working on double values, as it returns true for things that are clearly ...
static LLVM_ABI bool isValueValidForType(Type *Ty, const APFloat &V)
Return true if Ty is big enough to represent V.
static LLVM_ABI ConstantFP * getSNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
static LLVM_ABI ConstantFP * getInfinity(Type *Ty, bool Negative=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V.
friend class Constant
Definition Constants.h:88
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
static LLVM_ABI ConstantInt * getBool(LLVMContext &Context, bool V)
A constant pointer value that points to null.
Definition Constants.h:710
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
A signed pointer, in the ptrauth sense.
Definition Constants.h:1217
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1258
friend struct ConstantPtrAuthKeyType
Definition Constants.h:1218
LLVM_ABI bool isKnownCompatibleWith(const Value *Key, const Value *Discriminator, const DataLayout &DL) const
Check whether an authentication operation with key Key and (possibly blended) discriminator Discrimin...
LLVM_ABI bool hasSpecialAddressDiscriminator(uint64_t Value) const
Whether the address uses a special address discriminator.
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
friend class Constant
Definition Constants.h:1219
LLVM_ABI ConstantPtrAuth * getWithSameSchema(Constant *Pointer) const
Produce a new ptrauth expression signing the given value using the same schema as is stored in one.
ConstantInt * getKey() const
The Key ID, an i32 constant.
Definition Constants.h:1248
Constant * getDeactivationSymbol() const
Definition Constants.h:1267
bool hasAddressDiscriminator() const
Whether there is any non-null address discriminator.
Definition Constants.h:1263
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1251
This class represents a range of values.
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI Constant * get(StructType *T, ArrayRef< Constant * > V)
friend class Constant
Definition Constants.h:618
static LLVM_ABI StructType * getTypeForElements(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct type to use for a constant with the specified set of elements.
StructType * getType() const
Specialization - reduce amount of casting.
Definition Constants.h:655
static LLVM_ABI ConstantTargetNone * get(TargetExtType *T)
Static factory methods - Return objects of the specified value.
TargetExtType * getType() const
Specialize the getType() method to always return an TargetExtType, which reduces the amount of castin...
Definition Constants.h:1070
A constant token which is empty.
Definition Constants.h:1029
static LLVM_ABI ConstantTokenNone * get(LLVMContext &Context)
Return the ConstantTokenNone.
void remove(ConstantClass *CP)
Remove this constant from the map.
ConstantClass * replaceOperandsInPlace(ArrayRef< Constant * > Operands, ConstantClass *CP, Value *From, Constant *To, unsigned NumUpdated=0, unsigned OperandNo=~0u)
Constant Vector Declarations.
Definition Constants.h:668
friend class Constant
Definition Constants.h:670
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition Constants.h:691
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
LLVM_ABI bool hasExactInverseFP() const
Return true if this scalar has an exact multiplicative inverse or this vector has an exact multiplica...
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
LLVM_ABI bool containsUndefElement() const
Return true if this is a vector constant that includes any strictly undef (not poison) elements.
static LLVM_ABI Constant * mergeUndefsWith(Constant *C, Constant *Other)
Merges undefs of a Constant with another Constant, along with the undefs already present.
LLVM_ABI ConstantRange toConstantRange() const
Convert constant to an approximate constant range.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI bool hasZeroLiveUses() const
Return true if the constant has no live uses.
LLVM_ABI bool isOneValue() const
Returns true if the value is one.
Definition Constants.cpp:89
LLVM_ABI bool isManifestConstant() const
Return true if a constant is ConstantData or a ConstantAggregate or ConstantExpr that contain only Co...
LLVM_ABI bool isNegativeZeroValue() const
Return true if the value is what would be returned by getZeroValueForNegation.
Definition Constants.cpp:50
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:68
Constant(Type *ty, ValueTy vty, AllocInfo AllocInfo)
Definition Constant.h:54
LLVM_ABI bool isMaxSignedValue() const
Return true if the value is the largest signed value.
LLVM_ABI bool hasOneLiveUse() const
Return true if the constant has exactly one live use.
LLVM_ABI bool needsRelocation() const
This method classifies the entry according to whether or not it may generate a relocation entry (eith...
LLVM_ABI bool isDLLImportDependent() const
Return true if the value is dependent on a dllimport variable.
LLVM_ABI const APInt & getUniqueInteger() const
If C is a constant integer then return its value, otherwise C must be a vector of constant integers,...
LLVM_ABI bool containsConstantExpression() const
Return true if this is a fixed width vector constant that includes any constant expressions.
LLVM_ABI bool isFiniteNonZeroFP() const
Return true if this is a finite and non-zero floating-point scalar constant or a fixed width vector c...
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
LLVM_ABI bool isNormalFP() const
Return true if this is a normal (as opposed to denormal, infinity, nan, or zero) floating-point scala...
LLVM_ABI bool needsDynamicRelocation() const
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNaN() const
Return true if this is a floating-point NaN constant or a vector floating-point constant with all NaN...
LLVM_ABI bool isMinSignedValue() const
Return true if the value is the smallest signed value.
LLVM_ABI bool isConstantUsed() const
Return true if the constant has users other than constant expressions and other dangling things.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
LLVM_ABI bool isThreadDependent() const
Return true if the value can vary between threads.
LLVM_ABI void destroyConstant()
Called if some element of this constant is no longer valid.
LLVM_ABI bool isNotMinSignedValue() const
Return true if the value is not the smallest signed value, or, for vectors, does not contain smallest...
LLVM_ABI bool isNotOneValue() const
Return true if the value is not the one value, or, for vectors, does not contain one value elements.
LLVM_ABI bool isElementWiseEqual(Value *Y) const
Return true if this constant and a constant 'Y' are element-wise equal.
LLVM_ABI bool containsUndefOrPoisonElement() const
Return true if this is a vector constant that includes any undef or poison elements.
LLVM_ABI bool containsPoisonElement() const
Return true if this is a vector constant that includes any poison elements.
LLVM_ABI void handleOperandChange(Value *, Value *)
This method is a special form of User::replaceUsesOfWith (which does not work on constants) that does...
Wrapper for a function that represents a value that functionally represents the original function.
Definition Constants.h:1137
GlobalValue * getGlobalValue() const
Definition Constants.h:1158
static LLVM_ABI DSOLocalEquivalent * get(GlobalValue *GV)
Return a DSOLocalEquivalent for the specified global value.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:309
ExtractElementConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to...
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:869
Represents flags for the getelementptr instruction/expression.
unsigned getRaw() const
GetElementPtrConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
std::optional< ConstantRange > getInRange() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static Type * getGEPReturnType(Value *Ptr, ArrayRef< Value * > IdxList)
Returns the pointer type returned by the GEP instruction, which may be a vector of pointers.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
PointerType * getType() const
Global values are always pointers.
InsertElementConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
bool isCast() const
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI bool isCommutative() const LLVM_READONLY
Return true if the instruction is commutative:
bool isBinaryOp() const
const char * getOpcodeName() const
LLVM_ABI void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag.
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:350
A wrapper class for inspecting calls to intrinsic functions.
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntOneConstants
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntZeroConstants
DenseMap< Type *, std::unique_ptr< ConstantPointerNull > > CPNConstants
DenseMap< APFloat, std::unique_ptr< ConstantFP > > FPConstants
DenseMap< Type *, std::unique_ptr< ConstantAggregateZero > > CAZConstants
DenseMap< Type *, std::unique_ptr< PoisonValue > > PVConstants
DenseMap< APInt, std::unique_ptr< ConstantInt > > IntConstants
std::unique_ptr< ConstantTokenNone > TheNoneToken
VectorConstantsTy VectorConstants
DenseMap< const GlobalValue *, NoCFIValue * > NoCFIValues
DenseMap< const BasicBlock *, BlockAddress * > BlockAddresses
DenseMap< Type *, std::unique_ptr< UndefValue > > UVConstants
StringMap< std::unique_ptr< ConstantDataSequential > > CDSConstants
StructConstantsTy StructConstants
ConstantUniqueMap< ConstantPtrAuth > ConstantPtrAuths
DenseMap< TargetExtType *, std::unique_ptr< ConstantTargetNone > > CTNConstants
ConstantUniqueMap< ConstantExpr > ExprConstants
DenseMap< unsigned, std::unique_ptr< ConstantByte > > ByteOneConstants
ArrayConstantsTy ArrayConstants
DenseMap< const GlobalValue *, DSOLocalEquivalent * > DSOLocalEquivalents
DenseMap< unsigned, std::unique_ptr< ConstantByte > > ByteZeroConstants
DenseMap< APInt, std::unique_ptr< ConstantByte > > ByteConstants
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVMContextImpl *const pImpl
Definition LLVMContext.h:70
Wrapper for a value that won't be replaced with a CFI jump table pointer in LowerTypeTestsModule.
Definition Constants.h:1176
static LLVM_ABI NoCFIValue * get(GlobalValue *GV)
Return a NoCFIValue for the specified function.
PointerType * getType() const
NoCFIValue is always a pointer.
Definition Constants.h:1200
GlobalValue * getGlobalValue() const
Definition Constants.h:1195
Class to represent pointers.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
Definition Constants.h:1673
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
friend class Constant
Definition Constants.h:1674
LLVM_ABI PoisonValue * getStructElement(unsigned Elt) const
If this poison has struct type, return a poison with the right element type for the specified element...
LLVM_ABI PoisonValue * getSequentialElement() const
If this poison has array or vector type, return a poison with the right element type.
LLVM_ABI PoisonValue * getElementValue(Constant *C) const
Return an poison of the right value for the specified GEP index if we can, otherwise return null (e....
static LLVM_ABI void SalvageDebugInfo(const Constant &C)
Replace all uses of the constant with Undef in debug info metadata.
Definition Metadata.cpp:338
ShuffleVectorConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:128
iterator end()
Definition StringMap.h:213
iterator find(StringRef Key)
Definition StringMap.h:226
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Class to represent struct types.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:479
Class to represent target extensions types, which are generally unintrospectable from target-independ...
@ HasZeroInit
zeroinitializer is valid for this target extension type.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
bool isByteTy() const
True if this is an instance of ByteType.
Definition Type.h:242
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:309
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition Type.h:76
@ HalfTyID
16-bit floating point type
Definition Type.h:57
@ TargetExtTyID
Target extension type.
Definition Type.h:80
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:78
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ StructTyID
Structures.
Definition Type.h:75
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:77
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:61
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:63
@ TokenTyID
Tokens.
Definition Type.h:68
@ ByteTyID
Arbitrary bit width bytes.
Definition Type.h:72
@ PointerTyID
Pointers.
Definition Type.h:74
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
static LLVM_ABI Type * getFloatingPointTy(LLVMContext &C, const fltSemantics &S)
Definition Type.cpp:125
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
static LLVM_ABI IntegerType * getInt16Ty(LLVMContext &C)
Definition Type.cpp:308
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
static LLVM_ABI ByteType * getByte8Ty(LLVMContext &C)
Definition Type.cpp:296
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:306
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:287
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:286
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
'undef' values are things that do not have specified contents.
Definition Constants.h:1625
LLVM_ABI UndefValue * getElementValue(Constant *C) const
Return an undef of the right value for the specified GEP index if we can, otherwise return null (e....
LLVM_ABI UndefValue * getStructElement(unsigned Elt) const
If this undef has struct type, return a undef with the right element type for the specified element.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
friend class Constant
Definition Constants.h:1626
LLVM_ABI unsigned getNumElements() const
Return the number of elements in the array, vector, or struct.
LLVM_ABI UndefValue * getSequentialElement() const
If this Undef has array or vector type, return a undef with the right element type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
const Use * getOperandList() const
Definition User.h:200
op_range operands()
Definition User.h:267
User(Type *ty, unsigned vty, AllocInfo AllocInfo)
Definition User.h:119
op_iterator op_begin()
Definition User.h:259
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Use & Op()
Definition User.h:171
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
iterator_range< value_op_iterator > operand_values()
Definition User.h:291
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator_impl< const User > const_user_iterator
Definition Value.h:392
user_iterator user_begin()
Definition Value.h:402
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:54
unsigned char SubclassOptionalData
Hold arbitary subclass data.
Definition Value.h:85
LLVM_ABI const Value * stripPointerCastsAndAliases() const
Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
Definition Value.cpp:717
LLVM_ABI const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition Value.cpp:725
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
User * user_back()
Definition Value.h:412
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:543
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:713
bool use_empty() const
Definition Value.h:346
user_iterator user_end()
Definition Value.h:410
iterator_range< use_iterator > uses()
Definition Value.h:380
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:807
ValueTy
Concrete subclass of this.
Definition Value.h:524
Base class of all SIMD vector types.
static VectorType * getInteger(VectorType *VTy)
This static method gets a VectorType with the same number of elements as the input type,...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
An efficient, type-erasing, non-owning reference to a callable.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Undef()
Match an arbitrary undef constant.
initializer< Ty > init(const Ty &Val)
constexpr double e
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1738
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Constant * ConstantFoldCompareInstruction(CmpInst::Predicate Predicate, Constant *C1, Constant *C2)
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:243
gep_type_iterator gep_type_end(const User *GEP)
void deleteConstant(Constant *C)
LLVM_ABI Constant * ConstantFoldGetElementPtr(Type *Ty, Constant *C, std::optional< ConstantRange > InRange, ArrayRef< Value * > Idxs)
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2172
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI Constant * ConstantFoldInsertElementInstruction(Constant *Val, Constant *Elt, Constant *Idx)
Attempt to constant fold an insertelement instruction with the specified operands and indices.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI Constant * ConstantFoldExtractElementInstruction(Constant *Val, Constant *Idx)
Attempt to constant fold an extractelement instruction with the specified operands and indices.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1884
constexpr unsigned BitWidth
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1916
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:248
LLVM_ABI Constant * ConstantFoldCastInstruction(unsigned opcode, Constant *V, Type *DestTy)
LLVM_ABI Constant * ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2, ArrayRef< int > Mask)
Attempt to constant fold a shufflevector instruction with the specified operands and mask.
LLVM_ABI Constant * ConstantFoldBinaryInstruction(unsigned Opcode, Constant *V1, Constant *V2)
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:860
#define N
#define NC
Definition regutils.h:42
Summary of memprof metadata on allocations.
Information about how a User object was allocated, to be passed into the User constructor.
Definition User.h:79