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 if (cast<VectorType>(Ty)->getElementType()->isPointerTy())
383 return ConstantPointerNull::get(Ty);
385 case Type::StructTyID:
386 case Type::ArrayTyID:
388 case Type::TokenTyID:
389 return ConstantTokenNone::get(Ty->getContext());
392 default:
393 // Function, Label, or Opaque type?
394 llvm_unreachable("Cannot create a null constant of that type!");
395 }
396}
397
399 Type *ScalarTy = Ty->getScalarType();
400
401 // Create the base integer constant.
402 Constant *C = ConstantInt::get(Ty->getContext(), V);
403
404 // Convert an integer to a pointer, if necessary.
405 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
407
408 // Convert an integer to a byte, if necessary.
409 if (ByteType *BTy = dyn_cast<ByteType>(ScalarTy))
411
412 // Broadcast a scalar to a vector, if necessary.
413 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
414 C = ConstantVector::getSplat(VTy->getElementCount(), C);
415
416 return C;
417}
418
420 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
421 return ConstantInt::get(Ty->getContext(),
422 APInt::getAllOnes(ITy->getBitWidth()));
423
424 if (Ty->isFloatingPointTy()) {
425 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
426 return ConstantFP::get(Ty->getContext(), FL);
427 }
428
429 if (ByteType *BTy = dyn_cast<ByteType>(Ty))
430 return ConstantByte::get(Ty->getContext(),
431 APInt::getAllOnes(BTy->getBitWidth()));
432
433 VectorType *VTy = cast<VectorType>(Ty);
434 return ConstantVector::getSplat(VTy->getElementCount(),
435 getAllOnesValue(VTy->getElementType()));
436}
437
439 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
440 "Must be an aggregate/vector constant");
441
442 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
443 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
444
445 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
446 return Elt < CAZ->getElementCount().getKnownMinValue()
447 ? CAZ->getElementValue(Elt)
448 : nullptr;
449
450 if (const auto *CI = dyn_cast<ConstantInt>(this))
451 return Elt < cast<VectorType>(getType())
452 ->getElementCount()
453 .getKnownMinValue()
454 ? ConstantInt::get(getContext(), CI->getValue())
455 : nullptr;
456
457 if (const auto *CB = dyn_cast<ConstantByte>(this))
458 return Elt < cast<VectorType>(getType())
459 ->getElementCount()
460 .getKnownMinValue()
461 ? ConstantByte::get(getContext(), CB->getValue())
462 : nullptr;
463
464 if (const auto *CFP = dyn_cast<ConstantFP>(this))
465 return Elt < cast<VectorType>(getType())
466 ->getElementCount()
467 .getKnownMinValue()
468 ? ConstantFP::get(getContext(), CFP->getValue())
469 : nullptr;
470
471 if (isa<ConstantPointerNull>(this)) {
472 auto *VT = cast<VectorType>(getType());
473 return Elt < VT->getElementCount().getKnownMinValue()
474 ? ConstantPointerNull::get(VT->getElementType())
475 : nullptr;
476 }
477
478 // FIXME: getNumElements() will fail for non-fixed vector types.
480 return nullptr;
481
482 if (const auto *PV = dyn_cast<PoisonValue>(this))
483 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
484
485 if (const auto *UV = dyn_cast<UndefValue>(this))
486 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
487
488 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
489 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
490 : nullptr;
491
492 return nullptr;
493}
494
496 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
498 // Check if the constant fits into an uint64_t.
499 if (CI->getValue().getActiveBits() > 64)
500 return nullptr;
501 return getAggregateElement(CI->getZExtValue());
502 }
503 return nullptr;
504}
505
507 /// First call destroyConstantImpl on the subclass. This gives the subclass
508 /// a chance to remove the constant from any maps/pools it's contained in.
509 switch (getValueID()) {
510 default:
511 llvm_unreachable("Not a constant!");
512#define HANDLE_CONSTANT(Name) \
513 case Value::Name##Val: \
514 cast<Name>(this)->destroyConstantImpl(); \
515 break;
516#include "llvm/IR/Value.def"
517 }
518
519 // When a Constant is destroyed, there may be lingering
520 // references to the constant by other constants in the constant pool. These
521 // constants are implicitly dependent on the module that is being deleted,
522 // but they don't know that. Because we only find out when the CPV is
523 // deleted, we must now notify all of our users (that should only be
524 // Constants) that they are, in fact, invalid now and should be deleted.
525 //
526 while (!use_empty()) {
527 Value *V = user_back();
528#ifndef NDEBUG // Only in -g mode...
529 if (!isa<Constant>(V)) {
530 dbgs() << "While deleting: " << *this
531 << "\n\nUse still stuck around after Def is destroyed: " << *V
532 << "\n\n";
533 }
534#endif
535 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
536 cast<Constant>(V)->destroyConstant();
537
538 // The constant should remove itself from our use list...
539 assert((use_empty() || user_back() != V) && "Constant not removed!");
540 }
541
542 // Value has no outstanding references it is safe to delete it now...
543 deleteConstant(this);
544}
545
547 switch (C->getValueID()) {
548 case Constant::ConstantIntVal:
549 delete static_cast<ConstantInt *>(C);
550 break;
551 case Constant::ConstantByteVal:
552 delete static_cast<ConstantByte *>(C);
553 break;
554 case Constant::ConstantFPVal:
555 delete static_cast<ConstantFP *>(C);
556 break;
557 case Constant::ConstantAggregateZeroVal:
558 delete static_cast<ConstantAggregateZero *>(C);
559 break;
560 case Constant::ConstantArrayVal:
561 delete static_cast<ConstantArray *>(C);
562 break;
563 case Constant::ConstantStructVal:
564 delete static_cast<ConstantStruct *>(C);
565 break;
566 case Constant::ConstantVectorVal:
567 delete static_cast<ConstantVector *>(C);
568 break;
569 case Constant::ConstantPointerNullVal:
570 delete static_cast<ConstantPointerNull *>(C);
571 break;
572 case Constant::ConstantDataArrayVal:
573 delete static_cast<ConstantDataArray *>(C);
574 break;
575 case Constant::ConstantDataVectorVal:
576 delete static_cast<ConstantDataVector *>(C);
577 break;
578 case Constant::ConstantTokenNoneVal:
579 delete static_cast<ConstantTokenNone *>(C);
580 break;
581 case Constant::BlockAddressVal:
582 delete static_cast<BlockAddress *>(C);
583 break;
584 case Constant::DSOLocalEquivalentVal:
585 delete static_cast<DSOLocalEquivalent *>(C);
586 break;
587 case Constant::NoCFIValueVal:
588 delete static_cast<NoCFIValue *>(C);
589 break;
590 case Constant::ConstantPtrAuthVal:
591 delete static_cast<ConstantPtrAuth *>(C);
592 break;
593 case Constant::UndefValueVal:
594 delete static_cast<UndefValue *>(C);
595 break;
596 case Constant::PoisonValueVal:
597 delete static_cast<PoisonValue *>(C);
598 break;
599 case Constant::ConstantExprVal:
601 delete static_cast<CastConstantExpr *>(C);
602 else if (isa<BinaryConstantExpr>(C))
603 delete static_cast<BinaryConstantExpr *>(C);
605 delete static_cast<ExtractElementConstantExpr *>(C);
607 delete static_cast<InsertElementConstantExpr *>(C);
609 delete static_cast<ShuffleVectorConstantExpr *>(C);
611 delete static_cast<GetElementPtrConstantExpr *>(C);
612 else
613 llvm_unreachable("Unexpected constant expr");
614 break;
615 default:
616 llvm_unreachable("Unexpected constant");
617 }
618}
619
620/// Check if C contains a GlobalValue for which Predicate is true.
621static bool
623 bool (*Predicate)(const GlobalValue *)) {
626 WorkList.push_back(C);
627 Visited.insert(C);
628
629 while (!WorkList.empty()) {
630 const Constant *WorkItem = WorkList.pop_back_val();
631 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
632 if (Predicate(GV))
633 return true;
634 for (const Value *Op : WorkItem->operands()) {
635 const Constant *ConstOp = dyn_cast<Constant>(Op);
636 if (!ConstOp)
637 continue;
638 if (Visited.insert(ConstOp).second)
639 WorkList.push_back(ConstOp);
640 }
641 }
642 return false;
643}
644
646 auto DLLImportPredicate = [](const GlobalValue *GV) {
647 return GV->isThreadLocal();
648 };
649 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
650}
651
653 auto DLLImportPredicate = [](const GlobalValue *GV) {
654 return GV->hasDLLImportStorageClass();
655 };
656 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
657}
658
660 for (const User *U : users()) {
661 const Constant *UC = dyn_cast<Constant>(U);
662 if (!UC || isa<GlobalValue>(UC))
663 return true;
664
665 if (UC->isConstantUsed())
666 return true;
667 }
668 return false;
669}
670
672 return getRelocationInfo() == GlobalRelocation;
673}
674
676 return getRelocationInfo() != NoRelocation;
677}
678
679Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
680 if (isa<GlobalValue>(this))
681 return GlobalRelocation; // Global reference.
682
683 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
684 return BA->getFunction()->getRelocationInfo();
685
686 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
687 if (CE->getOpcode() == Instruction::Sub) {
688 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
689 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
690 if (LHS && RHS &&
691 (LHS->getOpcode() == Instruction::PtrToInt ||
692 LHS->getOpcode() == Instruction::PtrToAddr) &&
693 (RHS->getOpcode() == Instruction::PtrToInt ||
694 RHS->getOpcode() == Instruction::PtrToAddr)) {
695 Constant *LHSOp0 = LHS->getOperand(0);
696 Constant *RHSOp0 = RHS->getOperand(0);
697
698 // While raw uses of blockaddress need to be relocated, differences
699 // between two of them don't when they are for labels in the same
700 // function. This is a common idiom when creating a table for the
701 // indirect goto extension, so we handle it efficiently here.
702 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
703 cast<BlockAddress>(LHSOp0)->getFunction() ==
705 return NoRelocation;
706
707 // Relative pointers do not need to be dynamically relocated.
708 if (auto *RHSGV =
710 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
711 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
712 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
713 return LocalRelocation;
714 } else if (isa<DSOLocalEquivalent>(LHS)) {
715 if (RHSGV->isDSOLocal())
716 return LocalRelocation;
717 }
718 }
719 }
720 }
721 }
722
723 PossibleRelocationsTy Result = NoRelocation;
724 for (const Value *Op : operands())
725 Result = std::max(cast<Constant>(Op)->getRelocationInfo(), Result);
726
727 return Result;
728}
729
730/// Return true if the specified constantexpr is dead. This involves
731/// recursively traversing users of the constantexpr.
732/// If RemoveDeadUsers is true, also remove dead users at the same time.
733static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
734 if (isa<GlobalValue>(C)) return false; // Cannot remove this
735
736 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
737 while (I != E) {
739 if (!User) return false; // Non-constant usage;
740 if (!constantIsDead(User, RemoveDeadUsers))
741 return false; // Constant wasn't dead
742
743 // Just removed User, so the iterator was invalidated.
744 // Since we return immediately upon finding a live user, we can always
745 // restart from user_begin().
746 if (RemoveDeadUsers)
747 I = C->user_begin();
748 else
749 ++I;
750 }
751
752 if (RemoveDeadUsers) {
753 // If C is only used by metadata, it should not be preserved but should
754 // have its uses replaced.
756 const_cast<Constant *>(C)->destroyConstant();
757 }
758
759 return true;
760}
761
764 Value::const_user_iterator LastNonDeadUser = E;
765 while (I != E) {
767 if (!User) {
768 LastNonDeadUser = I;
769 ++I;
770 continue;
771 }
772
773 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
774 // If the constant wasn't dead, remember that this was the last live use
775 // and move on to the next constant.
776 LastNonDeadUser = I;
777 ++I;
778 continue;
779 }
780
781 // If the constant was dead, then the iterator is invalidated.
782 if (LastNonDeadUser == E)
783 I = user_begin();
784 else
785 I = std::next(LastNonDeadUser);
786 }
787}
788
789bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
790
791bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
792
793bool Constant::hasNLiveUses(unsigned N) const {
794 unsigned NumUses = 0;
795 for (const Use &U : uses()) {
796 const Constant *User = dyn_cast<Constant>(U.getUser());
797 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
798 ++NumUses;
799
800 if (NumUses > N)
801 return false;
802 }
803 }
804 return NumUses == N;
805}
806
808 assert(C && Replacement && "Expected non-nullptr constant arguments");
809 Type *Ty = C->getType();
810 if (match(C, m_Undef())) {
811 assert(Ty == Replacement->getType() && "Expected matching types");
812 return Replacement;
813 }
814
815 // Don't know how to deal with this constant.
816 auto *VTy = dyn_cast<FixedVectorType>(Ty);
817 if (!VTy)
818 return C;
819
820 unsigned NumElts = VTy->getNumElements();
821 SmallVector<Constant *, 32> NewC(NumElts);
822 for (unsigned i = 0; i != NumElts; ++i) {
823 Constant *EltC = C->getAggregateElement(i);
824 assert((!EltC || EltC->getType() == Replacement->getType()) &&
825 "Expected matching types");
826 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
827 }
828 return ConstantVector::get(NewC);
829}
830
832 assert(C && Other && "Expected non-nullptr constant arguments");
833 if (match(C, m_Undef()))
834 return C;
835
836 Type *Ty = C->getType();
837 if (match(Other, m_Undef()))
838 return UndefValue::get(Ty);
839
840 auto *VTy = dyn_cast<FixedVectorType>(Ty);
841 if (!VTy)
842 return C;
843
844 Type *EltTy = VTy->getElementType();
845 unsigned NumElts = VTy->getNumElements();
846 assert(isa<FixedVectorType>(Other->getType()) &&
847 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
848 "Type mismatch");
849
850 bool FoundExtraUndef = false;
851 SmallVector<Constant *, 32> NewC(NumElts);
852 for (unsigned I = 0; I != NumElts; ++I) {
853 NewC[I] = C->getAggregateElement(I);
854 Constant *OtherEltC = Other->getAggregateElement(I);
855 assert(NewC[I] && OtherEltC && "Unknown vector element");
856 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
857 NewC[I] = UndefValue::get(EltTy);
858 FoundExtraUndef = true;
859 }
860 }
861 if (FoundExtraUndef)
862 return ConstantVector::get(NewC);
863 return C;
864}
865
867 if (isa<UndefValue>(this))
868 return false;
869 if (isa<ConstantData>(this))
870 return true;
871 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
872 for (const Value *Op : operand_values())
874 return false;
875 return true;
876 }
877 return false;
878}
879
880//===----------------------------------------------------------------------===//
881// ConstantInt
882//===----------------------------------------------------------------------===//
883
884ConstantInt::ConstantInt(Type *Ty, const APInt &V)
885 : ConstantData(Ty, ConstantIntVal), Val(V) {
886 assert(V.getBitWidth() ==
887 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
888 "Invalid constant for type");
889 if (V.isZero())
891}
892
893ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
894 LLVMContextImpl *pImpl = Context.pImpl;
895 if (!pImpl->TheTrueVal)
896 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
897 return pImpl->TheTrueVal;
898}
899
900ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
901 LLVMContextImpl *pImpl = Context.pImpl;
902 if (!pImpl->TheFalseVal)
903 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
904 return pImpl->TheFalseVal;
905}
906
907ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
908 return V ? getTrue(Context) : getFalse(Context);
909}
910
912 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
913 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
914 if (auto *VTy = dyn_cast<VectorType>(Ty))
915 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
916 return TrueC;
917}
918
920 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
921 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
922 if (auto *VTy = dyn_cast<VectorType>(Ty))
923 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
924 return FalseC;
925}
926
928 return V ? getTrue(Ty) : getFalse(Ty);
929}
930
931// Get a ConstantInt from an APInt.
932ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
933 // get an existing value or the insertion position
934 LLVMContextImpl *pImpl = Context.pImpl;
935 std::unique_ptr<ConstantInt> &Slot =
936 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
937 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
938 : pImpl->IntConstants[V];
939 if (!Slot) {
940 // Get the corresponding integer type for the bit width of the value.
941 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
942 Slot.reset(new ConstantInt(ITy, V));
943 }
944 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
945 return Slot.get();
946}
947
948// Get a ConstantInt vector with each lane set to the same APInt.
949ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
950 const APInt &V) {
951 // Get an existing value or the insertion position.
952 std::unique_ptr<ConstantInt> &Slot =
953 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
954 if (!Slot) {
955 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
956 VectorType *VTy = VectorType::get(ITy, EC);
957 Slot.reset(new ConstantInt(VTy, V));
958 }
959
960#ifndef NDEBUG
961 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
962 VectorType *VTy = VectorType::get(ITy, EC);
963 assert(Slot->getType() == VTy);
964#endif
965 return Slot.get();
966}
967
968Constant *ConstantInt::get(Type *Ty, uint64_t V, bool IsSigned,
969 bool ImplicitTrunc) {
970 Constant *C =
971 get(cast<IntegerType>(Ty->getScalarType()), V, IsSigned, ImplicitTrunc);
972
973 // For vectors, broadcast the value.
974 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
975 return ConstantVector::getSplat(VTy->getElementCount(), C);
976
977 return C;
978}
979
980ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool IsSigned,
981 bool ImplicitTrunc) {
982 return get(Ty->getContext(),
983 APInt(Ty->getBitWidth(), V, IsSigned, ImplicitTrunc));
984}
985
986Constant *ConstantInt::get(Type *Ty, const APInt& V) {
987 ConstantInt *C = get(Ty->getContext(), V);
988 assert(C->getType() == Ty->getScalarType() &&
989 "ConstantInt type doesn't match the type implied by its value!");
990
991 // For vectors, broadcast the value.
992 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
993 return ConstantVector::getSplat(VTy->getElementCount(), C);
994
995 return C;
996}
997
998ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
999 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1000}
1001
1002/// Remove the constant from the constant table.
1003void ConstantInt::destroyConstantImpl() {
1004 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
1005}
1006
1007//===----------------------------------------------------------------------===//
1008// ConstantByte
1009//===----------------------------------------------------------------------===//
1010
1011ConstantByte::ConstantByte(Type *Ty, const APInt &V)
1012 : ConstantData(Ty, ConstantByteVal), Val(V) {
1013 assert(V.getBitWidth() ==
1014 cast<ByteType>(Ty->getScalarType())->getBitWidth() &&
1015 "Invalid constant for type");
1016 if (V.isZero())
1018}
1019
1020// Get a ConstantByte from an APInt.
1021ConstantByte *ConstantByte::get(LLVMContext &Context, const APInt &V) {
1022 // get an existing value or the insertion position
1023 LLVMContextImpl *pImpl = Context.pImpl;
1024 std::unique_ptr<ConstantByte> &Slot =
1025 V.isZero() ? pImpl->ByteZeroConstants[V.getBitWidth()]
1026 : V.isOne() ? pImpl->ByteOneConstants[V.getBitWidth()]
1027 : pImpl->ByteConstants[V];
1028 if (!Slot) {
1029 // Get the corresponding byte type for the bit width of the value.
1030 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1031 Slot.reset(new ConstantByte(BTy, V));
1032 }
1033 assert(Slot->getType() == ByteType::get(Context, V.getBitWidth()));
1034 return Slot.get();
1035}
1036
1037// Get a ConstantByte vector with each lane set to the same APInt.
1038ConstantByte *ConstantByte::get(LLVMContext &Context, ElementCount EC,
1039 const APInt &V) {
1040 // Get an existing value or the insertion position.
1041 std::unique_ptr<ConstantByte> &Slot =
1042 Context.pImpl->ByteSplatConstants[std::make_pair(EC, V)];
1043 if (!Slot) {
1044 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1045 VectorType *VTy = VectorType::get(BTy, EC);
1046 Slot.reset(new ConstantByte(VTy, V));
1047 }
1048
1049#ifndef NDEBUG
1050 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1051 VectorType *VTy = VectorType::get(BTy, EC);
1052 assert(Slot->getType() == VTy);
1053#endif
1054 return Slot.get();
1055}
1056
1057Constant *ConstantByte::get(Type *Ty, uint64_t V, bool isSigned,
1058 bool ImplicitTrunc) {
1059 Constant *C =
1060 get(cast<ByteType>(Ty->getScalarType()), V, isSigned, ImplicitTrunc);
1061
1062 // For vectors, broadcast the value.
1063 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1064 return ConstantVector::getSplat(VTy->getElementCount(), C);
1065
1066 return C;
1067}
1068
1069ConstantByte *ConstantByte::get(ByteType *Ty, uint64_t V, bool isSigned,
1070 bool ImplicitTrunc) {
1071 return get(Ty->getContext(),
1072 APInt(Ty->getBitWidth(), V, isSigned, ImplicitTrunc));
1073}
1074
1075Constant *ConstantByte::get(Type *Ty, const APInt &V) {
1076 ConstantByte *C = get(Ty->getContext(), V);
1077 assert(C->getType() == Ty->getScalarType() &&
1078 "ConstantByte type doesn't match the type implied by its value!");
1079
1080 // For vectors, broadcast the value.
1081 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1082 return ConstantVector::getSplat(VTy->getElementCount(), C);
1083
1084 return C;
1085}
1086
1087ConstantByte *ConstantByte::get(ByteType *Ty, StringRef Str, uint8_t radix) {
1088 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1089}
1090
1091/// Remove the constant from the constant table.
1092void ConstantByte::destroyConstantImpl() {
1093 llvm_unreachable("You can't ConstantByte->destroyConstantImpl()!");
1094}
1095
1096//===----------------------------------------------------------------------===//
1097// ConstantFP
1098//===----------------------------------------------------------------------===//
1099
1100ConstantFP *ConstantFP::get(Type *Ty, double V) {
1101 LLVMContext &Context = Ty->getContext();
1102
1103 APFloat FV(V);
1104 bool ignored;
1105 FV.convert(Ty->getScalarType()->getFltSemantics(),
1107
1108 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1109 return get(Context, VTy->getElementCount(), FV);
1110
1111 return get(Context, FV);
1112}
1113
1114ConstantFP *ConstantFP::get(Type *Ty, const APFloat &V) {
1115 LLVMContext &Context = Ty->getContext();
1116 assert(Ty->getScalarType() ==
1117 Type::getFloatingPointTy(Context, V.getSemantics()) &&
1118 "ConstantFP type doesn't match the type implied by its value!");
1119
1120 if (auto *VTy = dyn_cast<VectorType>(Ty))
1121 return get(Context, VTy->getElementCount(), V);
1122
1123 return get(Ty->getContext(), V);
1124}
1125
1126ConstantFP *ConstantFP::get(Type *Ty, StringRef Str) {
1127 LLVMContext &Context = Ty->getContext();
1128 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1129
1130 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1131 return get(Context, VTy->getElementCount(), FV);
1132
1133 return get(Context, FV);
1134}
1135
1136ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1137 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1138 return get(Ty, APFloat::getInf(Semantics, Negative));
1139}
1140
1141ConstantFP *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1142 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1143 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1144 return get(Ty, NaN);
1145}
1146
1147ConstantFP *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1148 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1149 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1150 return get(Ty, NaN);
1151}
1152
1153ConstantFP *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1154 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1155 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1156 return get(Ty, NaN);
1157}
1158
1159ConstantFP *ConstantFP::getZero(Type *Ty, bool Negative) {
1160 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1161 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1162 return get(Ty, NegZero);
1163}
1164
1165// ConstantFP accessors.
1166ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1167 LLVMContextImpl* pImpl = Context.pImpl;
1168
1169 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1170
1171 if (!Slot) {
1172 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1173 Slot.reset(new ConstantFP(Ty, V));
1174 }
1175
1176 return Slot.get();
1177}
1178
1179// Get a ConstantFP vector with each lane set to the same APFloat.
1180ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1181 const APFloat &V) {
1182 // Get an existing value or the insertion position.
1183 std::unique_ptr<ConstantFP> &Slot =
1184 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1185 if (!Slot) {
1186 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1187 VectorType *VTy = VectorType::get(EltTy, EC);
1188 Slot.reset(new ConstantFP(VTy, V));
1189 }
1190
1191#ifndef NDEBUG
1192 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1193 VectorType *VTy = VectorType::get(EltTy, EC);
1194 assert(Slot->getType() == VTy);
1195#endif
1196 return Slot.get();
1197}
1198
1199ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1200 : ConstantData(Ty, ConstantFPVal), Val(V) {
1201 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1202 "FP type Mismatch");
1203 // ppc_fp128 determine isZero using high order double only
1204 // so check the bitwise value to make sure all bits are zero.
1205 if (V.bitcastToAPInt().isZero())
1207}
1208
1210 return Val.bitwiseIsEqual(V);
1211}
1212
1213/// Remove the constant from the constant table.
1214void ConstantFP::destroyConstantImpl() {
1215 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1216}
1217
1218//===----------------------------------------------------------------------===//
1219// ConstantAggregateZero Implementation
1220//===----------------------------------------------------------------------===//
1221
1223 if (auto *AT = dyn_cast<ArrayType>(getType()))
1224 return Constant::getNullValue(AT->getElementType());
1225 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1226}
1227
1229 return Constant::getNullValue(getType()->getStructElementType(Elt));
1230}
1231
1237
1240 return getSequentialElement();
1241 return getStructElement(Idx);
1242}
1243
1245 Type *Ty = getType();
1246 if (auto *AT = dyn_cast<ArrayType>(Ty))
1247 return ElementCount::getFixed(AT->getNumElements());
1248 if (auto *VT = dyn_cast<VectorType>(Ty))
1249 return VT->getElementCount();
1250 return ElementCount::getFixed(Ty->getStructNumElements());
1251}
1252
1253//===----------------------------------------------------------------------===//
1254// UndefValue Implementation
1255//===----------------------------------------------------------------------===//
1256
1259 return UndefValue::get(ATy->getElementType());
1260 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1261}
1262
1263UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1264 return UndefValue::get(getType()->getStructElementType(Elt));
1265}
1266
1269 return getSequentialElement();
1270 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1271}
1272
1273UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1275 return getSequentialElement();
1276 return getStructElement(Idx);
1277}
1278
1280 Type *Ty = getType();
1281 if (auto *AT = dyn_cast<ArrayType>(Ty))
1282 return AT->getNumElements();
1283 if (auto *VT = dyn_cast<VectorType>(Ty))
1284 return cast<FixedVectorType>(VT)->getNumElements();
1285 return Ty->getStructNumElements();
1286}
1287
1288//===----------------------------------------------------------------------===//
1289// PoisonValue Implementation
1290//===----------------------------------------------------------------------===//
1291
1294 return PoisonValue::get(ATy->getElementType());
1295 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1296}
1297
1298PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1299 return PoisonValue::get(getType()->getStructElementType(Elt));
1300}
1301
1304 return getSequentialElement();
1305 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1306}
1307
1308PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1310 return getSequentialElement();
1311 return getStructElement(Idx);
1312}
1313
1314//===----------------------------------------------------------------------===//
1315// ConstantXXX Classes
1316//===----------------------------------------------------------------------===//
1317
1318template <typename ItTy, typename EltTy>
1319static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1320 for (; Start != End; ++Start)
1321 if (*Start != Elt)
1322 return false;
1323 return true;
1324}
1325
1326template <typename SequentialTy, typename ElementTy>
1328 assert(!V.empty() && "Cannot get empty int sequence.");
1329
1331 for (Constant *C : V)
1332 if (auto *CI = dyn_cast<ConstantInt>(C))
1333 Elts.push_back(CI->getZExtValue());
1334 else
1335 return nullptr;
1336 return SequentialTy::get(V[0]->getContext(), Elts);
1337}
1338
1339template <typename SequentialTy, typename ElementTy>
1341 assert(!V.empty() && "Cannot get empty byte sequence.");
1342
1344 for (Constant *C : V)
1345 if (auto *CI = dyn_cast<ConstantByte>(C))
1346 Elts.push_back(CI->getZExtValue());
1347 else
1348 return nullptr;
1349 return SequentialTy::getByte(V[0]->getType(), Elts);
1350}
1351
1352template <typename SequentialTy, typename ElementTy>
1354 assert(!V.empty() && "Cannot get empty FP sequence.");
1355
1357 for (Constant *C : V)
1358 if (auto *CFP = dyn_cast<ConstantFP>(C))
1359 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1360 else
1361 return nullptr;
1362 return SequentialTy::getFP(V[0]->getType(), Elts);
1363}
1364
1365template <typename SequenceTy>
1368 // We speculatively build the elements here even if it turns out that there is
1369 // a constantexpr or something else weird, since it is so uncommon for that to
1370 // happen.
1371 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1372 if (CI->getType()->isIntegerTy(8))
1374 else if (CI->getType()->isIntegerTy(16))
1376 else if (CI->getType()->isIntegerTy(32))
1378 else if (CI->getType()->isIntegerTy(64))
1380 } else if (ConstantByte *CB = dyn_cast<ConstantByte>(C)) {
1381 if (CB->getType()->isByteTy(8))
1383 else if (CB->getType()->isByteTy(16))
1385 else if (CB->getType()->isByteTy(32))
1387 else if (CB->getType()->isByteTy(64))
1389 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1390 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1392 else if (CFP->getType()->isFloatTy())
1394 else if (CFP->getType()->isDoubleTy())
1396 }
1397
1398 return nullptr;
1399}
1400
1404 : Constant(T, VT, AllocInfo) {
1405 llvm::copy(V, op_begin());
1406
1407 // Check that types match, unless this is an opaque struct.
1408 if (auto *ST = dyn_cast<StructType>(T)) {
1409 if (ST->isOpaque())
1410 return;
1411 for (unsigned I = 0, E = V.size(); I != E; ++I)
1412 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1413 "Initializer for struct element doesn't match!");
1414 }
1415}
1416
1417ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1419 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1420 assert(V.size() == T->getNumElements() &&
1421 "Invalid initializer for constant array");
1422}
1423
1425 if (Constant *C = getImpl(Ty, V))
1426 return C;
1427 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1428}
1429
1430Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1431 // Empty arrays are canonicalized to ConstantAggregateZero.
1432 if (V.empty())
1433 return ConstantAggregateZero::get(Ty);
1434
1435 for (Constant *C : V) {
1436 assert(C->getType() == Ty->getElementType() &&
1437 "Wrong type in array element initializer");
1438 (void)C;
1439 }
1440
1441 // If this is an all-zero array, return a ConstantAggregateZero object. If
1442 // all undef, return an UndefValue, if "all simple", then return a
1443 // ConstantDataArray.
1444 Constant *C = V[0];
1445 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1446 return PoisonValue::get(Ty);
1447
1448 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1449 return UndefValue::get(Ty);
1450
1451 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1452 return ConstantAggregateZero::get(Ty);
1453
1454 // Check to see if all of the elements are ConstantFP or ConstantInt or
1455 // ConstantByte and if the element type is compatible with ConstantDataVector.
1456 // If so, use it.
1459
1460 // Otherwise, we really do want to create a ConstantArray.
1461 return nullptr;
1462}
1463
1466 bool Packed) {
1467 unsigned VecSize = V.size();
1468 SmallVector<Type*, 16> EltTypes(VecSize);
1469 for (unsigned i = 0; i != VecSize; ++i)
1470 EltTypes[i] = V[i]->getType();
1471
1472 return StructType::get(Context, EltTypes, Packed);
1473}
1474
1475
1477 bool Packed) {
1478 assert(!V.empty() &&
1479 "ConstantStruct::getTypeForElements cannot be called on empty list");
1480 return getTypeForElements(V[0]->getContext(), V, Packed);
1481}
1482
1483ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1485 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1486 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1487 "Invalid initializer for constant struct");
1488}
1489
1490// ConstantStruct accessors.
1492 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1493 "Incorrect # elements specified to ConstantStruct::get");
1494
1495 // Create a ConstantAggregateZero value if all elements are zeros.
1496 bool isZero = true;
1497 bool isUndef = false;
1498 bool isPoison = false;
1499
1500 if (!V.empty()) {
1501 isUndef = isa<UndefValue>(V[0]);
1502 isPoison = isa<PoisonValue>(V[0]);
1503 isZero = V[0]->isNullValue();
1504 // PoisonValue inherits UndefValue, so its check is not necessary.
1505 if (isUndef || isZero) {
1506 for (Constant *C : V) {
1507 if (!C->isNullValue())
1508 isZero = false;
1509 if (!isa<PoisonValue>(C))
1510 isPoison = false;
1512 isUndef = false;
1513 }
1514 }
1515 }
1516 if (isZero)
1517 return ConstantAggregateZero::get(ST);
1518 if (isPoison)
1519 return PoisonValue::get(ST);
1520 if (isUndef)
1521 return UndefValue::get(ST);
1522
1523 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1524}
1525
1526ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1528 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1529 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1530 "Invalid initializer for constant vector");
1531}
1532
1533// ConstantVector accessors.
1535 if (Constant *C = getImpl(V))
1536 return C;
1537 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1538 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1539}
1540
1541Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1542 assert(!V.empty() && "Vectors can't be empty");
1543 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1544
1545 // If this is an all-undef or all-zero vector, return a
1546 // ConstantAggregateZero or UndefValue.
1547 Constant *C = V[0];
1548 bool isZero = C->isNullValue();
1549 bool isUndef = isa<UndefValue>(C);
1550 bool isPoison = isa<PoisonValue>(C);
1551 bool isSplatFP = isa<ConstantFP>(C);
1553 bool isSplatByte = isa<ConstantByte>(C);
1554 bool isSplatPtrNull = isa<ConstantPointerNull>(C);
1555
1556 if (isZero || isUndef || isSplatFP || isSplatInt || isSplatByte ||
1557 isSplatPtrNull) {
1558 for (unsigned i = 1, e = V.size(); i != e; ++i)
1559 if (V[i] != C) {
1560 isZero = isUndef = isPoison = isSplatFP = isSplatInt = isSplatByte =
1561 isSplatPtrNull = false;
1562 break;
1563 }
1564 }
1565
1566 if (isSplatPtrNull)
1568 if (isZero)
1570 if (isPoison)
1571 return PoisonValue::get(T);
1572 if (isUndef)
1573 return UndefValue::get(T);
1574 if (isSplatFP)
1575 return ConstantFP::get(C->getContext(), T->getElementCount(),
1576 cast<ConstantFP>(C)->getValue());
1577 if (isSplatInt)
1578 return ConstantInt::get(C->getContext(), T->getElementCount(),
1579 cast<ConstantInt>(C)->getValue());
1580 if (isSplatByte)
1581 return ConstantByte::get(C->getContext(), T->getElementCount(),
1582 cast<ConstantByte>(C)->getValue());
1583
1584 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1585 // the element type is compatible with ConstantDataVector. If so, use it.
1588
1589 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1590 // the operand list contains a ConstantExpr or something else strange.
1591 return nullptr;
1592}
1593
1595 if (isa<ConstantPointerNull>(V)) {
1596 VectorType *VTy = VectorType::get(V->getType(), EC);
1597 return ConstantPointerNull::get(VTy);
1598 }
1599
1600 if (auto *CB = dyn_cast<ConstantByte>(V))
1601 return ConstantByte::get(V->getContext(), EC, CB->getValue());
1602
1603 if (auto *CFP = dyn_cast<ConstantFP>(V))
1604 return ConstantFP::get(V->getContext(), EC, CFP->getValue());
1605
1606 if (!EC.isScalable()) {
1607 // Maintain special handling of zero.
1608 if (!V->isNullValue()) {
1610 return ConstantInt::get(V->getContext(), EC,
1611 cast<ConstantInt>(V)->getValue());
1612 }
1613
1614 // If this splat is compatible with ConstantDataVector, use it instead of
1615 // ConstantVector.
1616 if (isa<ConstantInt>(V) &&
1618 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1619
1620 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1621 return get(Elts);
1622 }
1623
1624 // Maintain special handling of zero.
1625 if (!V->isNullValue()) {
1627 return ConstantInt::get(V->getContext(), EC,
1628 cast<ConstantInt>(V)->getValue());
1629 }
1630
1631 Type *VTy = VectorType::get(V->getType(), EC);
1632
1633 if (V->isNullValue())
1634 return ConstantAggregateZero::get(VTy);
1635 if (isa<PoisonValue>(V))
1636 return PoisonValue::get(VTy);
1637 if (isa<UndefValue>(V))
1638 return UndefValue::get(VTy);
1639
1640 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1641
1642 // Move scalar into vector.
1643 Constant *PoisonV = PoisonValue::get(VTy);
1644 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1645 // Build shuffle mask to perform the splat.
1646 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1647 // Splat.
1648 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1649}
1650
1651ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1652 LLVMContextImpl *pImpl = Context.pImpl;
1653 if (!pImpl->TheNoneToken)
1654 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1655 return pImpl->TheNoneToken.get();
1656}
1657
1658/// Remove the constant from the constant table.
1659void ConstantTokenNone::destroyConstantImpl() {
1660 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1661}
1662
1663// Utility function for determining if a ConstantExpr is a CastOp or not. This
1664// can't be inline because we don't want to #include Instruction.h into
1665// Constant.h
1667
1671
1673 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1674}
1675
1677 bool OnlyIfReduced, Type *SrcTy) const {
1678 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1679
1680 // If no operands changed return self.
1681 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1682 return const_cast<ConstantExpr*>(this);
1683
1684 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1685 switch (getOpcode()) {
1686 case Instruction::Trunc:
1687 case Instruction::ZExt:
1688 case Instruction::SExt:
1689 case Instruction::FPTrunc:
1690 case Instruction::FPExt:
1691 case Instruction::UIToFP:
1692 case Instruction::SIToFP:
1693 case Instruction::FPToUI:
1694 case Instruction::FPToSI:
1695 case Instruction::PtrToAddr:
1696 case Instruction::PtrToInt:
1697 case Instruction::IntToPtr:
1698 case Instruction::BitCast:
1699 case Instruction::AddrSpaceCast:
1700 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1701 case Instruction::InsertElement:
1702 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1703 OnlyIfReducedTy);
1704 case Instruction::ExtractElement:
1705 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1706 case Instruction::ShuffleVector:
1708 OnlyIfReducedTy);
1709 case Instruction::GetElementPtr: {
1710 auto *GEPO = cast<GEPOperator>(this);
1711 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1713 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1714 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1715 }
1716 default:
1717 assert(getNumOperands() == 2 && "Must be binary operator?");
1719 OnlyIfReducedTy);
1720 }
1721}
1722
1723
1724//===----------------------------------------------------------------------===//
1725// isValueValidForType implementations
1726
1728 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1729 if (Ty->isIntegerTy(1))
1730 return Val == 0 || Val == 1;
1731 return isUIntN(NumBits, Val);
1732}
1733
1735 unsigned NumBits = Ty->getIntegerBitWidth();
1736 if (Ty->isIntegerTy(1))
1737 return Val == 0 || Val == 1 || Val == -1;
1738 return isIntN(NumBits, Val);
1739}
1740
1742 // convert modifies in place, so make a copy.
1743 APFloat Val2 = APFloat(Val);
1744 bool losesInfo;
1745 switch (Ty->getTypeID()) {
1746 default:
1747 return false; // These can't be represented as floating point!
1748
1749 // FIXME rounding mode needs to be more flexible
1750 case Type::HalfTyID: {
1751 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1752 return true;
1754 return !losesInfo;
1755 }
1756 case Type::BFloatTyID: {
1757 if (&Val2.getSemantics() == &APFloat::BFloat())
1758 return true;
1760 return !losesInfo;
1761 }
1762 case Type::FloatTyID: {
1763 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1764 return true;
1766 return !losesInfo;
1767 }
1768 case Type::DoubleTyID: {
1769 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1770 &Val2.getSemantics() == &APFloat::BFloat() ||
1771 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1772 &Val2.getSemantics() == &APFloat::IEEEdouble())
1773 return true;
1775 return !losesInfo;
1776 }
1777 case Type::X86_FP80TyID:
1778 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1779 &Val2.getSemantics() == &APFloat::BFloat() ||
1780 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1781 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1783 case Type::FP128TyID:
1784 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1785 &Val2.getSemantics() == &APFloat::BFloat() ||
1786 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1787 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1788 &Val2.getSemantics() == &APFloat::IEEEquad();
1790 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1791 &Val2.getSemantics() == &APFloat::BFloat() ||
1792 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1793 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1795 }
1796}
1797
1798
1799//===----------------------------------------------------------------------===//
1800// Factory Function Implementation
1801
1802ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1803 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1804 "Cannot create an aggregate zero of non-aggregate type!");
1805
1806 std::unique_ptr<ConstantAggregateZero> &Entry =
1807 Ty->getContext().pImpl->CAZConstants[Ty];
1808 if (!Entry)
1809 Entry.reset(new ConstantAggregateZero(Ty));
1810
1811 return Entry.get();
1812}
1813
1814/// Remove the constant from the constant table.
1815void ConstantAggregateZero::destroyConstantImpl() {
1817}
1818
1819/// Remove the constant from the constant table.
1820void ConstantArray::destroyConstantImpl() {
1822}
1823
1824
1825//---- ConstantStruct::get() implementation...
1826//
1827
1828/// Remove the constant from the constant table.
1829void ConstantStruct::destroyConstantImpl() {
1831}
1832
1833/// Remove the constant from the constant table.
1834void ConstantVector::destroyConstantImpl() {
1836}
1837
1838Constant *Constant::getSplatValue(bool AllowPoison) const {
1839 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1840 if (isa<PoisonValue>(this))
1841 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1843 return getNullValue(cast<VectorType>(getType())->getElementType());
1844 if (auto *CI = dyn_cast<ConstantInt>(this))
1845 return ConstantInt::get(getContext(), CI->getValue());
1846 if (auto *CB = dyn_cast<ConstantByte>(this))
1847 return ConstantByte::get(getContext(), CB->getValue());
1848 if (auto *CFP = dyn_cast<ConstantFP>(this))
1849 return ConstantFP::get(getContext(), CFP->getValue());
1850 if (auto *CPN = dyn_cast<ConstantPointerNull>(this))
1851 return ConstantPointerNull::get(CPN->getPointerType());
1853 return CV->getSplatValue();
1854 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1855 return CV->getSplatValue(AllowPoison);
1856
1857 // Check if this is a constant expression splat of the form returned by
1858 // ConstantVector::getSplat()
1859 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1860 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1861 isa<UndefValue>(Shuf->getOperand(1))) {
1862
1863 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1864 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1865 isa<UndefValue>(IElt->getOperand(0))) {
1866
1867 ArrayRef<int> Mask = Shuf->getShuffleMask();
1868 Constant *SplatVal = IElt->getOperand(1);
1869 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1870
1871 if (Index && Index->getValue() == 0 && llvm::all_of(Mask, equal_to(0)))
1872 return SplatVal;
1873 }
1874 }
1875
1876 return nullptr;
1877}
1878
1879Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1880 // Check out first element.
1881 Constant *Elt = getOperand(0);
1882 // Then make sure all remaining elements point to the same value.
1883 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1884 Constant *OpC = getOperand(I);
1885 if (OpC == Elt)
1886 continue;
1887
1888 // Strict mode: any mismatch is not a splat.
1889 if (!AllowPoison)
1890 return nullptr;
1891
1892 // Allow poison mode: ignore poison elements.
1893 if (isa<PoisonValue>(OpC))
1894 continue;
1895
1896 // If we do not have a defined element yet, use the current operand.
1897 if (isa<PoisonValue>(Elt))
1898 Elt = OpC;
1899
1900 if (OpC != Elt)
1901 return nullptr;
1902 }
1903 return Elt;
1904}
1905
1907 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1908 return CI->getValue();
1909 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
1910 return CB->getValue();
1911 // Scalable vectors can use a ConstantExpr to build a splat.
1912 if (isa<ConstantExpr>(this))
1913 return cast<ConstantInt>(this->getSplatValue())->getValue();
1914 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1915 // calling getSplatValue in release builds.
1916 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1917 const Constant *C = this->getAggregateElement(0U);
1918 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1919 return cast<ConstantInt>(C)->getValue();
1920}
1921
1923 if (auto *CI = dyn_cast<ConstantInt>(this))
1924 return ConstantRange(CI->getValue());
1925
1926 unsigned BitWidth = getType()->getScalarSizeInBits();
1927 if (!getType()->isVectorTy())
1928 return ConstantRange::getFull(BitWidth);
1929
1930 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1931 getSplatValue(/*AllowPoison=*/true)))
1932 return ConstantRange(CI->getValue());
1933
1934 if (auto *CB =
1935 dyn_cast_or_null<ConstantByte>(getSplatValue(/*AllowPoison=*/true)))
1936 return ConstantRange(CB->getValue());
1937
1938 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1939 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1940 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1941 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1942 return CR;
1943 }
1944
1945 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1946 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1947 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1948 Constant *Elem = CV->getOperand(I);
1949 if (!Elem)
1950 return ConstantRange::getFull(BitWidth);
1951 if (isa<PoisonValue>(Elem))
1952 continue;
1953 auto *CI = dyn_cast<ConstantInt>(Elem);
1954 auto *CB = dyn_cast<ConstantByte>(Elem);
1955 if (!CI && !CB)
1956 return ConstantRange::getFull(BitWidth);
1957 CR = CR.unionWith(CI ? CI->getValue() : CB->getValue());
1958 }
1959 return CR;
1960 }
1961
1962 return ConstantRange::getFull(BitWidth);
1963}
1964
1965//---- ConstantPointerNull::get() implementation.
1966//
1967
1968ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1969 return get(static_cast<Type *>(Ty));
1970}
1971
1972ConstantPointerNull *ConstantPointerNull::get(Type *Ty) {
1973 assert(Ty->isPtrOrPtrVectorTy() && "invalid type for null pointer constant");
1974 std::unique_ptr<ConstantPointerNull> &Entry =
1975 Ty->getContext().pImpl->CPNConstants[Ty];
1976 if (!Entry)
1977 Entry.reset(new ConstantPointerNull(Ty));
1978
1979 assert(Entry->getType() == Ty);
1980 return Entry.get();
1981}
1982
1983/// Remove the constant from the constant table.
1984void ConstantPointerNull::destroyConstantImpl() {
1986}
1987
1988//---- ConstantTargetNone::get() implementation.
1989//
1990
1991ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
1992 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
1993 "Target extension type not allowed to have a zeroinitializer");
1994 std::unique_ptr<ConstantTargetNone> &Entry =
1995 Ty->getContext().pImpl->CTNConstants[Ty];
1996 if (!Entry)
1997 Entry.reset(new ConstantTargetNone(Ty));
1998
1999 return Entry.get();
2000}
2001
2002/// Remove the constant from the constant table.
2003void ConstantTargetNone::destroyConstantImpl() {
2005}
2006
2007UndefValue *UndefValue::get(Type *Ty) {
2008 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
2009 if (!Entry)
2010 Entry.reset(new UndefValue(Ty));
2011
2012 return Entry.get();
2013}
2014
2015/// Remove the constant from the constant table.
2016void UndefValue::destroyConstantImpl() {
2017 // Free the constant and any dangling references to it.
2018 if (getValueID() == UndefValueVal) {
2019 getContext().pImpl->UVConstants.erase(getType());
2020 } else if (getValueID() == PoisonValueVal) {
2021 getContext().pImpl->PVConstants.erase(getType());
2022 }
2023 llvm_unreachable("Not a undef or a poison!");
2024}
2025
2026PoisonValue *PoisonValue::get(Type *Ty) {
2027 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
2028 if (!Entry)
2029 Entry.reset(new PoisonValue(Ty));
2030
2031 return Entry.get();
2032}
2033
2034/// Remove the constant from the constant table.
2035void PoisonValue::destroyConstantImpl() {
2036 // Free the constant and any dangling references to it.
2037 getContext().pImpl->PVConstants.erase(getType());
2038}
2039
2040BlockAddress *BlockAddress::get(Type *Ty, BasicBlock *BB) {
2041 BlockAddress *&BA = BB->getContext().pImpl->BlockAddresses[BB];
2042 if (!BA)
2043 BA = new BlockAddress(Ty, BB);
2044 return BA;
2045}
2046
2047BlockAddress *BlockAddress::get(BasicBlock *BB) {
2048 assert(BB->getParent() && "Block must have a parent");
2049 return get(BB->getParent()->getType(), BB);
2050}
2051
2053 assert(BB->getParent() == F && "Block not part of specified function");
2054 return get(BB->getParent()->getType(), BB);
2055}
2056
2057BlockAddress::BlockAddress(Type *Ty, BasicBlock *BB)
2058 : Constant(Ty, Value::BlockAddressVal, AllocMarker) {
2059 Block = BB;
2060 BB->setHasAddressTaken(true);
2061}
2062
2063BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
2064 if (!BB->hasAddressTaken())
2065 return nullptr;
2066
2067 BlockAddress *BA = BB->getContext().pImpl->BlockAddresses.lookup(BB);
2068 assert(BA && "Refcount and block address map disagree!");
2069 return BA;
2070}
2071
2072/// Remove the constant from the constant table.
2073void BlockAddress::destroyConstantImpl() {
2075 getBasicBlock()->setHasAddressTaken(false);
2076}
2077
2078Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
2079 assert(From == getBasicBlock());
2080 BasicBlock *NewBB = cast<BasicBlock>(To);
2081
2082 // See if the 'new' entry already exists, if not, just update this in place
2083 // and return early.
2084 if (BlockAddress *NewBA = getContext().pImpl->BlockAddresses.lookup(NewBB))
2085 return NewBA;
2086
2087 getBasicBlock()->setHasAddressTaken(false);
2088
2089 // erase invalidates iterators/references, hence the duplicate NewBB lookup.
2091 getContext().pImpl->BlockAddresses[NewBB] = this;
2092 Block = NewBB;
2093 getBasicBlock()->setHasAddressTaken(true);
2094
2095 // If we just want to keep the existing value, then return null.
2096 // Callers know that this means we shouldn't delete this value.
2097 return nullptr;
2098}
2099
2100DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
2101 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
2102 if (!Equiv)
2103 Equiv = new DSOLocalEquivalent(GV);
2104
2105 assert(Equiv->getGlobalValue() == GV &&
2106 "DSOLocalFunction does not match the expected global value");
2107 return Equiv;
2108}
2109
2110DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
2111 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
2112 setOperand(0, GV);
2113}
2114
2115/// Remove the constant from the constant table.
2116void DSOLocalEquivalent::destroyConstantImpl() {
2117 const GlobalValue *GV = getGlobalValue();
2118 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
2119}
2120
2121Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
2122 assert(From == getGlobalValue() && "Changing value does not match operand.");
2123 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
2124
2125 // The replacement is with another global value.
2126 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
2127 if (DSOLocalEquivalent *NewEquiv =
2128 getContext().pImpl->DSOLocalEquivalents.lookup(ToObj))
2129 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2130 }
2131
2132 // If the argument is replaced with a null value, just replace this constant
2133 // with a null value.
2135 return To;
2136
2137 // The replacement could be a bitcast or an alias to another function. We can
2138 // replace it with a bitcast to the dso_local_equivalent of that function.
2140 if (DSOLocalEquivalent *NewEquiv =
2141 getContext().pImpl->DSOLocalEquivalents.lookup(Func))
2142 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2143
2144 // erase invalidates iterators/references, hence the duplicate Func lookup.
2147 setOperand(0, Func);
2148
2149 if (Func->getType() != getType()) {
2150 // It is ok to mutate the type here because this constant should always
2151 // reflect the type of the function it's holding.
2152 mutateType(Func->getType());
2153 }
2154 return nullptr;
2155}
2156
2158 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2159 if (!NC)
2160 NC = new NoCFIValue(GV);
2161
2162 assert(NC->getGlobalValue() == GV &&
2163 "NoCFIValue does not match the expected global value");
2164 return NC;
2165}
2166
2167NoCFIValue::NoCFIValue(GlobalValue *GV)
2168 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2169 setOperand(0, GV);
2170}
2171
2172/// Remove the constant from the constant table.
2173void NoCFIValue::destroyConstantImpl() {
2174 const GlobalValue *GV = getGlobalValue();
2175 GV->getContext().pImpl->NoCFIValues.erase(GV);
2176}
2177
2178Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2179 assert(From == getGlobalValue() && "Changing value does not match operand.");
2180
2181 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2182 assert(GV && "Can only replace the operands with a global value");
2183
2184 if (NoCFIValue *NewNC = getContext().pImpl->NoCFIValues.lookup(GV))
2185 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2186
2187 // erase invalidates iterators/references, hence the duplicate GV lookup.
2189 getContext().pImpl->NoCFIValues[GV] = this;
2190 setOperand(0, GV);
2191
2192 if (GV->getType() != getType())
2193 mutateType(GV->getType());
2194
2195 return nullptr;
2196}
2197
2198//---- ConstantPtrAuth::get() implementations.
2199//
2200
2202 ConstantInt *Disc, Constant *AddrDisc,
2203 Constant *DeactivationSymbol) {
2204 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc, DeactivationSymbol};
2205 ConstantPtrAuthKeyType MapKey(ArgVec);
2206 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2207 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2208}
2209
2210ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2211 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator(),
2213}
2214
2215ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2216 ConstantInt *Disc, Constant *AddrDisc,
2217 Constant *DeactivationSymbol)
2218 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2219 assert(Ptr->getType()->isPointerTy());
2220 assert(Key->getBitWidth() == 32);
2221 assert(Disc->getBitWidth() == 64);
2222 assert(AddrDisc->getType()->isPointerTy());
2223 assert(DeactivationSymbol->getType()->isPointerTy());
2224 setOperand(0, Ptr);
2225 setOperand(1, Key);
2226 setOperand(2, Disc);
2227 setOperand(3, AddrDisc);
2228 setOperand(4, DeactivationSymbol);
2229}
2230
2231/// Remove the constant from the constant table.
2232void ConstantPtrAuth::destroyConstantImpl() {
2233 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2234}
2235
2236Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2237 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2238 Constant *To = cast<Constant>(ToV);
2239
2240 SmallVector<Constant *, 4> Values;
2241 Values.reserve(getNumOperands());
2242
2243 unsigned NumUpdated = 0;
2244
2245 Use *OperandList = getOperandList();
2246 unsigned OperandNo = 0;
2247 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2248 Constant *Val = cast<Constant>(O->get());
2249 if (Val == From) {
2250 OperandNo = (O - OperandList);
2251 Val = To;
2252 ++NumUpdated;
2253 }
2254 Values.push_back(Val);
2255 }
2256
2257 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2258 Values, this, From, To, NumUpdated, OperandNo);
2259}
2260
2262 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2263 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2264 return false;
2265
2266 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2267 if (!IntVal)
2268 return false;
2269
2270 return IntVal->getValue() == Value;
2271}
2272
2274 const Value *Discriminator,
2275 const DataLayout &DL) const {
2276 // This function may only be validly called to analyze a ptrauth operation
2277 // with no deactivation symbol, so if we have one it isn't compatible.
2279 return false;
2280
2281 // If the keys are different, there's no chance for this to be compatible.
2282 if (getKey() != Key)
2283 return false;
2284
2285 // We can have 3 kinds of discriminators:
2286 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2287 // - address-only: `i64 0, ptr p` vs. `ptr p`
2288 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2289
2290 // If this constant has a simple discriminator (integer, no address), easy:
2291 // it's compatible iff the provided full discriminator is also a simple
2292 // discriminator, identical to our integer discriminator.
2294 return getDiscriminator() == Discriminator;
2295
2296 // Otherwise, we can isolate address and integer discriminator components.
2297 const Value *AddrDiscriminator = nullptr;
2298
2299 // This constant may or may not have an integer discriminator (instead of 0).
2300 if (!getDiscriminator()->isNullValue()) {
2301 // If it does, there's an implicit blend. We need to have a matching blend
2302 // intrinsic in the provided full discriminator.
2303 if (!match(Discriminator,
2305 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2306 return false;
2307 } else {
2308 // Otherwise, interpret the provided full discriminator as address-only.
2309 AddrDiscriminator = Discriminator;
2310 }
2311
2312 // Either way, we can now focus on comparing the address discriminators.
2313
2314 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2315 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2316 AddrDiscriminator = Cast->getPointerOperand();
2317
2318 // Beyond that, we're only interested in compatible pointers.
2319 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2320 return false;
2321
2322 // These are often the same constant GEP, making them trivially equivalent.
2323 if (getAddrDiscriminator() == AddrDiscriminator)
2324 return true;
2325
2326 // Finally, they may be equivalent base+offset expressions.
2327 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2329 DL, Off1, /*AllowNonInbounds=*/true);
2330
2331 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2332 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2333 DL, Off2, /*AllowNonInbounds=*/true);
2334
2335 return Base1 == Base2 && Off1 == Off2;
2336}
2337
2338//---- ConstantExpr::get() implementations.
2339//
2340
2341/// This is a utility function to handle folding of casts and lookup of the
2342/// cast in the ExprConstants map. It is used by the various get* methods below.
2344 bool OnlyIfReduced = false) {
2345 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2346 // Fold a few common cases
2347 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2348 return FC;
2349
2350 if (OnlyIfReduced)
2351 return nullptr;
2352
2353 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2354
2355 // Look up the constant in the table first to ensure uniqueness.
2357
2358 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2359}
2360
2362 bool OnlyIfReduced) {
2364 assert(Instruction::isCast(opc) && "opcode out of range");
2366 "Cast opcode not supported as constant expression");
2367 assert(C && Ty && "Null arguments to getCast");
2368 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2369
2370 switch (opc) {
2371 default:
2372 llvm_unreachable("Invalid cast opcode");
2373 case Instruction::Trunc:
2374 return getTrunc(C, Ty, OnlyIfReduced);
2375 case Instruction::PtrToAddr:
2376 return getPtrToAddr(C, Ty, OnlyIfReduced);
2377 case Instruction::PtrToInt:
2378 return getPtrToInt(C, Ty, OnlyIfReduced);
2379 case Instruction::IntToPtr:
2380 return getIntToPtr(C, Ty, OnlyIfReduced);
2381 case Instruction::BitCast:
2382 return getBitCast(C, Ty, OnlyIfReduced);
2383 case Instruction::AddrSpaceCast:
2384 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2385 }
2386}
2387
2389 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2390 return getBitCast(C, Ty);
2391 return getTrunc(C, Ty);
2392}
2393
2395 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2396 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2397 "Invalid cast");
2398
2399 if (Ty->isIntOrIntVectorTy())
2400 return getPtrToInt(S, Ty);
2401
2402 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2403 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2404 return getAddrSpaceCast(S, Ty);
2405
2406 return getBitCast(S, Ty);
2407}
2408
2410 Type *Ty) {
2411 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2412 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2413
2414 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2415 return getAddrSpaceCast(S, Ty);
2416
2417 return getBitCast(S, Ty);
2418}
2419
2420Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2421#ifndef NDEBUG
2422 bool fromVec = isa<VectorType>(C->getType());
2423 bool toVec = isa<VectorType>(Ty);
2424#endif
2425 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2426 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2427 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2428 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2429 "SrcTy must be larger than DestTy for Trunc!");
2430
2431 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2432}
2433
2435 bool OnlyIfReduced) {
2436 assert(C->getType()->isPtrOrPtrVectorTy() &&
2437 "PtrToAddr source must be pointer or pointer vector");
2438 assert(DstTy->isIntOrIntVectorTy() &&
2439 "PtrToAddr destination must be integer or integer vector");
2440 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2441 if (isa<VectorType>(C->getType()))
2442 assert(cast<VectorType>(C->getType())->getElementCount() ==
2443 cast<VectorType>(DstTy)->getElementCount() &&
2444 "Invalid cast between a different number of vector elements");
2445 return getFoldedCast(Instruction::PtrToAddr, C, DstTy, OnlyIfReduced);
2446}
2447
2449 bool OnlyIfReduced) {
2450 assert(C->getType()->isPtrOrPtrVectorTy() &&
2451 "PtrToInt source must be pointer or pointer vector");
2452 assert(DstTy->isIntOrIntVectorTy() &&
2453 "PtrToInt destination must be integer or integer vector");
2454 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2455 if (isa<VectorType>(C->getType()))
2456 assert(cast<VectorType>(C->getType())->getElementCount() ==
2457 cast<VectorType>(DstTy)->getElementCount() &&
2458 "Invalid cast between a different number of vector elements");
2459 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2460}
2461
2463 bool OnlyIfReduced) {
2464 assert(C->getType()->isIntOrIntVectorTy() &&
2465 "IntToPtr source must be integer or integer vector");
2466 assert(DstTy->isPtrOrPtrVectorTy() &&
2467 "IntToPtr destination must be a pointer or pointer vector");
2468 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2469 if (isa<VectorType>(C->getType()))
2470 assert(cast<VectorType>(C->getType())->getElementCount() ==
2471 cast<VectorType>(DstTy)->getElementCount() &&
2472 "Invalid cast between a different number of vector elements");
2473 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2474}
2475
2477 bool OnlyIfReduced) {
2478 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2479 "Invalid constantexpr bitcast!");
2480
2481 // It is common to ask for a bitcast of a value to its own type, handle this
2482 // speedily.
2483 if (C->getType() == DstTy) return C;
2484
2485 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2486}
2487
2489 bool OnlyIfReduced) {
2490 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2491 "Invalid constantexpr addrspacecast!");
2492 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2493}
2494
2495Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2496 unsigned Flags, Type *OnlyIfReducedTy) {
2497 // Check the operands for consistency first.
2499 "Invalid opcode in binary constant expression");
2500 assert(isSupportedBinOp(Opcode) &&
2501 "Binop not supported as constant expression");
2502 assert(C1->getType() == C2->getType() &&
2503 "Operand types in binary constant expression should match");
2504
2505#ifndef NDEBUG
2506 switch (Opcode) {
2507 case Instruction::Add:
2508 case Instruction::Sub:
2509 case Instruction::Mul:
2511 "Tried to create an integer operation on a non-integer type!");
2512 break;
2513 case Instruction::And:
2514 case Instruction::Or:
2515 case Instruction::Xor:
2517 "Tried to create a logical operation on a non-integral type!");
2518 break;
2519 default:
2520 break;
2521 }
2522#endif
2523
2524 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2525 return FC;
2526
2527 if (OnlyIfReducedTy == C1->getType())
2528 return nullptr;
2529
2530 Constant *ArgVec[] = {C1, C2};
2531 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2532
2533 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2534 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2535}
2536
2537bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2538 switch (Opcode) {
2539 case Instruction::UDiv:
2540 case Instruction::SDiv:
2541 case Instruction::URem:
2542 case Instruction::SRem:
2543 case Instruction::FAdd:
2544 case Instruction::FSub:
2545 case Instruction::FMul:
2546 case Instruction::FDiv:
2547 case Instruction::FRem:
2548 case Instruction::And:
2549 case Instruction::Or:
2550 case Instruction::LShr:
2551 case Instruction::AShr:
2552 case Instruction::Shl:
2553 case Instruction::Mul:
2554 return false;
2555 case Instruction::Add:
2556 case Instruction::Sub:
2557 case Instruction::Xor:
2558 return true;
2559 default:
2560 llvm_unreachable("Argument must be binop opcode");
2561 }
2562}
2563
2564bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2565 switch (Opcode) {
2566 case Instruction::UDiv:
2567 case Instruction::SDiv:
2568 case Instruction::URem:
2569 case Instruction::SRem:
2570 case Instruction::FAdd:
2571 case Instruction::FSub:
2572 case Instruction::FMul:
2573 case Instruction::FDiv:
2574 case Instruction::FRem:
2575 case Instruction::And:
2576 case Instruction::Or:
2577 case Instruction::LShr:
2578 case Instruction::AShr:
2579 case Instruction::Shl:
2580 case Instruction::Mul:
2581 return false;
2582 case Instruction::Add:
2583 case Instruction::Sub:
2584 case Instruction::Xor:
2585 return true;
2586 default:
2587 llvm_unreachable("Argument must be binop opcode");
2588 }
2589}
2590
2591bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2592 switch (Opcode) {
2593 case Instruction::ZExt:
2594 case Instruction::SExt:
2595 case Instruction::FPTrunc:
2596 case Instruction::FPExt:
2597 case Instruction::UIToFP:
2598 case Instruction::SIToFP:
2599 case Instruction::FPToUI:
2600 case Instruction::FPToSI:
2601 return false;
2602 case Instruction::Trunc:
2603 case Instruction::PtrToAddr:
2604 case Instruction::PtrToInt:
2605 case Instruction::IntToPtr:
2606 case Instruction::BitCast:
2607 case Instruction::AddrSpaceCast:
2608 return true;
2609 default:
2610 llvm_unreachable("Argument must be cast opcode");
2611 }
2612}
2613
2614bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2615 switch (Opcode) {
2616 case Instruction::ZExt:
2617 case Instruction::SExt:
2618 case Instruction::FPTrunc:
2619 case Instruction::FPExt:
2620 case Instruction::UIToFP:
2621 case Instruction::SIToFP:
2622 case Instruction::FPToUI:
2623 case Instruction::FPToSI:
2624 return false;
2625 case Instruction::Trunc:
2626 case Instruction::PtrToAddr:
2627 case Instruction::PtrToInt:
2628 case Instruction::IntToPtr:
2629 case Instruction::BitCast:
2630 case Instruction::AddrSpaceCast:
2631 return true;
2632 default:
2633 llvm_unreachable("Argument must be cast opcode");
2634 }
2635}
2636
2638 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2639 // Note that a non-inbounds gep is used, as null isn't within any object.
2640 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2642 Ty, Constant::getNullValue(PointerType::getUnqual(Ty->getContext())),
2643 GEPIdx);
2644 return getPtrToInt(GEP,
2645 Type::getInt64Ty(Ty->getContext()));
2646}
2647
2649 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2650 // Note that a non-inbounds gep is used, as null isn't within any object.
2651 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2652 Constant *NullPtr =
2654 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2655 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2656 Constant *Indices[2] = {Zero, One};
2657 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2658 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2659}
2660
2662 ArrayRef<Value *> Idxs,
2663 GEPNoWrapFlags NW,
2664 std::optional<ConstantRange> InRange,
2665 Type *OnlyIfReducedTy) {
2666 assert(Ty && "Must specify element type");
2667 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2668
2669 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2670 return FC; // Fold a few common cases.
2671
2672 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2673 ;
2674
2675 // Get the result type of the getelementptr!
2677 if (OnlyIfReducedTy == ReqTy)
2678 return nullptr;
2679
2680 auto EltCount = ElementCount::getFixed(0);
2681 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2682 EltCount = VecTy->getElementCount();
2683
2684 // Look up the constant in the table first to ensure uniqueness
2685 std::vector<Constant*> ArgVec;
2686 ArgVec.reserve(1 + Idxs.size());
2687 ArgVec.push_back(C);
2688 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2689 for (; GTI != GTE; ++GTI) {
2690 auto *Idx = cast<Constant>(GTI.getOperand());
2691 assert(
2692 (!isa<VectorType>(Idx->getType()) ||
2693 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2694 "getelementptr index type missmatch");
2695
2696 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2697 Idx = Idx->getSplatValue();
2698 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2699 !Idx->getType()->isVectorTy()) {
2700 Idx = ConstantVector::getSplat(EltCount, Idx);
2701 }
2702 ArgVec.push_back(Idx);
2703 }
2704
2705 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2706 {}, Ty, InRange);
2707
2708 LLVMContextImpl *pImpl = C->getContext().pImpl;
2709 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2710}
2711
2713 Type *OnlyIfReducedTy) {
2714 assert(Val->getType()->isVectorTy() &&
2715 "Tried to create extractelement operation on non-vector type!");
2716 assert(Idx->getType()->isIntegerTy() &&
2717 "Extractelement index must be an integer type!");
2718
2720 return FC; // Fold a few common cases.
2721
2722 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2723 if (OnlyIfReducedTy == ReqTy)
2724 return nullptr;
2725
2726 // Look up the constant in the table first to ensure uniqueness
2727 Constant *ArgVec[] = { Val, Idx };
2728 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2729
2730 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2731 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2732}
2733
2735 Constant *Idx, Type *OnlyIfReducedTy) {
2736 assert(Val->getType()->isVectorTy() &&
2737 "Tried to create insertelement operation on non-vector type!");
2738 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2739 "Insertelement types must match!");
2740 assert(Idx->getType()->isIntegerTy() &&
2741 "Insertelement index must be i32 type!");
2742
2743 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2744 return FC; // Fold a few common cases.
2745
2746 if (OnlyIfReducedTy == Val->getType())
2747 return nullptr;
2748
2749 // Look up the constant in the table first to ensure uniqueness
2750 Constant *ArgVec[] = { Val, Elt, Idx };
2751 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2752
2753 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2754 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2755}
2756
2758 ArrayRef<int> Mask,
2759 Type *OnlyIfReducedTy) {
2761 "Invalid shuffle vector constant expr operands!");
2762
2763 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2764 return FC; // Fold a few common cases.
2765
2766 unsigned NElts = Mask.size();
2767 auto V1VTy = cast<VectorType>(V1->getType());
2768 Type *EltTy = V1VTy->getElementType();
2769 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2770 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2771
2772 if (OnlyIfReducedTy == ShufTy)
2773 return nullptr;
2774
2775 // Look up the constant in the table first to ensure uniqueness
2776 Constant *ArgVec[] = {V1, V2};
2777 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2778
2779 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2780 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2781}
2782
2784 assert(C->getType()->isIntOrIntVectorTy() &&
2785 "Cannot NEG a nonintegral value!");
2786 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2787}
2788
2790 assert(C->getType()->isIntOrIntVectorTy() &&
2791 "Cannot NOT a nonintegral value!");
2792 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2793}
2794
2796 bool HasNUW, bool HasNSW) {
2797 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2799 return get(Instruction::Add, C1, C2, Flags);
2800}
2801
2803 bool HasNUW, bool HasNSW) {
2804 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2806 return get(Instruction::Sub, C1, C2, Flags);
2807}
2808
2810 return get(Instruction::Xor, C1, C2);
2811}
2812
2814 Type *Ty = C->getType();
2815 const APInt *IVal;
2816 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2817 return ConstantInt::get(Ty, IVal->logBase2());
2818
2819 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2820 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2821 if (!VecTy)
2822 return nullptr;
2823
2825 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2826 Constant *Elt = C->getAggregateElement(I);
2827 if (!Elt)
2828 return nullptr;
2829 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2830 if (isa<UndefValue>(Elt)) {
2831 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2832 continue;
2833 }
2834 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2835 return nullptr;
2836 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2837 }
2838
2839 return ConstantVector::get(Elts);
2840}
2841
2843 bool AllowRHSConstant, bool NSZ) {
2844 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2845
2846 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2847 if (Instruction::isCommutative(Opcode)) {
2848 switch (Opcode) {
2849 case Instruction::Add: // X + 0 = X
2850 case Instruction::Or: // X | 0 = X
2851 case Instruction::Xor: // X ^ 0 = X
2852 return Constant::getNullValue(Ty);
2853 case Instruction::Mul: // X * 1 = X
2854 return ConstantInt::get(Ty, 1);
2855 case Instruction::And: // X & -1 = X
2856 return Constant::getAllOnesValue(Ty);
2857 case Instruction::FAdd: // X + -0.0 = X
2858 return ConstantFP::getZero(Ty, !NSZ);
2859 case Instruction::FMul: // X * 1.0 = X
2860 return ConstantFP::get(Ty, 1.0);
2861 default:
2862 llvm_unreachable("Every commutative binop has an identity constant");
2863 }
2864 }
2865
2866 // Non-commutative opcodes: AllowRHSConstant must be set.
2867 if (!AllowRHSConstant)
2868 return nullptr;
2869
2870 switch (Opcode) {
2871 case Instruction::Sub: // X - 0 = X
2872 case Instruction::Shl: // X << 0 = X
2873 case Instruction::LShr: // X >>u 0 = X
2874 case Instruction::AShr: // X >> 0 = X
2875 case Instruction::FSub: // X - 0.0 = X
2876 return Constant::getNullValue(Ty);
2877 case Instruction::SDiv: // X / 1 = X
2878 case Instruction::UDiv: // X /u 1 = X
2879 return ConstantInt::get(Ty, 1);
2880 case Instruction::FDiv: // X / 1.0 = X
2881 return ConstantFP::get(Ty, 1.0);
2882 default:
2883 return nullptr;
2884 }
2885}
2886
2888 switch (ID) {
2889 case Intrinsic::umax:
2890 return Constant::getNullValue(Ty);
2891 case Intrinsic::umin:
2892 return Constant::getAllOnesValue(Ty);
2893 case Intrinsic::smax:
2895 Ty, APInt::getSignedMinValue(Ty->getIntegerBitWidth()));
2896 case Intrinsic::smin:
2898 Ty, APInt::getSignedMaxValue(Ty->getIntegerBitWidth()));
2899 default:
2900 return nullptr;
2901 }
2902}
2903
2905 bool AllowRHSConstant, bool NSZ) {
2906 if (I->isBinaryOp())
2907 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2909 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2910 return nullptr;
2911}
2912
2914 bool AllowLHSConstant) {
2915 switch (Opcode) {
2916 default:
2917 break;
2918
2919 case Instruction::Or: // -1 | X = -1
2920 return Constant::getAllOnesValue(Ty);
2921
2922 case Instruction::And: // 0 & X = 0
2923 case Instruction::Mul: // 0 * X = 0
2924 return Constant::getNullValue(Ty);
2925 }
2926
2927 // AllowLHSConstant must be set.
2928 if (!AllowLHSConstant)
2929 return nullptr;
2930
2931 switch (Opcode) {
2932 default:
2933 return nullptr;
2934 case Instruction::Shl: // 0 << X = 0
2935 case Instruction::LShr: // 0 >>l X = 0
2936 case Instruction::AShr: // 0 >>a X = 0
2937 case Instruction::SDiv: // 0 /s X = 0
2938 case Instruction::UDiv: // 0 /u X = 0
2939 case Instruction::URem: // 0 %u X = 0
2940 case Instruction::SRem: // 0 %s X = 0
2941 return Constant::getNullValue(Ty);
2942 }
2943}
2944
2945/// Remove the constant from the constant table.
2946void ConstantExpr::destroyConstantImpl() {
2947 getType()->getContext().pImpl->ExprConstants.remove(this);
2948}
2949
2950const char *ConstantExpr::getOpcodeName() const {
2952}
2953
2954GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2955 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
2956 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
2957 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
2958 SrcElementTy(SrcElementTy),
2959 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
2960 InRange(std::move(InRange)) {
2961 Op<0>() = C;
2962 Use *OperandList = getOperandList();
2963 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2964 OperandList[i+1] = IdxList[i];
2965}
2966
2968 return SrcElementTy;
2969}
2970
2972 return ResElementTy;
2973}
2974
2975std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
2976 return InRange;
2977}
2978
2979//===----------------------------------------------------------------------===//
2980// ConstantData* implementations
2981
2984 return ATy->getElementType();
2985 return cast<VectorType>(getType())->getElementType();
2986}
2987
2991
2993 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2994 return true;
2995 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2996 switch (IT->getBitWidth()) {
2997 case 8:
2998 case 16:
2999 case 32:
3000 case 64:
3001 return true;
3002 default: break;
3003 }
3004 }
3005 if (auto *IT = dyn_cast<ByteType>(Ty)) {
3006 switch (IT->getBitWidth()) {
3007 case 8:
3008 case 16:
3009 case 32:
3010 case 64:
3011 return true;
3012 default:
3013 break;
3014 }
3015 }
3016 return false;
3017}
3018
3021 return AT->getNumElements();
3022 return cast<FixedVectorType>(getType())->getNumElements();
3023}
3024
3028
3029/// Return the start of the specified element.
3030const char *ConstantDataSequential::getElementPointer(uint64_t Elt) const {
3031 assert(Elt < getNumElements() && "Invalid Elt");
3032 return DataElements + Elt * getElementByteSize();
3033}
3034
3035/// Return true if the array is empty or all zeros.
3036static bool isAllZeros(StringRef Arr) {
3037 for (char I : Arr)
3038 if (I != 0)
3039 return false;
3040 return true;
3041}
3042
3043/// This is the underlying implementation of all of the
3044/// ConstantDataSequential::get methods. They all thunk down to here, providing
3045/// the correct element type. We take the bytes in as a StringRef because
3046/// we *want* an underlying "char*" to avoid TBAA type punning violations.
3048#ifndef NDEBUG
3049 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
3050 assert(isElementTypeCompatible(ATy->getElementType()));
3051 else
3053#endif
3054 // If the elements are all zero or there are no elements, return a CAZ, which
3055 // is more dense and canonical.
3056 if (isAllZeros(Elements))
3057 return ConstantAggregateZero::get(Ty);
3058
3059 // Do a lookup to see if we have already formed one of these.
3060 auto &Slot =
3061 *Ty->getContext().pImpl->CDSConstants.try_emplace(Elements).first;
3062
3063 // The bucket can point to a linked list of different CDS's that have the same
3064 // body but different types. For example, 0,0,0,1 could be a 4 element array
3065 // of i8, or a 1-element array of i32. They'll both end up in the same
3066 /// StringMap bucket, linked up by their Next pointers. Walk the list.
3067 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
3068 for (; *Entry; Entry = &(*Entry)->Next)
3069 if ((*Entry)->getType() == Ty)
3070 return Entry->get();
3071
3072 // Okay, we didn't get a hit. Create a node of the right class, link it in,
3073 // and return it.
3074 if (isa<ArrayType>(Ty)) {
3075 // Use reset because std::make_unique can't access the constructor.
3076 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
3077 return Entry->get();
3078 }
3079
3081 // Use reset because std::make_unique can't access the constructor.
3082 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
3083 return Entry->get();
3084}
3085
3086void ConstantDataSequential::destroyConstantImpl() {
3087 // Remove the constant from the StringMap.
3090
3091 auto Slot = CDSConstants.find(getRawDataValues());
3092
3093 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
3094
3095 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
3096
3097 // Remove the entry from the hash table.
3098 if (!(*Entry)->Next) {
3099 // If there is only one value in the bucket (common case) it must be this
3100 // entry, and removing the entry should remove the bucket completely.
3101 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
3102 getContext().pImpl->CDSConstants.erase(Slot);
3103 return;
3104 }
3105
3106 // Otherwise, there are multiple entries linked off the bucket, unlink the
3107 // node we care about but keep the bucket around.
3108 while (true) {
3109 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
3110 assert(Node && "Didn't find entry in its uniquing hash table!");
3111 // If we found our entry, unlink it from the list and we're done.
3112 if (Node.get() == this) {
3113 Node = std::move(Node->Next);
3114 return;
3115 }
3116
3117 Entry = &Node->Next;
3118 }
3119}
3120
3121/// getFP() constructors - Return a constant of array type with a float
3122/// element type taken from argument `ElementType', and count taken from
3123/// argument `Elts'. The amount of bits of the contained type must match the
3124/// number of bits of the type contained in the passed in ArrayRef.
3125/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3126/// that this can return a ConstantAggregateZero object.
3128 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3129 "Element type is not a 16-bit float type");
3130 Type *Ty = ArrayType::get(ElementType, Elts.size());
3131 const char *Data = reinterpret_cast<const char *>(Elts.data());
3132 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3133}
3135 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3136 Type *Ty = ArrayType::get(ElementType, Elts.size());
3137 const char *Data = reinterpret_cast<const char *>(Elts.data());
3138 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3139}
3141 assert(ElementType->isDoubleTy() &&
3142 "Element type is not a 64-bit float type");
3143 Type *Ty = ArrayType::get(ElementType, Elts.size());
3144 const char *Data = reinterpret_cast<const char *>(Elts.data());
3145 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3146}
3147
3148/// getByte() constructors - Return a constant of array type with a byte
3149/// element type taken from argument `ElementType', and count taken from
3150/// argument `Elts'. The amount of bits of the contained type must match the
3151/// number of bits of the type contained in the passed in ArrayRef.
3152/// Note that this can return a ConstantAggregateZero object.
3154 ArrayRef<uint8_t> Elts) {
3155 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte type");
3156 Type *Ty = ArrayType::get(ElementType, Elts.size());
3157 const char *Data = reinterpret_cast<const char *>(Elts.data());
3158 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3159}
3161 ArrayRef<uint16_t> Elts) {
3162 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte type");
3163 Type *Ty = ArrayType::get(ElementType, Elts.size());
3164 const char *Data = reinterpret_cast<const char *>(Elts.data());
3165 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3166}
3168 ArrayRef<uint32_t> Elts) {
3169 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte type");
3170 Type *Ty = ArrayType::get(ElementType, Elts.size());
3171 const char *Data = reinterpret_cast<const char *>(Elts.data());
3172 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3173}
3175 ArrayRef<uint64_t> Elts) {
3176 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte type");
3177 Type *Ty = ArrayType::get(ElementType, Elts.size());
3178 const char *Data = reinterpret_cast<const char *>(Elts.data());
3179 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3180}
3181
3183 bool AddNull, bool ByteString) {
3184 if (!AddNull) {
3185 const uint8_t *Data = Str.bytes_begin();
3186 return ByteString
3187 ? getByte(Type::getByte8Ty(Context), ArrayRef(Data, Str.size()))
3188 : get(Context, ArrayRef(Data, Str.size()));
3189 }
3190
3191 SmallVector<uint8_t, 64> ElementVals;
3192 ElementVals.append(Str.begin(), Str.end());
3193 ElementVals.push_back(0);
3194 return ByteString ? getByte(Type::getByte8Ty(Context), ElementVals)
3195 : get(Context, ElementVals);
3196}
3197
3198/// get() constructors - Return a constant with vector type with an element
3199/// count and element type matching the ArrayRef passed in. Note that this
3200/// can return a ConstantAggregateZero object.
3202 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3203 const char *Data = reinterpret_cast<const char *>(Elts.data());
3204 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3205}
3207 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3208 const char *Data = reinterpret_cast<const char *>(Elts.data());
3209 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3210}
3212 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3213 const char *Data = reinterpret_cast<const char *>(Elts.data());
3214 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3215}
3217 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3218 const char *Data = reinterpret_cast<const char *>(Elts.data());
3219 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3220}
3222 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3223 const char *Data = reinterpret_cast<const char *>(Elts.data());
3224 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3225}
3227 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3228 const char *Data = reinterpret_cast<const char *>(Elts.data());
3229 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3230}
3231
3232/// getByte() constructors - Return a constant of vector type with a byte
3233/// element type taken from argument `ElementType', and count taken from
3234/// argument `Elts'. The amount of bits of the contained type must match the
3235/// number of bits of the type contained in the passed in ArrayRef.
3236/// Note that this can return a ConstantAggregateZero object.
3238 ArrayRef<uint8_t> Elts) {
3239 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte");
3240 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3241 const char *Data = reinterpret_cast<const char *>(Elts.data());
3242 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3243}
3245 ArrayRef<uint16_t> Elts) {
3246 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte");
3247 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3248 const char *Data = reinterpret_cast<const char *>(Elts.data());
3249 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3250}
3252 ArrayRef<uint32_t> Elts) {
3253 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte");
3254 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3255 const char *Data = reinterpret_cast<const char *>(Elts.data());
3256 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3257}
3259 ArrayRef<uint64_t> Elts) {
3260 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte");
3261 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3262 const char *Data = reinterpret_cast<const char *>(Elts.data());
3263 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3264}
3265
3266/// getFP() constructors - Return a constant of vector type with a float
3267/// element type taken from argument `ElementType', and count taken from
3268/// argument `Elts'. The amount of bits of the contained type must match the
3269/// number of bits of the type contained in the passed in ArrayRef.
3270/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3271/// that this can return a ConstantAggregateZero object.
3273 ArrayRef<uint16_t> Elts) {
3274 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3275 "Element type is not a 16-bit float type");
3276 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3277 const char *Data = reinterpret_cast<const char *>(Elts.data());
3278 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3279}
3281 ArrayRef<uint32_t> Elts) {
3282 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3283 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3284 const char *Data = reinterpret_cast<const char *>(Elts.data());
3285 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3286}
3288 ArrayRef<uint64_t> Elts) {
3289 assert(ElementType->isDoubleTy() &&
3290 "Element type is not a 64-bit float type");
3291 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3292 const char *Data = reinterpret_cast<const char *>(Elts.data());
3293 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3294}
3295
3297 assert(isElementTypeCompatible(V->getType()) &&
3298 "Element type not compatible with ConstantData");
3299 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3300 if (CI->getType()->isIntegerTy(8)) {
3301 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3302 return get(V->getContext(), Elts);
3303 }
3304 if (CI->getType()->isIntegerTy(16)) {
3305 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3306 return get(V->getContext(), Elts);
3307 }
3308 if (CI->getType()->isIntegerTy(32)) {
3309 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3310 return get(V->getContext(), Elts);
3311 }
3312 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3313 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3314 return get(V->getContext(), Elts);
3315 }
3316
3317 if (ConstantByte *CB = dyn_cast<ConstantByte>(V)) {
3318 if (CB->getType()->isByteTy(8)) {
3319 SmallVector<uint8_t, 16> Elts(NumElts, CB->getZExtValue());
3320 return getByte(V->getType(), Elts);
3321 }
3322 if (CB->getType()->isByteTy(16)) {
3323 SmallVector<uint16_t, 16> Elts(NumElts, CB->getZExtValue());
3324 return getByte(V->getType(), Elts);
3325 }
3326 if (CB->getType()->isByteTy(32)) {
3327 SmallVector<uint32_t, 16> Elts(NumElts, CB->getZExtValue());
3328 return getByte(V->getType(), Elts);
3329 }
3330 assert(CB->getType()->isByteTy(64) && "Unsupported ConstantData type");
3331 SmallVector<uint64_t, 16> Elts(NumElts, CB->getZExtValue());
3332 return getByte(V->getType(), Elts);
3333 }
3334
3335 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3336 if (CFP->getType()->isHalfTy()) {
3338 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3339 return getFP(V->getType(), Elts);
3340 }
3341 if (CFP->getType()->isBFloatTy()) {
3343 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3344 return getFP(V->getType(), Elts);
3345 }
3346 if (CFP->getType()->isFloatTy()) {
3348 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3349 return getFP(V->getType(), Elts);
3350 }
3351 if (CFP->getType()->isDoubleTy()) {
3353 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3354 return getFP(V->getType(), Elts);
3355 }
3356 }
3358}
3359
3361 assert(
3363 "Accessor can only be used when element is an integer or byte");
3364 const char *EltPtr = getElementPointer(Elt);
3365
3366 // The data is stored in host byte order, make sure to cast back to the right
3367 // type to load with the right endianness.
3368 switch (getElementType()->getScalarSizeInBits()) {
3369 default: llvm_unreachable("Invalid bitwidth for CDS");
3370 case 8:
3371 return *reinterpret_cast<const uint8_t *>(EltPtr);
3372 case 16:
3373 return *reinterpret_cast<const uint16_t *>(EltPtr);
3374 case 32:
3375 return *reinterpret_cast<const uint32_t *>(EltPtr);
3376 case 64:
3377 return *reinterpret_cast<const uint64_t *>(EltPtr);
3378 }
3379}
3380
3382 assert(
3384 "Accessor can only be used when element is an integer or byte");
3385 const char *EltPtr = getElementPointer(Elt);
3386
3387 // The data is stored in host byte order, make sure to cast back to the right
3388 // type to load with the right endianness.
3389 switch (getElementType()->getScalarSizeInBits()) {
3390 default: llvm_unreachable("Invalid bitwidth for CDS");
3391 case 8: {
3392 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3393 return APInt(8, EltVal);
3394 }
3395 case 16: {
3396 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3397 return APInt(16, EltVal);
3398 }
3399 case 32: {
3400 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3401 return APInt(32, EltVal);
3402 }
3403 case 64: {
3404 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3405 return APInt(64, EltVal);
3406 }
3407 }
3408}
3409
3411 const char *EltPtr = getElementPointer(Elt);
3412
3413 switch (getElementType()->getTypeID()) {
3414 default:
3415 llvm_unreachable("Accessor can only be used when element is float/double!");
3416 case Type::HalfTyID: {
3417 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3418 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3419 }
3420 case Type::BFloatTyID: {
3421 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3422 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3423 }
3424 case Type::FloatTyID: {
3425 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3426 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3427 }
3428 case Type::DoubleTyID: {
3429 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3430 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3431 }
3432 }
3433}
3434
3436 assert(getElementType()->isFloatTy() &&
3437 "Accessor can only be used when element is a 'float'");
3438 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3439}
3440
3442 assert(getElementType()->isDoubleTy() &&
3443 "Accessor can only be used when element is a 'float'");
3444 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3445}
3446
3448 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3449 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3450 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3451
3452 if (getElementType()->isByteTy())
3453 return ConstantByte::get(getElementType(), getElementAsInteger(Elt));
3454
3455 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3456}
3457
3458bool ConstantDataSequential::isString(unsigned CharSize) const {
3459 return isa<ArrayType>(getType()) &&
3460 (getElementType()->isIntegerTy(CharSize) ||
3461 getElementType()->isByteTy(CharSize));
3462}
3463
3465 if (!isString())
3466 return false;
3467
3468 StringRef Str = getAsString();
3469
3470 // The last value must be nul.
3471 if (Str.back() != 0) return false;
3472
3473 // Other elements must be non-nul.
3474 return !Str.drop_back().contains(0);
3475}
3476
3477bool ConstantDataVector::isSplatData() const {
3478 const char *Base = getRawDataValues().data();
3479
3480 // Compare elements 1+ to the 0'th element.
3481 unsigned EltSize = getElementByteSize();
3482 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3483 if (memcmp(Base, Base+i*EltSize, EltSize))
3484 return false;
3485
3486 return true;
3487}
3488
3490 if (!IsSplatSet) {
3491 IsSplatSet = true;
3492 IsSplat = isSplatData();
3493 }
3494 return IsSplat;
3495}
3496
3498 // If they're all the same, return the 0th one as a representative.
3499 return isSplat() ? getElementAsConstant(0) : nullptr;
3500}
3501
3502//===----------------------------------------------------------------------===//
3503// handleOperandChange implementations
3504
3505/// Update this constant array to change uses of
3506/// 'From' to be uses of 'To'. This must update the uniquing data structures
3507/// etc.
3508///
3509/// Note that we intentionally replace all uses of From with To here. Consider
3510/// a large array that uses 'From' 1000 times. By handling this case all here,
3511/// ConstantArray::handleOperandChange is only invoked once, and that
3512/// single invocation handles all 1000 uses. Handling them one at a time would
3513/// work, but would be really slow because it would have to unique each updated
3514/// array instance.
3515///
3517 Value *Replacement = nullptr;
3518 switch (getValueID()) {
3519 default:
3520 llvm_unreachable("Not a constant!");
3521#define HANDLE_CONSTANT(Name) \
3522 case Value::Name##Val: \
3523 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3524 break;
3525#include "llvm/IR/Value.def"
3526 }
3527
3528 // If handleOperandChangeImpl returned nullptr, then it handled
3529 // replacing itself and we don't want to delete or replace anything else here.
3530 if (!Replacement)
3531 return;
3532
3533 // I do need to replace this with an existing value.
3534 assert(Replacement != this && "I didn't contain From!");
3535
3536 // Everyone using this now uses the replacement.
3537 replaceAllUsesWith(Replacement);
3538
3539 // Delete the old constant!
3541}
3542
3543Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3544 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3545 Constant *ToC = cast<Constant>(To);
3546
3548 Values.reserve(getNumOperands()); // Build replacement array.
3549
3550 // Fill values with the modified operands of the constant array. Also,
3551 // compute whether this turns into an all-zeros array.
3552 unsigned NumUpdated = 0;
3553
3554 // Keep track of whether all the values in the array are "ToC".
3555 bool AllSame = true;
3556 Use *OperandList = getOperandList();
3557 unsigned OperandNo = 0;
3558 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3559 Constant *Val = cast<Constant>(O->get());
3560 if (Val == From) {
3561 OperandNo = (O - OperandList);
3562 Val = ToC;
3563 ++NumUpdated;
3564 }
3565 Values.push_back(Val);
3566 AllSame &= Val == ToC;
3567 }
3568
3569 if (AllSame && ToC->isNullValue())
3571
3572 if (AllSame && isa<UndefValue>(ToC))
3573 return UndefValue::get(getType());
3574
3575 // Check for any other type of constant-folding.
3576 if (Constant *C = getImpl(getType(), Values))
3577 return C;
3578
3579 // Update to the new value.
3581 Values, this, From, ToC, NumUpdated, OperandNo);
3582}
3583
3584Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3585 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3586 Constant *ToC = cast<Constant>(To);
3587
3588 Use *OperandList = getOperandList();
3589
3591 Values.reserve(getNumOperands()); // Build replacement struct.
3592
3593 // Fill values with the modified operands of the constant struct. Also,
3594 // compute whether this turns into an all-zeros struct.
3595 unsigned NumUpdated = 0;
3596 bool AllSame = true;
3597 unsigned OperandNo = 0;
3598 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3599 Constant *Val = cast<Constant>(O->get());
3600 if (Val == From) {
3601 OperandNo = (O - OperandList);
3602 Val = ToC;
3603 ++NumUpdated;
3604 }
3605 Values.push_back(Val);
3606 AllSame &= Val == ToC;
3607 }
3608
3609 if (AllSame && ToC->isNullValue())
3611
3612 if (AllSame && isa<UndefValue>(ToC))
3613 return UndefValue::get(getType());
3614
3615 // Update to the new value.
3617 Values, this, From, ToC, NumUpdated, OperandNo);
3618}
3619
3620Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3621 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3622 Constant *ToC = cast<Constant>(To);
3623
3625 Values.reserve(getNumOperands()); // Build replacement array...
3626 unsigned NumUpdated = 0;
3627 unsigned OperandNo = 0;
3628 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3629 Constant *Val = getOperand(i);
3630 if (Val == From) {
3631 OperandNo = i;
3632 ++NumUpdated;
3633 Val = ToC;
3634 }
3635 Values.push_back(Val);
3636 }
3637
3638 if (Constant *C = getImpl(Values))
3639 return C;
3640
3641 // Update to the new value.
3643 Values, this, From, ToC, NumUpdated, OperandNo);
3644}
3645
3646Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3647 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3648 Constant *To = cast<Constant>(ToV);
3649
3651 unsigned NumUpdated = 0;
3652 unsigned OperandNo = 0;
3653 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3654 Constant *Op = getOperand(i);
3655 if (Op == From) {
3656 OperandNo = i;
3657 ++NumUpdated;
3658 Op = To;
3659 }
3660 NewOps.push_back(Op);
3661 }
3662 assert(NumUpdated && "I didn't contain From!");
3663
3664 if (Constant *C = getWithOperands(NewOps, getType(), true))
3665 return C;
3666
3667 // Update to the new value.
3668 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3669 NewOps, this, From, To, NumUpdated, OperandNo);
3670}
3671
3673 SmallVector<Value *, 4> ValueOperands(operands());
3674 ArrayRef<Value*> Ops(ValueOperands);
3675
3676 switch (getOpcode()) {
3677 case Instruction::Trunc:
3678 case Instruction::PtrToAddr:
3679 case Instruction::PtrToInt:
3680 case Instruction::IntToPtr:
3681 case Instruction::BitCast:
3682 case Instruction::AddrSpaceCast:
3684 getType(), "");
3685 case Instruction::InsertElement:
3686 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3687 case Instruction::ExtractElement:
3688 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3689 case Instruction::ShuffleVector:
3690 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3691
3692 case Instruction::GetElementPtr: {
3693 const auto *GO = cast<GEPOperator>(this);
3694 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3695 Ops.slice(1), GO->getNoWrapFlags(), "");
3696 }
3697 default:
3698 assert(getNumOperands() == 2 && "Must be binary operator?");
3700 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3706 }
3709 return BO;
3710 }
3711}
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:296
static const fltSemantics & BFloat()
Definition APFloat.h:295
static const fltSemantics & IEEEquad()
Definition APFloat.h:298
static const fltSemantics & IEEEdouble()
Definition APFloat.h:297
static const fltSemantics & x87DoubleExtended()
Definition APFloat.h:317
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:344
static const fltSemantics & IEEEhalf()
Definition APFloat.h:294
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:299
static APFloat getQNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for QNaN values.
Definition APFloat.h:1179
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1187
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5912
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:5938
const fltSemantics & getSemantics() const
Definition APFloat.h:1546
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1157
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1168
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1138
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:133
iterator end()
Definition StringMap.h:224
iterator find(StringRef Key)
Definition StringMap.h:237
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 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:53
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:716
LLVM_ABI const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition Value.cpp:724
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:552
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:712
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:806
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
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:371
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:861
#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