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-fp-for-fixed-length-splat", cl::init(false), cl::Hidden,
44 cl::desc("Use ConstantFP's native fixed-length vector splat support."));
46 "use-constant-int-for-scalable-splat", cl::init(false), cl::Hidden,
47 cl::desc("Use ConstantInt's native scalable vector splat support."));
49 "use-constant-fp-for-scalable-splat", cl::init(false), cl::Hidden,
50 cl::desc("Use ConstantFP's native scalable vector splat support."));
51
52//===----------------------------------------------------------------------===//
53// Constant Class
54//===----------------------------------------------------------------------===//
55
57 // Floating point values have an explicit -0.0 value.
58 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
59 return CFP->isZero() && CFP->isNegative();
60
61 // Equivalent for a vector of -0.0's.
62 if (getType()->isVectorTy())
63 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
64 return SplatCFP->isNegativeZeroValue();
65
66 // We've already handled true FP case; any other FP vectors can't represent -0.0.
67 if (getType()->isFPOrFPVectorTy())
68 return false;
69
70 // Otherwise, just use +0.0.
71 return isNullValue();
72}
73
75 // 0 is null.
76 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
77 return CI->isZero();
78
79 // +0.0 is null.
80 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
81 // ppc_fp128 determine isZero using high order double only
82 // Should check the bitwise value to make sure all bits are zero.
83 return CFP->isExactlyValue(+0.0);
84
85 // constant zero is zero for aggregates, cpnull is null for pointers, none for
86 // tokens.
89}
90
92 // Check for -1 integers
93 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
94 return CI->isMinusOne();
95
96 // Check for FP which are bitcasted from -1 integers
97 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
98 return CFP->getValueAPF().bitcastToAPInt().isAllOnes();
99
100 // Check for constant splat vectors of 1 values.
101 if (getType()->isVectorTy())
102 if (const auto *SplatVal = getSplatValue())
103 return SplatVal->isAllOnesValue();
104
105 return false;
106}
107
109 // Check for 1 integers
110 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
111 return CI->isOne();
112
113 // Check for FP which are bitcasted from 1 integers
114 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
115 return CFP->getValueAPF().bitcastToAPInt().isOne();
116
117 // Check for constant splat vectors of 1 values.
118 if (getType()->isVectorTy())
119 if (const auto *SplatVal = getSplatValue())
120 return SplatVal->isOneValue();
121
122 return false;
123}
124
126 // Check for 1 integers
127 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
128 return !CI->isOneValue();
129
130 // Check for FP which are bitcasted from 1 integers
131 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
132 return !CFP->getValueAPF().bitcastToAPInt().isOne();
133
134 // Check that vectors don't contain 1
135 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
136 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
138 if (!Elt || !Elt->isNotOneValue())
139 return false;
140 }
141 return true;
142 }
143
144 // Check for splats that don't contain 1
145 if (getType()->isVectorTy())
146 if (const auto *SplatVal = getSplatValue())
147 return SplatVal->isNotOneValue();
148
149 // It *may* contain 1, we can't tell.
150 return false;
151}
152
154 // Check for INT_MIN integers
155 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
156 return CI->isMinValue(/*isSigned=*/true);
157
158 // Check for FP which are bitcasted from INT_MIN integers
159 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
160 return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
161
162 // Check for splats of INT_MIN values.
163 if (getType()->isVectorTy())
164 if (const auto *SplatVal = getSplatValue())
165 return SplatVal->isMinSignedValue();
166
167 return false;
168}
169
171 // Check for INT_MAX integers
172 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
173 return CI->isMaxValue(/*isSigned=*/true);
174
175 // Check for FP which are bitcasted from INT_MAX integers
176 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
177 return CFP->getValueAPF().bitcastToAPInt().isMaxSignedValue();
178
179 // Check for splats of INT_MAX values.
180 if (getType()->isVectorTy())
181 if (const auto *SplatVal = getSplatValue())
182 return SplatVal->isMaxSignedValue();
183
184 return false;
185}
186
188 // Check for INT_MIN integers
189 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
190 return !CI->isMinValue(/*isSigned=*/true);
191
192 // Check for FP which are bitcasted from INT_MIN integers
193 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
194 return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
195
196 // Check that vectors don't contain INT_MIN
197 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
198 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
200 if (!Elt || !Elt->isNotMinSignedValue())
201 return false;
202 }
203 return true;
204 }
205
206 // Check for splats that aren't INT_MIN
207 if (getType()->isVectorTy())
208 if (const auto *SplatVal = getSplatValue())
209 return SplatVal->isNotMinSignedValue();
210
211 // It *may* contain INT_MIN, we can't tell.
212 return false;
213}
214
216 if (auto *CFP = dyn_cast<ConstantFP>(this))
217 return CFP->getValueAPF().isFiniteNonZero();
218
219 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
220 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
222 if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
223 return false;
224 }
225 return true;
226 }
227
228 if (getType()->isVectorTy())
229 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
230 return SplatCFP->isFiniteNonZeroFP();
231
232 // It *may* contain finite non-zero, we can't tell.
233 return false;
234}
235
237 if (auto *CFP = dyn_cast<ConstantFP>(this))
238 return CFP->getValueAPF().isNormal();
239
240 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
241 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
243 if (!CFP || !CFP->getValueAPF().isNormal())
244 return false;
245 }
246 return true;
247 }
248
249 if (getType()->isVectorTy())
250 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
251 return SplatCFP->isNormalFP();
252
253 // It *may* contain a normal fp value, we can't tell.
254 return false;
255}
256
258 if (auto *CFP = dyn_cast<ConstantFP>(this))
259 return CFP->getValueAPF().getExactInverse(nullptr);
260
261 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
262 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
264 if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
265 return false;
266 }
267 return true;
268 }
269
270 if (getType()->isVectorTy())
271 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
272 return SplatCFP->hasExactInverseFP();
273
274 // It *may* have an exact inverse fp value, we can't tell.
275 return false;
276}
277
278bool Constant::isNaN() const {
279 if (auto *CFP = dyn_cast<ConstantFP>(this))
280 return CFP->isNaN();
281
282 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
283 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
285 if (!CFP || !CFP->isNaN())
286 return false;
287 }
288 return true;
289 }
290
291 if (getType()->isVectorTy())
292 if (const auto *SplatCFP = dyn_cast_or_null<ConstantFP>(getSplatValue()))
293 return SplatCFP->isNaN();
294
295 // It *may* be NaN, we can't tell.
296 return false;
297}
298
300 // Are they fully identical?
301 if (this == Y)
302 return true;
303
304 // The input value must be a vector constant with the same type.
305 auto *VTy = dyn_cast<VectorType>(getType());
306 if (!isa<Constant>(Y) || !VTy || VTy != Y->getType())
307 return false;
308
309 // TODO: Compare pointer constants?
310 if (!(VTy->getElementType()->isIntegerTy() ||
311 VTy->getElementType()->isFloatingPointTy()))
312 return false;
313
314 // They may still be identical element-wise (if they have `undef`s).
315 // Bitcast to integer to allow exact bitwise comparison for all types.
316 Type *IntTy = VectorType::getInteger(VTy);
317 Constant *C0 = ConstantExpr::getBitCast(const_cast<Constant *>(this), IntTy);
320 return CmpEq && (isa<PoisonValue>(CmpEq) || match(CmpEq, m_One()));
321}
322
323static bool
325 function_ref<bool(const Constant *)> HasFn) {
326 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
327 if (HasFn(C))
328 return true;
330 return false;
331 if (isa<ScalableVectorType>(C->getType()))
332 return false;
333
334 for (unsigned i = 0, e = cast<FixedVectorType>(VTy)->getNumElements();
335 i != e; ++i) {
336 if (Constant *Elem = C->getAggregateElement(i))
337 if (HasFn(Elem))
338 return true;
339 }
340 }
341
342 return false;
343}
344
347 this, [&](const auto *C) { return isa<UndefValue>(C); });
348}
349
352 this, [&](const auto *C) { return isa<PoisonValue>(C); });
353}
354
356 return containsUndefinedElement(this, [&](const auto *C) {
357 return isa<UndefValue>(C) && !isa<PoisonValue>(C);
358 });
359}
360
362 if (isa<ConstantInt>(this) || isa<ConstantFP>(this))
363 return false;
364
365 if (auto *VTy = dyn_cast<FixedVectorType>(getType())) {
366 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i)
368 return true;
369 }
370 return false;
371}
372
373/// Constructor to create a '0' constant of arbitrary type.
375 switch (Ty->getTypeID()) {
377 return ConstantInt::get(Ty, 0);
378 case Type::HalfTyID:
379 case Type::BFloatTyID:
380 case Type::FloatTyID:
381 case Type::DoubleTyID:
383 case Type::FP128TyID:
385 return ConstantFP::get(Ty->getContext(),
386 APFloat::getZero(Ty->getFltSemantics()));
389 case Type::StructTyID:
390 case Type::ArrayTyID:
394 case Type::TokenTyID:
395 return ConstantTokenNone::get(Ty->getContext());
398 default:
399 // Function, Label, or Opaque type?
400 llvm_unreachable("Cannot create a null constant of that type!");
401 }
402}
403
405 Type *ScalarTy = Ty->getScalarType();
406
407 // Create the base integer constant.
408 Constant *C = ConstantInt::get(Ty->getContext(), V);
409
410 // Convert an integer to a pointer, if necessary.
411 if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
413
414 // Broadcast a scalar to a vector, if necessary.
415 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
416 C = ConstantVector::getSplat(VTy->getElementCount(), C);
417
418 return C;
419}
420
422 if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
423 return ConstantInt::get(Ty->getContext(),
424 APInt::getAllOnes(ITy->getBitWidth()));
425
426 if (Ty->isFloatingPointTy()) {
427 APFloat FL = APFloat::getAllOnesValue(Ty->getFltSemantics());
428 return ConstantFP::get(Ty->getContext(), FL);
429 }
430
431 VectorType *VTy = cast<VectorType>(Ty);
432 return ConstantVector::getSplat(VTy->getElementCount(),
433 getAllOnesValue(VTy->getElementType()));
434}
435
437 assert((getType()->isAggregateType() || getType()->isVectorTy()) &&
438 "Must be an aggregate/vector constant");
439
440 if (const auto *CC = dyn_cast<ConstantAggregate>(this))
441 return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
442
443 if (const auto *CAZ = dyn_cast<ConstantAggregateZero>(this))
444 return Elt < CAZ->getElementCount().getKnownMinValue()
445 ? CAZ->getElementValue(Elt)
446 : nullptr;
447
448 if (const auto *CI = dyn_cast<ConstantInt>(this))
449 return Elt < cast<VectorType>(getType())
450 ->getElementCount()
451 .getKnownMinValue()
452 ? ConstantInt::get(getContext(), CI->getValue())
453 : nullptr;
454
455 if (const auto *CFP = dyn_cast<ConstantFP>(this))
456 return Elt < cast<VectorType>(getType())
457 ->getElementCount()
458 .getKnownMinValue()
459 ? ConstantFP::get(getContext(), CFP->getValue())
460 : nullptr;
461
462 // FIXME: getNumElements() will fail for non-fixed vector types.
464 return nullptr;
465
466 if (const auto *PV = dyn_cast<PoisonValue>(this))
467 return Elt < PV->getNumElements() ? PV->getElementValue(Elt) : nullptr;
468
469 if (const auto *UV = dyn_cast<UndefValue>(this))
470 return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
471
472 if (const auto *CDS = dyn_cast<ConstantDataSequential>(this))
473 return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
474 : nullptr;
475
476 return nullptr;
477}
478
480 assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
481 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
482 // Check if the constant fits into an uint64_t.
483 if (CI->getValue().getActiveBits() > 64)
484 return nullptr;
485 return getAggregateElement(CI->getZExtValue());
486 }
487 return nullptr;
488}
489
491 /// First call destroyConstantImpl on the subclass. This gives the subclass
492 /// a chance to remove the constant from any maps/pools it's contained in.
493 switch (getValueID()) {
494 default:
495 llvm_unreachable("Not a constant!");
496#define HANDLE_CONSTANT(Name) \
497 case Value::Name##Val: \
498 cast<Name>(this)->destroyConstantImpl(); \
499 break;
500#include "llvm/IR/Value.def"
501 }
502
503 // When a Constant is destroyed, there may be lingering
504 // references to the constant by other constants in the constant pool. These
505 // constants are implicitly dependent on the module that is being deleted,
506 // but they don't know that. Because we only find out when the CPV is
507 // deleted, we must now notify all of our users (that should only be
508 // Constants) that they are, in fact, invalid now and should be deleted.
509 //
510 while (!use_empty()) {
511 Value *V = user_back();
512#ifndef NDEBUG // Only in -g mode...
513 if (!isa<Constant>(V)) {
514 dbgs() << "While deleting: " << *this
515 << "\n\nUse still stuck around after Def is destroyed: " << *V
516 << "\n\n";
517 }
518#endif
519 assert(isa<Constant>(V) && "References remain to Constant being destroyed");
520 cast<Constant>(V)->destroyConstant();
521
522 // The constant should remove itself from our use list...
523 assert((use_empty() || user_back() != V) && "Constant not removed!");
524 }
525
526 // Value has no outstanding references it is safe to delete it now...
527 deleteConstant(this);
528}
529
531 switch (C->getValueID()) {
532 case Constant::ConstantIntVal:
533 delete static_cast<ConstantInt *>(C);
534 break;
535 case Constant::ConstantFPVal:
536 delete static_cast<ConstantFP *>(C);
537 break;
538 case Constant::ConstantAggregateZeroVal:
539 delete static_cast<ConstantAggregateZero *>(C);
540 break;
541 case Constant::ConstantArrayVal:
542 delete static_cast<ConstantArray *>(C);
543 break;
544 case Constant::ConstantStructVal:
545 delete static_cast<ConstantStruct *>(C);
546 break;
547 case Constant::ConstantVectorVal:
548 delete static_cast<ConstantVector *>(C);
549 break;
550 case Constant::ConstantPointerNullVal:
551 delete static_cast<ConstantPointerNull *>(C);
552 break;
553 case Constant::ConstantDataArrayVal:
554 delete static_cast<ConstantDataArray *>(C);
555 break;
556 case Constant::ConstantDataVectorVal:
557 delete static_cast<ConstantDataVector *>(C);
558 break;
559 case Constant::ConstantTokenNoneVal:
560 delete static_cast<ConstantTokenNone *>(C);
561 break;
562 case Constant::BlockAddressVal:
563 delete static_cast<BlockAddress *>(C);
564 break;
565 case Constant::DSOLocalEquivalentVal:
566 delete static_cast<DSOLocalEquivalent *>(C);
567 break;
568 case Constant::NoCFIValueVal:
569 delete static_cast<NoCFIValue *>(C);
570 break;
571 case Constant::ConstantPtrAuthVal:
572 delete static_cast<ConstantPtrAuth *>(C);
573 break;
574 case Constant::UndefValueVal:
575 delete static_cast<UndefValue *>(C);
576 break;
577 case Constant::PoisonValueVal:
578 delete static_cast<PoisonValue *>(C);
579 break;
580 case Constant::ConstantExprVal:
582 delete static_cast<CastConstantExpr *>(C);
583 else if (isa<BinaryConstantExpr>(C))
584 delete static_cast<BinaryConstantExpr *>(C);
586 delete static_cast<ExtractElementConstantExpr *>(C);
588 delete static_cast<InsertElementConstantExpr *>(C);
590 delete static_cast<ShuffleVectorConstantExpr *>(C);
592 delete static_cast<GetElementPtrConstantExpr *>(C);
593 else
594 llvm_unreachable("Unexpected constant expr");
595 break;
596 default:
597 llvm_unreachable("Unexpected constant");
598 }
599}
600
601/// Check if C contains a GlobalValue for which Predicate is true.
602static bool
604 bool (*Predicate)(const GlobalValue *)) {
607 WorkList.push_back(C);
608 Visited.insert(C);
609
610 while (!WorkList.empty()) {
611 const Constant *WorkItem = WorkList.pop_back_val();
612 if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
613 if (Predicate(GV))
614 return true;
615 for (const Value *Op : WorkItem->operands()) {
616 const Constant *ConstOp = dyn_cast<Constant>(Op);
617 if (!ConstOp)
618 continue;
619 if (Visited.insert(ConstOp).second)
620 WorkList.push_back(ConstOp);
621 }
622 }
623 return false;
624}
625
627 auto DLLImportPredicate = [](const GlobalValue *GV) {
628 return GV->isThreadLocal();
629 };
630 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
631}
632
634 auto DLLImportPredicate = [](const GlobalValue *GV) {
635 return GV->hasDLLImportStorageClass();
636 };
637 return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
638}
639
641 for (const User *U : users()) {
642 const Constant *UC = dyn_cast<Constant>(U);
643 if (!UC || isa<GlobalValue>(UC))
644 return true;
645
646 if (UC->isConstantUsed())
647 return true;
648 }
649 return false;
650}
651
653 return getRelocationInfo() == GlobalRelocation;
654}
655
657 return getRelocationInfo() != NoRelocation;
658}
659
660Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
661 if (isa<GlobalValue>(this))
662 return GlobalRelocation; // Global reference.
663
664 if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
665 return BA->getFunction()->getRelocationInfo();
666
667 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
668 if (CE->getOpcode() == Instruction::Sub) {
669 ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
670 ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
671 if (LHS && RHS &&
672 (LHS->getOpcode() == Instruction::PtrToInt ||
673 LHS->getOpcode() == Instruction::PtrToAddr) &&
674 (RHS->getOpcode() == Instruction::PtrToInt ||
675 RHS->getOpcode() == Instruction::PtrToAddr)) {
676 Constant *LHSOp0 = LHS->getOperand(0);
677 Constant *RHSOp0 = RHS->getOperand(0);
678
679 // While raw uses of blockaddress need to be relocated, differences
680 // between two of them don't when they are for labels in the same
681 // function. This is a common idiom when creating a table for the
682 // indirect goto extension, so we handle it efficiently here.
683 if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
684 cast<BlockAddress>(LHSOp0)->getFunction() ==
686 return NoRelocation;
687
688 // Relative pointers do not need to be dynamically relocated.
689 if (auto *RHSGV =
691 auto *LHS = LHSOp0->stripInBoundsConstantOffsets();
692 if (auto *LHSGV = dyn_cast<GlobalValue>(LHS)) {
693 if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
694 return LocalRelocation;
695 } else if (isa<DSOLocalEquivalent>(LHS)) {
696 if (RHSGV->isDSOLocal())
697 return LocalRelocation;
698 }
699 }
700 }
701 }
702 }
703
704 PossibleRelocationsTy Result = NoRelocation;
705 for (const Value *Op : operands())
706 Result = std::max(cast<Constant>(Op)->getRelocationInfo(), Result);
707
708 return Result;
709}
710
711/// Return true if the specified constantexpr is dead. This involves
712/// recursively traversing users of the constantexpr.
713/// If RemoveDeadUsers is true, also remove dead users at the same time.
714static bool constantIsDead(const Constant *C, bool RemoveDeadUsers) {
715 if (isa<GlobalValue>(C)) return false; // Cannot remove this
716
717 Value::const_user_iterator I = C->user_begin(), E = C->user_end();
718 while (I != E) {
720 if (!User) return false; // Non-constant usage;
721 if (!constantIsDead(User, RemoveDeadUsers))
722 return false; // Constant wasn't dead
723
724 // Just removed User, so the iterator was invalidated.
725 // Since we return immediately upon finding a live user, we can always
726 // restart from user_begin().
727 if (RemoveDeadUsers)
728 I = C->user_begin();
729 else
730 ++I;
731 }
732
733 if (RemoveDeadUsers) {
734 // If C is only used by metadata, it should not be preserved but should
735 // have its uses replaced.
737 const_cast<Constant *>(C)->destroyConstant();
738 }
739
740 return true;
741}
742
745 Value::const_user_iterator LastNonDeadUser = E;
746 while (I != E) {
748 if (!User) {
749 LastNonDeadUser = I;
750 ++I;
751 continue;
752 }
753
754 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
755 // If the constant wasn't dead, remember that this was the last live use
756 // and move on to the next constant.
757 LastNonDeadUser = I;
758 ++I;
759 continue;
760 }
761
762 // If the constant was dead, then the iterator is invalidated.
763 if (LastNonDeadUser == E)
764 I = user_begin();
765 else
766 I = std::next(LastNonDeadUser);
767 }
768}
769
770bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
771
772bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
773
774bool Constant::hasNLiveUses(unsigned N) const {
775 unsigned NumUses = 0;
776 for (const Use &U : uses()) {
777 const Constant *User = dyn_cast<Constant>(U.getUser());
778 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
779 ++NumUses;
780
781 if (NumUses > N)
782 return false;
783 }
784 }
785 return NumUses == N;
786}
787
789 assert(C && Replacement && "Expected non-nullptr constant arguments");
790 Type *Ty = C->getType();
791 if (match(C, m_Undef())) {
792 assert(Ty == Replacement->getType() && "Expected matching types");
793 return Replacement;
794 }
795
796 // Don't know how to deal with this constant.
797 auto *VTy = dyn_cast<FixedVectorType>(Ty);
798 if (!VTy)
799 return C;
800
801 unsigned NumElts = VTy->getNumElements();
802 SmallVector<Constant *, 32> NewC(NumElts);
803 for (unsigned i = 0; i != NumElts; ++i) {
804 Constant *EltC = C->getAggregateElement(i);
805 assert((!EltC || EltC->getType() == Replacement->getType()) &&
806 "Expected matching types");
807 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
808 }
809 return ConstantVector::get(NewC);
810}
811
813 assert(C && Other && "Expected non-nullptr constant arguments");
814 if (match(C, m_Undef()))
815 return C;
816
817 Type *Ty = C->getType();
818 if (match(Other, m_Undef()))
819 return UndefValue::get(Ty);
820
821 auto *VTy = dyn_cast<FixedVectorType>(Ty);
822 if (!VTy)
823 return C;
824
825 Type *EltTy = VTy->getElementType();
826 unsigned NumElts = VTy->getNumElements();
827 assert(isa<FixedVectorType>(Other->getType()) &&
828 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
829 "Type mismatch");
830
831 bool FoundExtraUndef = false;
832 SmallVector<Constant *, 32> NewC(NumElts);
833 for (unsigned I = 0; I != NumElts; ++I) {
834 NewC[I] = C->getAggregateElement(I);
835 Constant *OtherEltC = Other->getAggregateElement(I);
836 assert(NewC[I] && OtherEltC && "Unknown vector element");
837 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
838 NewC[I] = UndefValue::get(EltTy);
839 FoundExtraUndef = true;
840 }
841 }
842 if (FoundExtraUndef)
843 return ConstantVector::get(NewC);
844 return C;
845}
846
848 if (isa<UndefValue>(this))
849 return false;
850 if (isa<ConstantData>(this))
851 return true;
852 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
853 for (const Value *Op : operand_values())
855 return false;
856 return true;
857 }
858 return false;
859}
860
861//===----------------------------------------------------------------------===//
862// ConstantInt
863//===----------------------------------------------------------------------===//
864
865ConstantInt::ConstantInt(Type *Ty, const APInt &V)
866 : ConstantData(Ty, ConstantIntVal), Val(V) {
867 assert(V.getBitWidth() ==
868 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
869 "Invalid constant for type");
870}
871
872ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
873 LLVMContextImpl *pImpl = Context.pImpl;
874 if (!pImpl->TheTrueVal)
875 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
876 return pImpl->TheTrueVal;
877}
878
879ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
880 LLVMContextImpl *pImpl = Context.pImpl;
881 if (!pImpl->TheFalseVal)
882 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
883 return pImpl->TheFalseVal;
884}
885
886ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
887 return V ? getTrue(Context) : getFalse(Context);
888}
889
891 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
892 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
893 if (auto *VTy = dyn_cast<VectorType>(Ty))
894 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
895 return TrueC;
896}
897
899 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
900 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
901 if (auto *VTy = dyn_cast<VectorType>(Ty))
902 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
903 return FalseC;
904}
905
907 return V ? getTrue(Ty) : getFalse(Ty);
908}
909
910// Get a ConstantInt from an APInt.
911ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
912 // get an existing value or the insertion position
913 LLVMContextImpl *pImpl = Context.pImpl;
914 std::unique_ptr<ConstantInt> &Slot =
915 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
916 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
917 : pImpl->IntConstants[V];
918 if (!Slot) {
919 // Get the corresponding integer type for the bit width of the value.
920 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
921 Slot.reset(new ConstantInt(ITy, V));
922 }
923 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
924 return Slot.get();
925}
926
927// Get a ConstantInt vector with each lane set to the same APInt.
928ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
929 const APInt &V) {
930 // Get an existing value or the insertion position.
931 std::unique_ptr<ConstantInt> &Slot =
932 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
933 if (!Slot) {
934 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
935 VectorType *VTy = VectorType::get(ITy, EC);
936 Slot.reset(new ConstantInt(VTy, V));
937 }
938
939#ifndef NDEBUG
940 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
941 VectorType *VTy = VectorType::get(ITy, EC);
942 assert(Slot->getType() == VTy);
943#endif
944 return Slot.get();
945}
946
947Constant *ConstantInt::get(Type *Ty, uint64_t V, bool IsSigned,
948 bool ImplicitTrunc) {
949 Constant *C =
950 get(cast<IntegerType>(Ty->getScalarType()), V, IsSigned, ImplicitTrunc);
951
952 // For vectors, broadcast the value.
953 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
954 return ConstantVector::getSplat(VTy->getElementCount(), C);
955
956 return C;
957}
958
959ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool IsSigned,
960 bool ImplicitTrunc) {
961 return get(Ty->getContext(),
962 APInt(Ty->getBitWidth(), V, IsSigned, ImplicitTrunc));
963}
964
965Constant *ConstantInt::get(Type *Ty, const APInt& V) {
966 ConstantInt *C = get(Ty->getContext(), V);
967 assert(C->getType() == Ty->getScalarType() &&
968 "ConstantInt type doesn't match the type implied by its value!");
969
970 // For vectors, broadcast the value.
971 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
972 return ConstantVector::getSplat(VTy->getElementCount(), C);
973
974 return C;
975}
976
977ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
978 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
979}
980
981/// Remove the constant from the constant table.
982void ConstantInt::destroyConstantImpl() {
983 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
984}
985
986//===----------------------------------------------------------------------===//
987// ConstantFP
988//===----------------------------------------------------------------------===//
989
990Constant *ConstantFP::get(Type *Ty, double V) {
991 LLVMContext &Context = Ty->getContext();
992
993 APFloat FV(V);
994 bool ignored;
995 FV.convert(Ty->getScalarType()->getFltSemantics(),
997 Constant *C = get(Context, FV);
998
999 // For vectors, broadcast the value.
1000 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1001 return ConstantVector::getSplat(VTy->getElementCount(), C);
1002
1003 return C;
1004}
1005
1006Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
1007 ConstantFP *C = get(Ty->getContext(), V);
1008 assert(C->getType() == Ty->getScalarType() &&
1009 "ConstantFP type doesn't match the type implied by its value!");
1010
1011 // For vectors, broadcast the value.
1012 if (auto *VTy = dyn_cast<VectorType>(Ty))
1013 return ConstantVector::getSplat(VTy->getElementCount(), C);
1014
1015 return C;
1016}
1017
1018Constant *ConstantFP::get(Type *Ty, StringRef Str) {
1019 LLVMContext &Context = Ty->getContext();
1020
1021 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1022 Constant *C = get(Context, FV);
1023
1024 // For vectors, broadcast the value.
1025 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1026 return ConstantVector::getSplat(VTy->getElementCount(), C);
1027
1028 return C;
1029}
1030
1031Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1032 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1033 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1034 Constant *C = get(Ty->getContext(), NaN);
1035
1036 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1037 return ConstantVector::getSplat(VTy->getElementCount(), C);
1038
1039 return C;
1040}
1041
1042Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1043 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1044 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1045 Constant *C = get(Ty->getContext(), NaN);
1046
1047 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1048 return ConstantVector::getSplat(VTy->getElementCount(), C);
1049
1050 return C;
1051}
1052
1053Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1054 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1055 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1056 Constant *C = get(Ty->getContext(), NaN);
1057
1058 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1059 return ConstantVector::getSplat(VTy->getElementCount(), C);
1060
1061 return C;
1062}
1063
1064Constant *ConstantFP::getZero(Type *Ty, bool Negative) {
1065 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1066 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1067 Constant *C = get(Ty->getContext(), NegZero);
1068
1069 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1070 return ConstantVector::getSplat(VTy->getElementCount(), C);
1071
1072 return C;
1073}
1074
1075
1076// ConstantFP accessors.
1077ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1078 LLVMContextImpl* pImpl = Context.pImpl;
1079
1080 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1081
1082 if (!Slot) {
1083 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1084 Slot.reset(new ConstantFP(Ty, V));
1085 }
1086
1087 return Slot.get();
1088}
1089
1090// Get a ConstantFP vector with each lane set to the same APFloat.
1091ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1092 const APFloat &V) {
1093 // Get an existing value or the insertion position.
1094 std::unique_ptr<ConstantFP> &Slot =
1095 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1096 if (!Slot) {
1097 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1098 VectorType *VTy = VectorType::get(EltTy, EC);
1099 Slot.reset(new ConstantFP(VTy, V));
1100 }
1101
1102#ifndef NDEBUG
1103 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1104 VectorType *VTy = VectorType::get(EltTy, EC);
1105 assert(Slot->getType() == VTy);
1106#endif
1107 return Slot.get();
1108}
1109
1111 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1112 Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
1113
1114 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1115 return ConstantVector::getSplat(VTy->getElementCount(), C);
1116
1117 return C;
1118}
1119
1120ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1121 : ConstantData(Ty, ConstantFPVal), Val(V) {
1122 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1123 "FP type Mismatch");
1124}
1125
1127 return Val.bitwiseIsEqual(V);
1128}
1129
1130/// Remove the constant from the constant table.
1131void ConstantFP::destroyConstantImpl() {
1132 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1133}
1134
1135//===----------------------------------------------------------------------===//
1136// ConstantAggregateZero Implementation
1137//===----------------------------------------------------------------------===//
1138
1140 if (auto *AT = dyn_cast<ArrayType>(getType()))
1141 return Constant::getNullValue(AT->getElementType());
1142 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1143}
1144
1146 return Constant::getNullValue(getType()->getStructElementType(Elt));
1147}
1148
1154
1157 return getSequentialElement();
1158 return getStructElement(Idx);
1159}
1160
1162 Type *Ty = getType();
1163 if (auto *AT = dyn_cast<ArrayType>(Ty))
1164 return ElementCount::getFixed(AT->getNumElements());
1165 if (auto *VT = dyn_cast<VectorType>(Ty))
1166 return VT->getElementCount();
1167 return ElementCount::getFixed(Ty->getStructNumElements());
1168}
1169
1170//===----------------------------------------------------------------------===//
1171// UndefValue Implementation
1172//===----------------------------------------------------------------------===//
1173
1176 return UndefValue::get(ATy->getElementType());
1177 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1178}
1179
1180UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1181 return UndefValue::get(getType()->getStructElementType(Elt));
1182}
1183
1186 return getSequentialElement();
1187 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1188}
1189
1190UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1192 return getSequentialElement();
1193 return getStructElement(Idx);
1194}
1195
1197 Type *Ty = getType();
1198 if (auto *AT = dyn_cast<ArrayType>(Ty))
1199 return AT->getNumElements();
1200 if (auto *VT = dyn_cast<VectorType>(Ty))
1201 return cast<FixedVectorType>(VT)->getNumElements();
1202 return Ty->getStructNumElements();
1203}
1204
1205//===----------------------------------------------------------------------===//
1206// PoisonValue Implementation
1207//===----------------------------------------------------------------------===//
1208
1211 return PoisonValue::get(ATy->getElementType());
1212 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1213}
1214
1215PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1216 return PoisonValue::get(getType()->getStructElementType(Elt));
1217}
1218
1221 return getSequentialElement();
1222 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1223}
1224
1225PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1227 return getSequentialElement();
1228 return getStructElement(Idx);
1229}
1230
1231//===----------------------------------------------------------------------===//
1232// ConstantXXX Classes
1233//===----------------------------------------------------------------------===//
1234
1235template <typename ItTy, typename EltTy>
1236static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1237 for (; Start != End; ++Start)
1238 if (*Start != Elt)
1239 return false;
1240 return true;
1241}
1242
1243template <typename SequentialTy, typename ElementTy>
1245 assert(!V.empty() && "Cannot get empty int sequence.");
1246
1248 for (Constant *C : V)
1249 if (auto *CI = dyn_cast<ConstantInt>(C))
1250 Elts.push_back(CI->getZExtValue());
1251 else
1252 return nullptr;
1253 return SequentialTy::get(V[0]->getContext(), Elts);
1254}
1255
1256template <typename SequentialTy, typename ElementTy>
1258 assert(!V.empty() && "Cannot get empty FP sequence.");
1259
1261 for (Constant *C : V)
1262 if (auto *CFP = dyn_cast<ConstantFP>(C))
1263 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1264 else
1265 return nullptr;
1266 return SequentialTy::getFP(V[0]->getType(), Elts);
1267}
1268
1269template <typename SequenceTy>
1272 // We speculatively build the elements here even if it turns out that there is
1273 // a constantexpr or something else weird, since it is so uncommon for that to
1274 // happen.
1275 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1276 if (CI->getType()->isIntegerTy(8))
1278 else if (CI->getType()->isIntegerTy(16))
1280 else if (CI->getType()->isIntegerTy(32))
1282 else if (CI->getType()->isIntegerTy(64))
1284 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1285 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1287 else if (CFP->getType()->isFloatTy())
1289 else if (CFP->getType()->isDoubleTy())
1291 }
1292
1293 return nullptr;
1294}
1295
1299 : Constant(T, VT, AllocInfo) {
1300 llvm::copy(V, op_begin());
1301
1302 // Check that types match, unless this is an opaque struct.
1303 if (auto *ST = dyn_cast<StructType>(T)) {
1304 if (ST->isOpaque())
1305 return;
1306 for (unsigned I = 0, E = V.size(); I != E; ++I)
1307 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1308 "Initializer for struct element doesn't match!");
1309 }
1310}
1311
1312ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1314 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1315 assert(V.size() == T->getNumElements() &&
1316 "Invalid initializer for constant array");
1317}
1318
1320 if (Constant *C = getImpl(Ty, V))
1321 return C;
1322 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1323}
1324
1325Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1326 // Empty arrays are canonicalized to ConstantAggregateZero.
1327 if (V.empty())
1328 return ConstantAggregateZero::get(Ty);
1329
1330 for (Constant *C : V) {
1331 assert(C->getType() == Ty->getElementType() &&
1332 "Wrong type in array element initializer");
1333 (void)C;
1334 }
1335
1336 // If this is an all-zero array, return a ConstantAggregateZero object. If
1337 // all undef, return an UndefValue, if "all simple", then return a
1338 // ConstantDataArray.
1339 Constant *C = V[0];
1340 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1341 return PoisonValue::get(Ty);
1342
1343 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1344 return UndefValue::get(Ty);
1345
1346 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1347 return ConstantAggregateZero::get(Ty);
1348
1349 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1350 // the element type is compatible with ConstantDataVector. If so, use it.
1353
1354 // Otherwise, we really do want to create a ConstantArray.
1355 return nullptr;
1356}
1357
1360 bool Packed) {
1361 unsigned VecSize = V.size();
1362 SmallVector<Type*, 16> EltTypes(VecSize);
1363 for (unsigned i = 0; i != VecSize; ++i)
1364 EltTypes[i] = V[i]->getType();
1365
1366 return StructType::get(Context, EltTypes, Packed);
1367}
1368
1369
1371 bool Packed) {
1372 assert(!V.empty() &&
1373 "ConstantStruct::getTypeForElements cannot be called on empty list");
1374 return getTypeForElements(V[0]->getContext(), V, Packed);
1375}
1376
1377ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1379 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1380 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1381 "Invalid initializer for constant struct");
1382}
1383
1384// ConstantStruct accessors.
1386 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1387 "Incorrect # elements specified to ConstantStruct::get");
1388
1389 // Create a ConstantAggregateZero value if all elements are zeros.
1390 bool isZero = true;
1391 bool isUndef = false;
1392 bool isPoison = false;
1393
1394 if (!V.empty()) {
1395 isUndef = isa<UndefValue>(V[0]);
1396 isPoison = isa<PoisonValue>(V[0]);
1397 isZero = V[0]->isNullValue();
1398 // PoisonValue inherits UndefValue, so its check is not necessary.
1399 if (isUndef || isZero) {
1400 for (Constant *C : V) {
1401 if (!C->isNullValue())
1402 isZero = false;
1403 if (!isa<PoisonValue>(C))
1404 isPoison = false;
1406 isUndef = false;
1407 }
1408 }
1409 }
1410 if (isZero)
1411 return ConstantAggregateZero::get(ST);
1412 if (isPoison)
1413 return PoisonValue::get(ST);
1414 if (isUndef)
1415 return UndefValue::get(ST);
1416
1417 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1418}
1419
1420ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1422 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1423 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1424 "Invalid initializer for constant vector");
1425}
1426
1427// ConstantVector accessors.
1429 if (Constant *C = getImpl(V))
1430 return C;
1431 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1432 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1433}
1434
1435Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1436 assert(!V.empty() && "Vectors can't be empty");
1437 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1438
1439 // If this is an all-undef or all-zero vector, return a
1440 // ConstantAggregateZero or UndefValue.
1441 Constant *C = V[0];
1442 bool isZero = C->isNullValue();
1443 bool isUndef = isa<UndefValue>(C);
1444 bool isPoison = isa<PoisonValue>(C);
1447
1448 if (isZero || isUndef || isSplatFP || isSplatInt) {
1449 for (unsigned i = 1, e = V.size(); i != e; ++i)
1450 if (V[i] != C) {
1451 isZero = isUndef = isPoison = isSplatFP = isSplatInt = false;
1452 break;
1453 }
1454 }
1455
1456 if (isZero)
1458 if (isPoison)
1459 return PoisonValue::get(T);
1460 if (isUndef)
1461 return UndefValue::get(T);
1462 if (isSplatFP)
1463 return ConstantFP::get(C->getContext(), T->getElementCount(),
1464 cast<ConstantFP>(C)->getValue());
1465 if (isSplatInt)
1466 return ConstantInt::get(C->getContext(), T->getElementCount(),
1467 cast<ConstantInt>(C)->getValue());
1468
1469 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1470 // the element type is compatible with ConstantDataVector. If so, use it.
1473
1474 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1475 // the operand list contains a ConstantExpr or something else strange.
1476 return nullptr;
1477}
1478
1480 if (!EC.isScalable()) {
1481 // Maintain special handling of zero.
1482 if (!V->isNullValue()) {
1484 return ConstantInt::get(V->getContext(), EC,
1485 cast<ConstantInt>(V)->getValue());
1487 return ConstantFP::get(V->getContext(), EC,
1488 cast<ConstantFP>(V)->getValue());
1489 }
1490
1491 // If this splat is compatible with ConstantDataVector, use it instead of
1492 // ConstantVector.
1493 if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
1495 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1496
1497 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1498 return get(Elts);
1499 }
1500
1501 // Maintain special handling of zero.
1502 if (!V->isNullValue()) {
1504 return ConstantInt::get(V->getContext(), EC,
1505 cast<ConstantInt>(V)->getValue());
1507 return ConstantFP::get(V->getContext(), EC,
1508 cast<ConstantFP>(V)->getValue());
1509 }
1510
1511 Type *VTy = VectorType::get(V->getType(), EC);
1512
1513 if (V->isNullValue())
1514 return ConstantAggregateZero::get(VTy);
1515 if (isa<PoisonValue>(V))
1516 return PoisonValue::get(VTy);
1517 if (isa<UndefValue>(V))
1518 return UndefValue::get(VTy);
1519
1520 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1521
1522 // Move scalar into vector.
1523 Constant *PoisonV = PoisonValue::get(VTy);
1524 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1525 // Build shuffle mask to perform the splat.
1526 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1527 // Splat.
1528 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1529}
1530
1531ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1532 LLVMContextImpl *pImpl = Context.pImpl;
1533 if (!pImpl->TheNoneToken)
1534 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1535 return pImpl->TheNoneToken.get();
1536}
1537
1538/// Remove the constant from the constant table.
1539void ConstantTokenNone::destroyConstantImpl() {
1540 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1541}
1542
1543// Utility function for determining if a ConstantExpr is a CastOp or not. This
1544// can't be inline because we don't want to #include Instruction.h into
1545// Constant.h
1547
1551
1553 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1554}
1555
1557 bool OnlyIfReduced, Type *SrcTy) const {
1558 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1559
1560 // If no operands changed return self.
1561 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1562 return const_cast<ConstantExpr*>(this);
1563
1564 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1565 switch (getOpcode()) {
1566 case Instruction::Trunc:
1567 case Instruction::ZExt:
1568 case Instruction::SExt:
1569 case Instruction::FPTrunc:
1570 case Instruction::FPExt:
1571 case Instruction::UIToFP:
1572 case Instruction::SIToFP:
1573 case Instruction::FPToUI:
1574 case Instruction::FPToSI:
1575 case Instruction::PtrToAddr:
1576 case Instruction::PtrToInt:
1577 case Instruction::IntToPtr:
1578 case Instruction::BitCast:
1579 case Instruction::AddrSpaceCast:
1580 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1581 case Instruction::InsertElement:
1582 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1583 OnlyIfReducedTy);
1584 case Instruction::ExtractElement:
1585 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1586 case Instruction::ShuffleVector:
1588 OnlyIfReducedTy);
1589 case Instruction::GetElementPtr: {
1590 auto *GEPO = cast<GEPOperator>(this);
1591 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1593 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1594 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1595 }
1596 default:
1597 assert(getNumOperands() == 2 && "Must be binary operator?");
1599 OnlyIfReducedTy);
1600 }
1601}
1602
1603
1604//===----------------------------------------------------------------------===//
1605// isValueValidForType implementations
1606
1608 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1609 if (Ty->isIntegerTy(1))
1610 return Val == 0 || Val == 1;
1611 return isUIntN(NumBits, Val);
1612}
1613
1615 unsigned NumBits = Ty->getIntegerBitWidth();
1616 if (Ty->isIntegerTy(1))
1617 return Val == 0 || Val == 1 || Val == -1;
1618 return isIntN(NumBits, Val);
1619}
1620
1622 // convert modifies in place, so make a copy.
1623 APFloat Val2 = APFloat(Val);
1624 bool losesInfo;
1625 switch (Ty->getTypeID()) {
1626 default:
1627 return false; // These can't be represented as floating point!
1628
1629 // FIXME rounding mode needs to be more flexible
1630 case Type::HalfTyID: {
1631 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1632 return true;
1634 return !losesInfo;
1635 }
1636 case Type::BFloatTyID: {
1637 if (&Val2.getSemantics() == &APFloat::BFloat())
1638 return true;
1640 return !losesInfo;
1641 }
1642 case Type::FloatTyID: {
1643 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1644 return true;
1646 return !losesInfo;
1647 }
1648 case Type::DoubleTyID: {
1649 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1650 &Val2.getSemantics() == &APFloat::BFloat() ||
1651 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1652 &Val2.getSemantics() == &APFloat::IEEEdouble())
1653 return true;
1655 return !losesInfo;
1656 }
1657 case Type::X86_FP80TyID:
1658 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1659 &Val2.getSemantics() == &APFloat::BFloat() ||
1660 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1661 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1663 case Type::FP128TyID:
1664 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1665 &Val2.getSemantics() == &APFloat::BFloat() ||
1666 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1667 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1668 &Val2.getSemantics() == &APFloat::IEEEquad();
1670 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1671 &Val2.getSemantics() == &APFloat::BFloat() ||
1672 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1673 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1675 }
1676}
1677
1678
1679//===----------------------------------------------------------------------===//
1680// Factory Function Implementation
1681
1682ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1683 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1684 "Cannot create an aggregate zero of non-aggregate type!");
1685
1686 std::unique_ptr<ConstantAggregateZero> &Entry =
1687 Ty->getContext().pImpl->CAZConstants[Ty];
1688 if (!Entry)
1689 Entry.reset(new ConstantAggregateZero(Ty));
1690
1691 return Entry.get();
1692}
1693
1694/// Remove the constant from the constant table.
1695void ConstantAggregateZero::destroyConstantImpl() {
1697}
1698
1699/// Remove the constant from the constant table.
1700void ConstantArray::destroyConstantImpl() {
1702}
1703
1704
1705//---- ConstantStruct::get() implementation...
1706//
1707
1708/// Remove the constant from the constant table.
1709void ConstantStruct::destroyConstantImpl() {
1711}
1712
1713/// Remove the constant from the constant table.
1714void ConstantVector::destroyConstantImpl() {
1716}
1717
1718Constant *Constant::getSplatValue(bool AllowPoison) const {
1719 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1720 if (isa<PoisonValue>(this))
1721 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1723 return getNullValue(cast<VectorType>(getType())->getElementType());
1724 if (auto *CI = dyn_cast<ConstantInt>(this))
1725 return ConstantInt::get(getContext(), CI->getValue());
1726 if (auto *CFP = dyn_cast<ConstantFP>(this))
1727 return ConstantFP::get(getContext(), CFP->getValue());
1729 return CV->getSplatValue();
1730 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1731 return CV->getSplatValue(AllowPoison);
1732
1733 // Check if this is a constant expression splat of the form returned by
1734 // ConstantVector::getSplat()
1735 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1736 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1737 isa<UndefValue>(Shuf->getOperand(1))) {
1738
1739 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1740 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1741 isa<UndefValue>(IElt->getOperand(0))) {
1742
1743 ArrayRef<int> Mask = Shuf->getShuffleMask();
1744 Constant *SplatVal = IElt->getOperand(1);
1745 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1746
1747 if (Index && Index->getValue() == 0 && llvm::all_of(Mask, equal_to(0)))
1748 return SplatVal;
1749 }
1750 }
1751
1752 return nullptr;
1753}
1754
1755Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1756 // Check out first element.
1757 Constant *Elt = getOperand(0);
1758 // Then make sure all remaining elements point to the same value.
1759 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1760 Constant *OpC = getOperand(I);
1761 if (OpC == Elt)
1762 continue;
1763
1764 // Strict mode: any mismatch is not a splat.
1765 if (!AllowPoison)
1766 return nullptr;
1767
1768 // Allow poison mode: ignore poison elements.
1769 if (isa<PoisonValue>(OpC))
1770 continue;
1771
1772 // If we do not have a defined element yet, use the current operand.
1773 if (isa<PoisonValue>(Elt))
1774 Elt = OpC;
1775
1776 if (OpC != Elt)
1777 return nullptr;
1778 }
1779 return Elt;
1780}
1781
1783 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1784 return CI->getValue();
1785 // Scalable vectors can use a ConstantExpr to build a splat.
1786 if (isa<ConstantExpr>(this))
1787 return cast<ConstantInt>(this->getSplatValue())->getValue();
1788 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1789 // calling getSplatValue in release builds.
1790 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1791 const Constant *C = this->getAggregateElement(0U);
1792 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1793 return cast<ConstantInt>(C)->getValue();
1794}
1795
1797 if (auto *CI = dyn_cast<ConstantInt>(this))
1798 return ConstantRange(CI->getValue());
1799
1800 unsigned BitWidth = getType()->getScalarSizeInBits();
1801 if (!getType()->isVectorTy())
1802 return ConstantRange::getFull(BitWidth);
1803
1804 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1805 getSplatValue(/*AllowPoison=*/true)))
1806 return ConstantRange(CI->getValue());
1807
1808 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1809 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1810 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1811 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1812 return CR;
1813 }
1814
1815 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1816 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1817 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1818 Constant *Elem = CV->getOperand(I);
1819 if (!Elem)
1820 return ConstantRange::getFull(BitWidth);
1821 if (isa<PoisonValue>(Elem))
1822 continue;
1823 auto *CI = dyn_cast<ConstantInt>(Elem);
1824 if (!CI)
1825 return ConstantRange::getFull(BitWidth);
1826 CR = CR.unionWith(CI->getValue());
1827 }
1828 return CR;
1829 }
1830
1831 return ConstantRange::getFull(BitWidth);
1832}
1833
1834//---- ConstantPointerNull::get() implementation.
1835//
1836
1837ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
1838 std::unique_ptr<ConstantPointerNull> &Entry =
1839 Ty->getContext().pImpl->CPNConstants[Ty];
1840 if (!Entry)
1841 Entry.reset(new ConstantPointerNull(Ty));
1842
1843 return Entry.get();
1844}
1845
1846/// Remove the constant from the constant table.
1847void ConstantPointerNull::destroyConstantImpl() {
1849}
1850
1851//---- ConstantTargetNone::get() implementation.
1852//
1853
1854ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
1855 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
1856 "Target extension type not allowed to have a zeroinitializer");
1857 std::unique_ptr<ConstantTargetNone> &Entry =
1858 Ty->getContext().pImpl->CTNConstants[Ty];
1859 if (!Entry)
1860 Entry.reset(new ConstantTargetNone(Ty));
1861
1862 return Entry.get();
1863}
1864
1865/// Remove the constant from the constant table.
1866void ConstantTargetNone::destroyConstantImpl() {
1868}
1869
1870UndefValue *UndefValue::get(Type *Ty) {
1871 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
1872 if (!Entry)
1873 Entry.reset(new UndefValue(Ty));
1874
1875 return Entry.get();
1876}
1877
1878/// Remove the constant from the constant table.
1879void UndefValue::destroyConstantImpl() {
1880 // Free the constant and any dangling references to it.
1881 if (getValueID() == UndefValueVal) {
1882 getContext().pImpl->UVConstants.erase(getType());
1883 } else if (getValueID() == PoisonValueVal) {
1884 getContext().pImpl->PVConstants.erase(getType());
1885 }
1886 llvm_unreachable("Not a undef or a poison!");
1887}
1888
1889PoisonValue *PoisonValue::get(Type *Ty) {
1890 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
1891 if (!Entry)
1892 Entry.reset(new PoisonValue(Ty));
1893
1894 return Entry.get();
1895}
1896
1897/// Remove the constant from the constant table.
1898void PoisonValue::destroyConstantImpl() {
1899 // Free the constant and any dangling references to it.
1900 getContext().pImpl->PVConstants.erase(getType());
1901}
1902
1903BlockAddress *BlockAddress::get(Type *Ty, BasicBlock *BB) {
1904 BlockAddress *&BA = BB->getContext().pImpl->BlockAddresses[BB];
1905 if (!BA)
1906 BA = new BlockAddress(Ty, BB);
1907 return BA;
1908}
1909
1910BlockAddress *BlockAddress::get(BasicBlock *BB) {
1911 assert(BB->getParent() && "Block must have a parent");
1912 return get(BB->getParent()->getType(), BB);
1913}
1914
1916 assert(BB->getParent() == F && "Block not part of specified function");
1917 return get(BB->getParent()->getType(), BB);
1918}
1919
1920BlockAddress::BlockAddress(Type *Ty, BasicBlock *BB)
1921 : Constant(Ty, Value::BlockAddressVal, AllocMarker) {
1922 setOperand(0, BB);
1923 BB->setHasAddressTaken(true);
1924}
1925
1926BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
1927 if (!BB->hasAddressTaken())
1928 return nullptr;
1929
1930 BlockAddress *BA = BB->getContext().pImpl->BlockAddresses.lookup(BB);
1931 assert(BA && "Refcount and block address map disagree!");
1932 return BA;
1933}
1934
1935/// Remove the constant from the constant table.
1936void BlockAddress::destroyConstantImpl() {
1938 getBasicBlock()->setHasAddressTaken(false);
1939}
1940
1941Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
1942 assert(From == getBasicBlock());
1943 BasicBlock *NewBB = cast<BasicBlock>(To);
1944
1945 // See if the 'new' entry already exists, if not, just update this in place
1946 // and return early.
1947 BlockAddress *&NewBA = getContext().pImpl->BlockAddresses[NewBB];
1948 if (NewBA)
1949 return NewBA;
1950
1951 getBasicBlock()->setHasAddressTaken(false);
1952
1953 // Remove the old entry, this can't cause the map to rehash (just a
1954 // tombstone will get added).
1956 NewBA = this;
1957 setOperand(0, NewBB);
1958 getBasicBlock()->setHasAddressTaken(true);
1959
1960 // If we just want to keep the existing value, then return null.
1961 // Callers know that this means we shouldn't delete this value.
1962 return nullptr;
1963}
1964
1965DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
1966 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
1967 if (!Equiv)
1968 Equiv = new DSOLocalEquivalent(GV);
1969
1970 assert(Equiv->getGlobalValue() == GV &&
1971 "DSOLocalFunction does not match the expected global value");
1972 return Equiv;
1973}
1974
1975DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
1976 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
1977 setOperand(0, GV);
1978}
1979
1980/// Remove the constant from the constant table.
1981void DSOLocalEquivalent::destroyConstantImpl() {
1982 const GlobalValue *GV = getGlobalValue();
1983 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
1984}
1985
1986Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
1987 assert(From == getGlobalValue() && "Changing value does not match operand.");
1988 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
1989
1990 // The replacement is with another global value.
1991 if (const auto *ToObj = dyn_cast<GlobalValue>(To)) {
1992 DSOLocalEquivalent *&NewEquiv =
1994 if (NewEquiv)
1995 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
1996 }
1997
1998 // If the argument is replaced with a null value, just replace this constant
1999 // with a null value.
2000 if (cast<Constant>(To)->isNullValue())
2001 return To;
2002
2003 // The replacement could be a bitcast or an alias to another function. We can
2004 // replace it with a bitcast to the dso_local_equivalent of that function.
2006 DSOLocalEquivalent *&NewEquiv = getContext().pImpl->DSOLocalEquivalents[Func];
2007 if (NewEquiv)
2008 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2009
2010 // Replace this with the new one.
2012 NewEquiv = this;
2013 setOperand(0, Func);
2014
2015 if (Func->getType() != getType()) {
2016 // It is ok to mutate the type here because this constant should always
2017 // reflect the type of the function it's holding.
2018 mutateType(Func->getType());
2019 }
2020 return nullptr;
2021}
2022
2024 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2025 if (!NC)
2026 NC = new NoCFIValue(GV);
2027
2028 assert(NC->getGlobalValue() == GV &&
2029 "NoCFIValue does not match the expected global value");
2030 return NC;
2031}
2032
2033NoCFIValue::NoCFIValue(GlobalValue *GV)
2034 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2035 setOperand(0, GV);
2036}
2037
2038/// Remove the constant from the constant table.
2039void NoCFIValue::destroyConstantImpl() {
2040 const GlobalValue *GV = getGlobalValue();
2041 GV->getContext().pImpl->NoCFIValues.erase(GV);
2042}
2043
2044Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2045 assert(From == getGlobalValue() && "Changing value does not match operand.");
2046
2047 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2048 assert(GV && "Can only replace the operands with a global value");
2049
2050 NoCFIValue *&NewNC = getContext().pImpl->NoCFIValues[GV];
2051 if (NewNC)
2052 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2053
2055 NewNC = this;
2056 setOperand(0, GV);
2057
2058 if (GV->getType() != getType())
2059 mutateType(GV->getType());
2060
2061 return nullptr;
2062}
2063
2064//---- ConstantPtrAuth::get() implementations.
2065//
2066
2068 ConstantInt *Disc, Constant *AddrDisc,
2069 Constant *DeactivationSymbol) {
2070 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc, DeactivationSymbol};
2071 ConstantPtrAuthKeyType MapKey(ArgVec);
2072 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2073 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2074}
2075
2076ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2077 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator(),
2079}
2080
2081ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2082 ConstantInt *Disc, Constant *AddrDisc,
2083 Constant *DeactivationSymbol)
2084 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2085 assert(Ptr->getType()->isPointerTy());
2086 assert(Key->getBitWidth() == 32);
2087 assert(Disc->getBitWidth() == 64);
2088 assert(AddrDisc->getType()->isPointerTy());
2089 assert(DeactivationSymbol->getType()->isPointerTy());
2090 setOperand(0, Ptr);
2091 setOperand(1, Key);
2092 setOperand(2, Disc);
2093 setOperand(3, AddrDisc);
2094 setOperand(4, DeactivationSymbol);
2095}
2096
2097/// Remove the constant from the constant table.
2098void ConstantPtrAuth::destroyConstantImpl() {
2099 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2100}
2101
2102Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2103 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2104 Constant *To = cast<Constant>(ToV);
2105
2106 SmallVector<Constant *, 4> Values;
2107 Values.reserve(getNumOperands());
2108
2109 unsigned NumUpdated = 0;
2110
2111 Use *OperandList = getOperandList();
2112 unsigned OperandNo = 0;
2113 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2114 Constant *Val = cast<Constant>(O->get());
2115 if (Val == From) {
2116 OperandNo = (O - OperandList);
2117 Val = To;
2118 ++NumUpdated;
2119 }
2120 Values.push_back(Val);
2121 }
2122
2123 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2124 Values, this, From, To, NumUpdated, OperandNo);
2125}
2126
2128 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2129 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2130 return false;
2131
2132 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2133 if (!IntVal)
2134 return false;
2135
2136 return IntVal->getValue() == Value;
2137}
2138
2140 const Value *Discriminator,
2141 const DataLayout &DL) const {
2142 // This function may only be validly called to analyze a ptrauth operation
2143 // with no deactivation symbol, so if we have one it isn't compatible.
2145 return false;
2146
2147 // If the keys are different, there's no chance for this to be compatible.
2148 if (getKey() != Key)
2149 return false;
2150
2151 // We can have 3 kinds of discriminators:
2152 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2153 // - address-only: `i64 0, ptr p` vs. `ptr p`
2154 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2155
2156 // If this constant has a simple discriminator (integer, no address), easy:
2157 // it's compatible iff the provided full discriminator is also a simple
2158 // discriminator, identical to our integer discriminator.
2160 return getDiscriminator() == Discriminator;
2161
2162 // Otherwise, we can isolate address and integer discriminator components.
2163 const Value *AddrDiscriminator = nullptr;
2164
2165 // This constant may or may not have an integer discriminator (instead of 0).
2166 if (!getDiscriminator()->isNullValue()) {
2167 // If it does, there's an implicit blend. We need to have a matching blend
2168 // intrinsic in the provided full discriminator.
2169 if (!match(Discriminator,
2171 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2172 return false;
2173 } else {
2174 // Otherwise, interpret the provided full discriminator as address-only.
2175 AddrDiscriminator = Discriminator;
2176 }
2177
2178 // Either way, we can now focus on comparing the address discriminators.
2179
2180 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2181 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2182 AddrDiscriminator = Cast->getPointerOperand();
2183
2184 // Beyond that, we're only interested in compatible pointers.
2185 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2186 return false;
2187
2188 // These are often the same constant GEP, making them trivially equivalent.
2189 if (getAddrDiscriminator() == AddrDiscriminator)
2190 return true;
2191
2192 // Finally, they may be equivalent base+offset expressions.
2193 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2195 DL, Off1, /*AllowNonInbounds=*/true);
2196
2197 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2198 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2199 DL, Off2, /*AllowNonInbounds=*/true);
2200
2201 return Base1 == Base2 && Off1 == Off2;
2202}
2203
2204//---- ConstantExpr::get() implementations.
2205//
2206
2207/// This is a utility function to handle folding of casts and lookup of the
2208/// cast in the ExprConstants map. It is used by the various get* methods below.
2210 bool OnlyIfReduced = false) {
2211 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2212 // Fold a few common cases
2213 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2214 return FC;
2215
2216 if (OnlyIfReduced)
2217 return nullptr;
2218
2219 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2220
2221 // Look up the constant in the table first to ensure uniqueness.
2223
2224 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2225}
2226
2228 bool OnlyIfReduced) {
2230 assert(Instruction::isCast(opc) && "opcode out of range");
2232 "Cast opcode not supported as constant expression");
2233 assert(C && Ty && "Null arguments to getCast");
2234 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2235
2236 switch (opc) {
2237 default:
2238 llvm_unreachable("Invalid cast opcode");
2239 case Instruction::Trunc:
2240 return getTrunc(C, Ty, OnlyIfReduced);
2241 case Instruction::PtrToAddr:
2242 return getPtrToAddr(C, Ty, OnlyIfReduced);
2243 case Instruction::PtrToInt:
2244 return getPtrToInt(C, Ty, OnlyIfReduced);
2245 case Instruction::IntToPtr:
2246 return getIntToPtr(C, Ty, OnlyIfReduced);
2247 case Instruction::BitCast:
2248 return getBitCast(C, Ty, OnlyIfReduced);
2249 case Instruction::AddrSpaceCast:
2250 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2251 }
2252}
2253
2255 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2256 return getBitCast(C, Ty);
2257 return getTrunc(C, Ty);
2258}
2259
2261 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2262 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2263 "Invalid cast");
2264
2265 if (Ty->isIntOrIntVectorTy())
2266 return getPtrToInt(S, Ty);
2267
2268 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2269 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2270 return getAddrSpaceCast(S, Ty);
2271
2272 return getBitCast(S, Ty);
2273}
2274
2276 Type *Ty) {
2277 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2278 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2279
2280 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2281 return getAddrSpaceCast(S, Ty);
2282
2283 return getBitCast(S, Ty);
2284}
2285
2286Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2287#ifndef NDEBUG
2288 bool fromVec = isa<VectorType>(C->getType());
2289 bool toVec = isa<VectorType>(Ty);
2290#endif
2291 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2292 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2293 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2294 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2295 "SrcTy must be larger than DestTy for Trunc!");
2296
2297 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2298}
2299
2301 bool OnlyIfReduced) {
2302 assert(C->getType()->isPtrOrPtrVectorTy() &&
2303 "PtrToAddr source must be pointer or pointer vector");
2304 assert(DstTy->isIntOrIntVectorTy() &&
2305 "PtrToAddr destination must be integer or integer vector");
2306 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2307 if (isa<VectorType>(C->getType()))
2308 assert(cast<VectorType>(C->getType())->getElementCount() ==
2309 cast<VectorType>(DstTy)->getElementCount() &&
2310 "Invalid cast between a different number of vector elements");
2311 return getFoldedCast(Instruction::PtrToAddr, C, DstTy, OnlyIfReduced);
2312}
2313
2315 bool OnlyIfReduced) {
2316 assert(C->getType()->isPtrOrPtrVectorTy() &&
2317 "PtrToInt source must be pointer or pointer vector");
2318 assert(DstTy->isIntOrIntVectorTy() &&
2319 "PtrToInt destination must be integer or integer vector");
2320 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2321 if (isa<VectorType>(C->getType()))
2322 assert(cast<VectorType>(C->getType())->getElementCount() ==
2323 cast<VectorType>(DstTy)->getElementCount() &&
2324 "Invalid cast between a different number of vector elements");
2325 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2326}
2327
2329 bool OnlyIfReduced) {
2330 assert(C->getType()->isIntOrIntVectorTy() &&
2331 "IntToPtr source must be integer or integer vector");
2332 assert(DstTy->isPtrOrPtrVectorTy() &&
2333 "IntToPtr destination must be a pointer or pointer vector");
2334 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2335 if (isa<VectorType>(C->getType()))
2336 assert(cast<VectorType>(C->getType())->getElementCount() ==
2337 cast<VectorType>(DstTy)->getElementCount() &&
2338 "Invalid cast between a different number of vector elements");
2339 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2340}
2341
2343 bool OnlyIfReduced) {
2344 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2345 "Invalid constantexpr bitcast!");
2346
2347 // It is common to ask for a bitcast of a value to its own type, handle this
2348 // speedily.
2349 if (C->getType() == DstTy) return C;
2350
2351 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2352}
2353
2355 bool OnlyIfReduced) {
2356 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2357 "Invalid constantexpr addrspacecast!");
2358 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2359}
2360
2361Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
2362 unsigned Flags, Type *OnlyIfReducedTy) {
2363 // Check the operands for consistency first.
2365 "Invalid opcode in binary constant expression");
2366 assert(isSupportedBinOp(Opcode) &&
2367 "Binop not supported as constant expression");
2368 assert(C1->getType() == C2->getType() &&
2369 "Operand types in binary constant expression should match");
2370
2371#ifndef NDEBUG
2372 switch (Opcode) {
2373 case Instruction::Add:
2374 case Instruction::Sub:
2375 case Instruction::Mul:
2377 "Tried to create an integer operation on a non-integer type!");
2378 break;
2379 case Instruction::And:
2380 case Instruction::Or:
2381 case Instruction::Xor:
2383 "Tried to create a logical operation on a non-integral type!");
2384 break;
2385 default:
2386 break;
2387 }
2388#endif
2389
2390 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2391 return FC;
2392
2393 if (OnlyIfReducedTy == C1->getType())
2394 return nullptr;
2395
2396 Constant *ArgVec[] = {C1, C2};
2397 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2398
2399 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2400 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2401}
2402
2403bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2404 switch (Opcode) {
2405 case Instruction::UDiv:
2406 case Instruction::SDiv:
2407 case Instruction::URem:
2408 case Instruction::SRem:
2409 case Instruction::FAdd:
2410 case Instruction::FSub:
2411 case Instruction::FMul:
2412 case Instruction::FDiv:
2413 case Instruction::FRem:
2414 case Instruction::And:
2415 case Instruction::Or:
2416 case Instruction::LShr:
2417 case Instruction::AShr:
2418 case Instruction::Shl:
2419 case Instruction::Mul:
2420 return false;
2421 case Instruction::Add:
2422 case Instruction::Sub:
2423 case Instruction::Xor:
2424 return true;
2425 default:
2426 llvm_unreachable("Argument must be binop opcode");
2427 }
2428}
2429
2430bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2431 switch (Opcode) {
2432 case Instruction::UDiv:
2433 case Instruction::SDiv:
2434 case Instruction::URem:
2435 case Instruction::SRem:
2436 case Instruction::FAdd:
2437 case Instruction::FSub:
2438 case Instruction::FMul:
2439 case Instruction::FDiv:
2440 case Instruction::FRem:
2441 case Instruction::And:
2442 case Instruction::Or:
2443 case Instruction::LShr:
2444 case Instruction::AShr:
2445 case Instruction::Shl:
2446 case Instruction::Mul:
2447 return false;
2448 case Instruction::Add:
2449 case Instruction::Sub:
2450 case Instruction::Xor:
2451 return true;
2452 default:
2453 llvm_unreachable("Argument must be binop opcode");
2454 }
2455}
2456
2457bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2458 switch (Opcode) {
2459 case Instruction::ZExt:
2460 case Instruction::SExt:
2461 case Instruction::FPTrunc:
2462 case Instruction::FPExt:
2463 case Instruction::UIToFP:
2464 case Instruction::SIToFP:
2465 case Instruction::FPToUI:
2466 case Instruction::FPToSI:
2467 return false;
2468 case Instruction::Trunc:
2469 case Instruction::PtrToAddr:
2470 case Instruction::PtrToInt:
2471 case Instruction::IntToPtr:
2472 case Instruction::BitCast:
2473 case Instruction::AddrSpaceCast:
2474 return true;
2475 default:
2476 llvm_unreachable("Argument must be cast opcode");
2477 }
2478}
2479
2480bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2481 switch (Opcode) {
2482 case Instruction::ZExt:
2483 case Instruction::SExt:
2484 case Instruction::FPTrunc:
2485 case Instruction::FPExt:
2486 case Instruction::UIToFP:
2487 case Instruction::SIToFP:
2488 case Instruction::FPToUI:
2489 case Instruction::FPToSI:
2490 return false;
2491 case Instruction::Trunc:
2492 case Instruction::PtrToAddr:
2493 case Instruction::PtrToInt:
2494 case Instruction::IntToPtr:
2495 case Instruction::BitCast:
2496 case Instruction::AddrSpaceCast:
2497 return true;
2498 default:
2499 llvm_unreachable("Argument must be cast opcode");
2500 }
2501}
2502
2504 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2505 // Note that a non-inbounds gep is used, as null isn't within any object.
2506 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2508 Ty, Constant::getNullValue(PointerType::getUnqual(Ty->getContext())),
2509 GEPIdx);
2510 return getPtrToInt(GEP,
2511 Type::getInt64Ty(Ty->getContext()));
2512}
2513
2515 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2516 // Note that a non-inbounds gep is used, as null isn't within any object.
2517 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2518 Constant *NullPtr =
2520 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2521 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2522 Constant *Indices[2] = {Zero, One};
2523 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2524 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2525}
2526
2528 ArrayRef<Value *> Idxs,
2529 GEPNoWrapFlags NW,
2530 std::optional<ConstantRange> InRange,
2531 Type *OnlyIfReducedTy) {
2532 assert(Ty && "Must specify element type");
2533 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2534
2535 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2536 return FC; // Fold a few common cases.
2537
2538 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2539 ;
2540
2541 // Get the result type of the getelementptr!
2543 if (OnlyIfReducedTy == ReqTy)
2544 return nullptr;
2545
2546 auto EltCount = ElementCount::getFixed(0);
2547 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2548 EltCount = VecTy->getElementCount();
2549
2550 // Look up the constant in the table first to ensure uniqueness
2551 std::vector<Constant*> ArgVec;
2552 ArgVec.reserve(1 + Idxs.size());
2553 ArgVec.push_back(C);
2554 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2555 for (; GTI != GTE; ++GTI) {
2556 auto *Idx = cast<Constant>(GTI.getOperand());
2557 assert(
2558 (!isa<VectorType>(Idx->getType()) ||
2559 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2560 "getelementptr index type missmatch");
2561
2562 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2563 Idx = Idx->getSplatValue();
2564 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2565 !Idx->getType()->isVectorTy()) {
2566 Idx = ConstantVector::getSplat(EltCount, Idx);
2567 }
2568 ArgVec.push_back(Idx);
2569 }
2570
2571 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2572 {}, Ty, InRange);
2573
2574 LLVMContextImpl *pImpl = C->getContext().pImpl;
2575 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2576}
2577
2579 Type *OnlyIfReducedTy) {
2580 assert(Val->getType()->isVectorTy() &&
2581 "Tried to create extractelement operation on non-vector type!");
2582 assert(Idx->getType()->isIntegerTy() &&
2583 "Extractelement index must be an integer type!");
2584
2586 return FC; // Fold a few common cases.
2587
2588 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2589 if (OnlyIfReducedTy == ReqTy)
2590 return nullptr;
2591
2592 // Look up the constant in the table first to ensure uniqueness
2593 Constant *ArgVec[] = { Val, Idx };
2594 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2595
2596 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2597 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2598}
2599
2601 Constant *Idx, Type *OnlyIfReducedTy) {
2602 assert(Val->getType()->isVectorTy() &&
2603 "Tried to create insertelement operation on non-vector type!");
2604 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2605 "Insertelement types must match!");
2606 assert(Idx->getType()->isIntegerTy() &&
2607 "Insertelement index must be i32 type!");
2608
2609 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2610 return FC; // Fold a few common cases.
2611
2612 if (OnlyIfReducedTy == Val->getType())
2613 return nullptr;
2614
2615 // Look up the constant in the table first to ensure uniqueness
2616 Constant *ArgVec[] = { Val, Elt, Idx };
2617 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2618
2619 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2620 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2621}
2622
2624 ArrayRef<int> Mask,
2625 Type *OnlyIfReducedTy) {
2627 "Invalid shuffle vector constant expr operands!");
2628
2629 if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
2630 return FC; // Fold a few common cases.
2631
2632 unsigned NElts = Mask.size();
2633 auto V1VTy = cast<VectorType>(V1->getType());
2634 Type *EltTy = V1VTy->getElementType();
2635 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2636 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2637
2638 if (OnlyIfReducedTy == ShufTy)
2639 return nullptr;
2640
2641 // Look up the constant in the table first to ensure uniqueness
2642 Constant *ArgVec[] = {V1, V2};
2643 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2644
2645 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2646 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2647}
2648
2650 assert(C->getType()->isIntOrIntVectorTy() &&
2651 "Cannot NEG a nonintegral value!");
2652 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2653}
2654
2656 assert(C->getType()->isIntOrIntVectorTy() &&
2657 "Cannot NOT a nonintegral value!");
2658 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2659}
2660
2662 bool HasNUW, bool HasNSW) {
2663 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2665 return get(Instruction::Add, C1, C2, Flags);
2666}
2667
2669 bool HasNUW, bool HasNSW) {
2670 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2672 return get(Instruction::Sub, C1, C2, Flags);
2673}
2674
2676 return get(Instruction::Xor, C1, C2);
2677}
2678
2680 Type *Ty = C->getType();
2681 const APInt *IVal;
2682 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2683 return ConstantInt::get(Ty, IVal->logBase2());
2684
2685 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2686 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2687 if (!VecTy)
2688 return nullptr;
2689
2691 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2692 Constant *Elt = C->getAggregateElement(I);
2693 if (!Elt)
2694 return nullptr;
2695 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2696 if (isa<UndefValue>(Elt)) {
2697 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2698 continue;
2699 }
2700 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2701 return nullptr;
2702 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2703 }
2704
2705 return ConstantVector::get(Elts);
2706}
2707
2709 bool AllowRHSConstant, bool NSZ) {
2710 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
2711
2712 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
2713 if (Instruction::isCommutative(Opcode)) {
2714 switch (Opcode) {
2715 case Instruction::Add: // X + 0 = X
2716 case Instruction::Or: // X | 0 = X
2717 case Instruction::Xor: // X ^ 0 = X
2718 return Constant::getNullValue(Ty);
2719 case Instruction::Mul: // X * 1 = X
2720 return ConstantInt::get(Ty, 1);
2721 case Instruction::And: // X & -1 = X
2722 return Constant::getAllOnesValue(Ty);
2723 case Instruction::FAdd: // X + -0.0 = X
2724 return ConstantFP::getZero(Ty, !NSZ);
2725 case Instruction::FMul: // X * 1.0 = X
2726 return ConstantFP::get(Ty, 1.0);
2727 default:
2728 llvm_unreachable("Every commutative binop has an identity constant");
2729 }
2730 }
2731
2732 // Non-commutative opcodes: AllowRHSConstant must be set.
2733 if (!AllowRHSConstant)
2734 return nullptr;
2735
2736 switch (Opcode) {
2737 case Instruction::Sub: // X - 0 = X
2738 case Instruction::Shl: // X << 0 = X
2739 case Instruction::LShr: // X >>u 0 = X
2740 case Instruction::AShr: // X >> 0 = X
2741 case Instruction::FSub: // X - 0.0 = X
2742 return Constant::getNullValue(Ty);
2743 case Instruction::SDiv: // X / 1 = X
2744 case Instruction::UDiv: // X /u 1 = X
2745 return ConstantInt::get(Ty, 1);
2746 case Instruction::FDiv: // X / 1.0 = X
2747 return ConstantFP::get(Ty, 1.0);
2748 default:
2749 return nullptr;
2750 }
2751}
2752
2754 switch (ID) {
2755 case Intrinsic::umax:
2756 return Constant::getNullValue(Ty);
2757 case Intrinsic::umin:
2758 return Constant::getAllOnesValue(Ty);
2759 case Intrinsic::smax:
2761 Ty, APInt::getSignedMinValue(Ty->getIntegerBitWidth()));
2762 case Intrinsic::smin:
2764 Ty, APInt::getSignedMaxValue(Ty->getIntegerBitWidth()));
2765 default:
2766 return nullptr;
2767 }
2768}
2769
2771 bool AllowRHSConstant, bool NSZ) {
2772 if (I->isBinaryOp())
2773 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
2775 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
2776 return nullptr;
2777}
2778
2780 bool AllowLHSConstant) {
2781 switch (Opcode) {
2782 default:
2783 break;
2784
2785 case Instruction::Or: // -1 | X = -1
2786 return Constant::getAllOnesValue(Ty);
2787
2788 case Instruction::And: // 0 & X = 0
2789 case Instruction::Mul: // 0 * X = 0
2790 return Constant::getNullValue(Ty);
2791 }
2792
2793 // AllowLHSConstant must be set.
2794 if (!AllowLHSConstant)
2795 return nullptr;
2796
2797 switch (Opcode) {
2798 default:
2799 return nullptr;
2800 case Instruction::Shl: // 0 << X = 0
2801 case Instruction::LShr: // 0 >>l X = 0
2802 case Instruction::AShr: // 0 >>a X = 0
2803 case Instruction::SDiv: // 0 /s X = 0
2804 case Instruction::UDiv: // 0 /u X = 0
2805 case Instruction::URem: // 0 %u X = 0
2806 case Instruction::SRem: // 0 %s X = 0
2807 return Constant::getNullValue(Ty);
2808 }
2809}
2810
2811/// Remove the constant from the constant table.
2812void ConstantExpr::destroyConstantImpl() {
2813 getType()->getContext().pImpl->ExprConstants.remove(this);
2814}
2815
2816const char *ConstantExpr::getOpcodeName() const {
2818}
2819
2820GetElementPtrConstantExpr::GetElementPtrConstantExpr(
2821 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
2822 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
2823 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
2824 SrcElementTy(SrcElementTy),
2825 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
2826 InRange(std::move(InRange)) {
2827 Op<0>() = C;
2828 Use *OperandList = getOperandList();
2829 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
2830 OperandList[i+1] = IdxList[i];
2831}
2832
2834 return SrcElementTy;
2835}
2836
2838 return ResElementTy;
2839}
2840
2841std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
2842 return InRange;
2843}
2844
2845//===----------------------------------------------------------------------===//
2846// ConstantData* implementations
2847
2850 return ATy->getElementType();
2851 return cast<VectorType>(getType())->getElementType();
2852}
2853
2857
2859 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
2860 return true;
2861 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
2862 switch (IT->getBitWidth()) {
2863 case 8:
2864 case 16:
2865 case 32:
2866 case 64:
2867 return true;
2868 default: break;
2869 }
2870 }
2871 return false;
2872}
2873
2876 return AT->getNumElements();
2877 return cast<FixedVectorType>(getType())->getNumElements();
2878}
2879
2883
2884/// Return the start of the specified element.
2885const char *ConstantDataSequential::getElementPointer(uint64_t Elt) const {
2886 assert(Elt < getNumElements() && "Invalid Elt");
2887 return DataElements + Elt * getElementByteSize();
2888}
2889
2890/// Return true if the array is empty or all zeros.
2891static bool isAllZeros(StringRef Arr) {
2892 for (char I : Arr)
2893 if (I != 0)
2894 return false;
2895 return true;
2896}
2897
2898/// This is the underlying implementation of all of the
2899/// ConstantDataSequential::get methods. They all thunk down to here, providing
2900/// the correct element type. We take the bytes in as a StringRef because
2901/// we *want* an underlying "char*" to avoid TBAA type punning violations.
2903#ifndef NDEBUG
2904 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
2905 assert(isElementTypeCompatible(ATy->getElementType()));
2906 else
2908#endif
2909 // If the elements are all zero or there are no elements, return a CAZ, which
2910 // is more dense and canonical.
2911 if (isAllZeros(Elements))
2912 return ConstantAggregateZero::get(Ty);
2913
2914 // Do a lookup to see if we have already formed one of these.
2915 auto &Slot =
2916 *Ty->getContext().pImpl->CDSConstants.try_emplace(Elements).first;
2917
2918 // The bucket can point to a linked list of different CDS's that have the same
2919 // body but different types. For example, 0,0,0,1 could be a 4 element array
2920 // of i8, or a 1-element array of i32. They'll both end up in the same
2921 /// StringMap bucket, linked up by their Next pointers. Walk the list.
2922 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
2923 for (; *Entry; Entry = &(*Entry)->Next)
2924 if ((*Entry)->getType() == Ty)
2925 return Entry->get();
2926
2927 // Okay, we didn't get a hit. Create a node of the right class, link it in,
2928 // and return it.
2929 if (isa<ArrayType>(Ty)) {
2930 // Use reset because std::make_unique can't access the constructor.
2931 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
2932 return Entry->get();
2933 }
2934
2936 // Use reset because std::make_unique can't access the constructor.
2937 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
2938 return Entry->get();
2939}
2940
2941void ConstantDataSequential::destroyConstantImpl() {
2942 // Remove the constant from the StringMap.
2945
2946 auto Slot = CDSConstants.find(getRawDataValues());
2947
2948 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
2949
2950 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
2951
2952 // Remove the entry from the hash table.
2953 if (!(*Entry)->Next) {
2954 // If there is only one value in the bucket (common case) it must be this
2955 // entry, and removing the entry should remove the bucket completely.
2956 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
2957 getContext().pImpl->CDSConstants.erase(Slot);
2958 return;
2959 }
2960
2961 // Otherwise, there are multiple entries linked off the bucket, unlink the
2962 // node we care about but keep the bucket around.
2963 while (true) {
2964 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
2965 assert(Node && "Didn't find entry in its uniquing hash table!");
2966 // If we found our entry, unlink it from the list and we're done.
2967 if (Node.get() == this) {
2968 Node = std::move(Node->Next);
2969 return;
2970 }
2971
2972 Entry = &Node->Next;
2973 }
2974}
2975
2976/// getFP() constructors - Return a constant of array type with a float
2977/// element type taken from argument `ElementType', and count taken from
2978/// argument `Elts'. The amount of bits of the contained type must match the
2979/// number of bits of the type contained in the passed in ArrayRef.
2980/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
2981/// that this can return a ConstantAggregateZero object.
2983 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
2984 "Element type is not a 16-bit float type");
2985 Type *Ty = ArrayType::get(ElementType, Elts.size());
2986 const char *Data = reinterpret_cast<const char *>(Elts.data());
2987 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
2988}
2990 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
2991 Type *Ty = ArrayType::get(ElementType, Elts.size());
2992 const char *Data = reinterpret_cast<const char *>(Elts.data());
2993 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
2994}
2996 assert(ElementType->isDoubleTy() &&
2997 "Element type is not a 64-bit float type");
2998 Type *Ty = ArrayType::get(ElementType, Elts.size());
2999 const char *Data = reinterpret_cast<const char *>(Elts.data());
3000 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3001}
3002
3004 StringRef Str, bool AddNull) {
3005 if (!AddNull) {
3006 const uint8_t *Data = Str.bytes_begin();
3007 return get(Context, ArrayRef(Data, Str.size()));
3008 }
3009
3010 SmallVector<uint8_t, 64> ElementVals;
3011 ElementVals.append(Str.begin(), Str.end());
3012 ElementVals.push_back(0);
3013 return get(Context, ElementVals);
3014}
3015
3016/// get() constructors - Return a constant with vector type with an element
3017/// count and element type matching the ArrayRef passed in. Note that this
3018/// can return a ConstantAggregateZero object.
3020 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3021 const char *Data = reinterpret_cast<const char *>(Elts.data());
3022 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3023}
3025 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3026 const char *Data = reinterpret_cast<const char *>(Elts.data());
3027 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3028}
3030 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3031 const char *Data = reinterpret_cast<const char *>(Elts.data());
3032 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3033}
3035 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3036 const char *Data = reinterpret_cast<const char *>(Elts.data());
3037 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3038}
3040 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3041 const char *Data = reinterpret_cast<const char *>(Elts.data());
3042 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3043}
3045 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3046 const char *Data = reinterpret_cast<const char *>(Elts.data());
3047 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3048}
3049
3050/// getFP() constructors - Return a constant of vector type with a float
3051/// element type taken from argument `ElementType', and count taken from
3052/// argument `Elts'. The amount of bits of the contained type must match the
3053/// number of bits of the type contained in the passed in ArrayRef.
3054/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3055/// that this can return a ConstantAggregateZero object.
3057 ArrayRef<uint16_t> Elts) {
3058 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3059 "Element type is not a 16-bit float type");
3060 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3061 const char *Data = reinterpret_cast<const char *>(Elts.data());
3062 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3063}
3065 ArrayRef<uint32_t> Elts) {
3066 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3067 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3068 const char *Data = reinterpret_cast<const char *>(Elts.data());
3069 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3070}
3072 ArrayRef<uint64_t> Elts) {
3073 assert(ElementType->isDoubleTy() &&
3074 "Element type is not a 64-bit float type");
3075 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3076 const char *Data = reinterpret_cast<const char *>(Elts.data());
3077 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3078}
3079
3081 assert(isElementTypeCompatible(V->getType()) &&
3082 "Element type not compatible with ConstantData");
3083 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3084 if (CI->getType()->isIntegerTy(8)) {
3085 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3086 return get(V->getContext(), Elts);
3087 }
3088 if (CI->getType()->isIntegerTy(16)) {
3089 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3090 return get(V->getContext(), Elts);
3091 }
3092 if (CI->getType()->isIntegerTy(32)) {
3093 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3094 return get(V->getContext(), Elts);
3095 }
3096 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3097 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3098 return get(V->getContext(), Elts);
3099 }
3100
3101 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3102 if (CFP->getType()->isHalfTy()) {
3104 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3105 return getFP(V->getType(), Elts);
3106 }
3107 if (CFP->getType()->isBFloatTy()) {
3109 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3110 return getFP(V->getType(), Elts);
3111 }
3112 if (CFP->getType()->isFloatTy()) {
3114 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3115 return getFP(V->getType(), Elts);
3116 }
3117 if (CFP->getType()->isDoubleTy()) {
3119 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3120 return getFP(V->getType(), Elts);
3121 }
3122 }
3124}
3125
3128 "Accessor can only be used when element is an integer");
3129 const char *EltPtr = getElementPointer(Elt);
3130
3131 // The data is stored in host byte order, make sure to cast back to the right
3132 // type to load with the right endianness.
3133 switch (getElementType()->getIntegerBitWidth()) {
3134 default: llvm_unreachable("Invalid bitwidth for CDS");
3135 case 8:
3136 return *reinterpret_cast<const uint8_t *>(EltPtr);
3137 case 16:
3138 return *reinterpret_cast<const uint16_t *>(EltPtr);
3139 case 32:
3140 return *reinterpret_cast<const uint32_t *>(EltPtr);
3141 case 64:
3142 return *reinterpret_cast<const uint64_t *>(EltPtr);
3143 }
3144}
3145
3148 "Accessor can only be used when element is an integer");
3149 const char *EltPtr = getElementPointer(Elt);
3150
3151 // The data is stored in host byte order, make sure to cast back to the right
3152 // type to load with the right endianness.
3153 switch (getElementType()->getIntegerBitWidth()) {
3154 default: llvm_unreachable("Invalid bitwidth for CDS");
3155 case 8: {
3156 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3157 return APInt(8, EltVal);
3158 }
3159 case 16: {
3160 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3161 return APInt(16, EltVal);
3162 }
3163 case 32: {
3164 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3165 return APInt(32, EltVal);
3166 }
3167 case 64: {
3168 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3169 return APInt(64, EltVal);
3170 }
3171 }
3172}
3173
3175 const char *EltPtr = getElementPointer(Elt);
3176
3177 switch (getElementType()->getTypeID()) {
3178 default:
3179 llvm_unreachable("Accessor can only be used when element is float/double!");
3180 case Type::HalfTyID: {
3181 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3182 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3183 }
3184 case Type::BFloatTyID: {
3185 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3186 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3187 }
3188 case Type::FloatTyID: {
3189 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3190 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3191 }
3192 case Type::DoubleTyID: {
3193 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3194 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3195 }
3196 }
3197}
3198
3200 assert(getElementType()->isFloatTy() &&
3201 "Accessor can only be used when element is a 'float'");
3202 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3203}
3204
3206 assert(getElementType()->isDoubleTy() &&
3207 "Accessor can only be used when element is a 'float'");
3208 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3209}
3210
3212 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3213 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3214 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3215
3216 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3217}
3218
3219bool ConstantDataSequential::isString(unsigned CharSize) const {
3220 return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
3221}
3222
3224 if (!isString())
3225 return false;
3226
3227 StringRef Str = getAsString();
3228
3229 // The last value must be nul.
3230 if (Str.back() != 0) return false;
3231
3232 // Other elements must be non-nul.
3233 return !Str.drop_back().contains(0);
3234}
3235
3236bool ConstantDataVector::isSplatData() const {
3237 const char *Base = getRawDataValues().data();
3238
3239 // Compare elements 1+ to the 0'th element.
3240 unsigned EltSize = getElementByteSize();
3241 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3242 if (memcmp(Base, Base+i*EltSize, EltSize))
3243 return false;
3244
3245 return true;
3246}
3247
3249 if (!IsSplatSet) {
3250 IsSplatSet = true;
3251 IsSplat = isSplatData();
3252 }
3253 return IsSplat;
3254}
3255
3257 // If they're all the same, return the 0th one as a representative.
3258 return isSplat() ? getElementAsConstant(0) : nullptr;
3259}
3260
3261//===----------------------------------------------------------------------===//
3262// handleOperandChange implementations
3263
3264/// Update this constant array to change uses of
3265/// 'From' to be uses of 'To'. This must update the uniquing data structures
3266/// etc.
3267///
3268/// Note that we intentionally replace all uses of From with To here. Consider
3269/// a large array that uses 'From' 1000 times. By handling this case all here,
3270/// ConstantArray::handleOperandChange is only invoked once, and that
3271/// single invocation handles all 1000 uses. Handling them one at a time would
3272/// work, but would be really slow because it would have to unique each updated
3273/// array instance.
3274///
3276 Value *Replacement = nullptr;
3277 switch (getValueID()) {
3278 default:
3279 llvm_unreachable("Not a constant!");
3280#define HANDLE_CONSTANT(Name) \
3281 case Value::Name##Val: \
3282 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3283 break;
3284#include "llvm/IR/Value.def"
3285 }
3286
3287 // If handleOperandChangeImpl returned nullptr, then it handled
3288 // replacing itself and we don't want to delete or replace anything else here.
3289 if (!Replacement)
3290 return;
3291
3292 // I do need to replace this with an existing value.
3293 assert(Replacement != this && "I didn't contain From!");
3294
3295 // Everyone using this now uses the replacement.
3296 replaceAllUsesWith(Replacement);
3297
3298 // Delete the old constant!
3300}
3301
3302Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3303 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3304 Constant *ToC = cast<Constant>(To);
3305
3307 Values.reserve(getNumOperands()); // Build replacement array.
3308
3309 // Fill values with the modified operands of the constant array. Also,
3310 // compute whether this turns into an all-zeros array.
3311 unsigned NumUpdated = 0;
3312
3313 // Keep track of whether all the values in the array are "ToC".
3314 bool AllSame = true;
3315 Use *OperandList = getOperandList();
3316 unsigned OperandNo = 0;
3317 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3318 Constant *Val = cast<Constant>(O->get());
3319 if (Val == From) {
3320 OperandNo = (O - OperandList);
3321 Val = ToC;
3322 ++NumUpdated;
3323 }
3324 Values.push_back(Val);
3325 AllSame &= Val == ToC;
3326 }
3327
3328 if (AllSame && ToC->isNullValue())
3330
3331 if (AllSame && isa<UndefValue>(ToC))
3332 return UndefValue::get(getType());
3333
3334 // Check for any other type of constant-folding.
3335 if (Constant *C = getImpl(getType(), Values))
3336 return C;
3337
3338 // Update to the new value.
3340 Values, this, From, ToC, NumUpdated, OperandNo);
3341}
3342
3343Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3344 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3345 Constant *ToC = cast<Constant>(To);
3346
3347 Use *OperandList = getOperandList();
3348
3350 Values.reserve(getNumOperands()); // Build replacement struct.
3351
3352 // Fill values with the modified operands of the constant struct. Also,
3353 // compute whether this turns into an all-zeros struct.
3354 unsigned NumUpdated = 0;
3355 bool AllSame = true;
3356 unsigned OperandNo = 0;
3357 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3358 Constant *Val = cast<Constant>(O->get());
3359 if (Val == From) {
3360 OperandNo = (O - OperandList);
3361 Val = ToC;
3362 ++NumUpdated;
3363 }
3364 Values.push_back(Val);
3365 AllSame &= Val == ToC;
3366 }
3367
3368 if (AllSame && ToC->isNullValue())
3370
3371 if (AllSame && isa<UndefValue>(ToC))
3372 return UndefValue::get(getType());
3373
3374 // Update to the new value.
3376 Values, this, From, ToC, NumUpdated, OperandNo);
3377}
3378
3379Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3380 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3381 Constant *ToC = cast<Constant>(To);
3382
3384 Values.reserve(getNumOperands()); // Build replacement array...
3385 unsigned NumUpdated = 0;
3386 unsigned OperandNo = 0;
3387 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3388 Constant *Val = getOperand(i);
3389 if (Val == From) {
3390 OperandNo = i;
3391 ++NumUpdated;
3392 Val = ToC;
3393 }
3394 Values.push_back(Val);
3395 }
3396
3397 if (Constant *C = getImpl(Values))
3398 return C;
3399
3400 // Update to the new value.
3402 Values, this, From, ToC, NumUpdated, OperandNo);
3403}
3404
3405Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3406 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3407 Constant *To = cast<Constant>(ToV);
3408
3410 unsigned NumUpdated = 0;
3411 unsigned OperandNo = 0;
3412 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3413 Constant *Op = getOperand(i);
3414 if (Op == From) {
3415 OperandNo = i;
3416 ++NumUpdated;
3417 Op = To;
3418 }
3419 NewOps.push_back(Op);
3420 }
3421 assert(NumUpdated && "I didn't contain From!");
3422
3423 if (Constant *C = getWithOperands(NewOps, getType(), true))
3424 return C;
3425
3426 // Update to the new value.
3427 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3428 NewOps, this, From, To, NumUpdated, OperandNo);
3429}
3430
3432 SmallVector<Value *, 4> ValueOperands(operands());
3433 ArrayRef<Value*> Ops(ValueOperands);
3434
3435 switch (getOpcode()) {
3436 case Instruction::Trunc:
3437 case Instruction::PtrToAddr:
3438 case Instruction::PtrToInt:
3439 case Instruction::IntToPtr:
3440 case Instruction::BitCast:
3441 case Instruction::AddrSpaceCast:
3443 getType(), "");
3444 case Instruction::InsertElement:
3445 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3446 case Instruction::ExtractElement:
3447 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3448 case Instruction::ShuffleVector:
3449 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3450
3451 case Instruction::GetElementPtr: {
3452 const auto *GO = cast<GEPOperator>(this);
3453 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3454 Ops.slice(1), GO->getNoWrapFlags(), "");
3455 }
3456 default:
3457 assert(getNumOperands() == 2 && "Must be binary operator?");
3459 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3465 }
3468 return BO;
3469 }
3470}
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 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 cl::opt< bool > UseConstantFPForScalableSplat("use-constant-fp-for-scalable-splat", cl::init(false), cl::Hidden, cl::desc("Use ConstantFP's native scalable vector splat support."))
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...
static cl::opt< bool > UseConstantFPForFixedLengthSplat("use-constant-fp-for-fixed-length-splat", cl::init(false), cl::Hidden, cl::desc("Use ConstantFP's native fixed-length vector splat support."))
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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)
Merge contiguous icmps into a memcmp
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 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:1183
static APFloat getSNaN(const fltSemantics &Sem, bool Negative=false, const APInt *payload=nullptr)
Factory for SNaN values.
Definition APFloat.h:1191
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:5975
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:6001
const fltSemantics & getSemantics() const
Definition APFloat.h:1520
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1161
static APFloat getNaN(const fltSemantics &Sem, bool Negative=false, uint64_t payload=0)
Factory for NaN values.
Definition APFloat.h:1172
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1142
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:1776
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:441
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
const T * data() const
Definition ArrayRef.h:139
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:696
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:904
static LLVM_ABI BlockAddress * lookup(const BasicBlock *BB)
Lookup an existing BlockAddress constant for the given BasicBlock.
BasicBlock * getBasicBlock() const
Definition Constants.h:939
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
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:364
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:413
LLVM_ABI ConstantAggregate(Type *T, ValueTy VT, ArrayRef< Constant * > V, AllocInfo AllocInfo)
ConstantArray - Constant Array Declarations.
Definition Constants.h:438
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
friend class Constant
Definition Constants.h:440
ArrayType * getType() const
Specialize the getType() method to always return an ArrayType, which reduces the amount of casting ne...
Definition Constants.h:457
An array constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:707
static LLVM_ABI Constant * getString(LLVMContext &Context, StringRef Initializer, bool AddNull=true)
This method constructs a CDS and initializes it with a text string.
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:720
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 ...
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:673
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.
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:781
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...
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:1130
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:1138
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:1131
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:1132
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:1412
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:1352
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:1284
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:1370
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:282
static LLVM_ABI Constant * getSNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
friend class Constant
Definition Constants.h:283
static LLVM_ABI Constant * getInfinity(Type *Ty, bool Negative=false)
static LLVM_ABI Constant * getZero(Type *Ty, bool Negative=false)
static LLVM_ABI Constant * getNaN(Type *Ty, bool Negative=false, uint64_t Payload=0)
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 Constant * getQNaN(Type *Ty, bool Negative=false, APInt *Payload=nullptr)
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:563
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
PointerType * getType() const
Specialize the getType() method to always return an PointerType, which reduces the amount of casting ...
Definition Constants.h:579
A signed pointer, in the ptrauth sense.
Definition Constants.h:1037
Constant * getAddrDiscriminator() const
The address discriminator if any, or the null constant.
Definition Constants.h:1078
friend struct ConstantPtrAuthKeyType
Definition Constants.h:1038
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:1039
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:1068
Constant * getDeactivationSymbol() const
Definition Constants.h:1087
bool hasAddressDiscriminator() const
Whether there is any non-null address discriminator.
Definition Constants.h:1083
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1071
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:472
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:509
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:892
A constant token which is empty.
Definition Constants.h:855
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:522
friend class Constant
Definition Constants.h:524
FixedVectorType * getType() const
Specialize the getType() method to always return a FixedVectorType, which reduces the amount of casti...
Definition Constants.h:545
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.
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.
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:56
LLVM_ABI bool isAllOnesValue() const
Return true if this is the value that would be returned by getAllOnesValue.
Definition Constants.cpp:91
Constant(Type *ty, ValueTy vty, AllocInfo AllocInfo)
Definition Constant.h:45
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 isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:74
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:957
GlobalValue * getGlobalValue() const
Definition Constants.h:978
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:802
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:318
A wrapper class for inspecting calls to intrinsic functions.
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntOneConstants
DenseMap< unsigned, std::unique_ptr< ConstantInt > > IntZeroConstants
DenseMap< APFloat, std::unique_ptr< ConstantFP > > FPConstants
DenseMap< PointerType *, std::unique_ptr< ConstantPointerNull > > CPNConstants
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
ArrayConstantsTy ArrayConstants
DenseMap< const GlobalValue *, DSOLocalEquivalent * > DSOLocalEquivalents
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:996
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:1020
GlobalValue * getGlobalValue() const
Definition Constants.h:1015
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:1493
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
friend class Constant
Definition Constants.h:1494
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
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
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:413
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:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:297
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:246
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
@ ArrayTyID
Arrays.
Definition Type.h:74
@ HalfTyID
16-bit floating point type
Definition Type.h:56
@ TargetExtTyID
Target extension type.
Definition Type.h:78
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:76
@ FloatTyID
32-bit floating point type
Definition Type.h:58
@ StructTyID
Structures.
Definition Type.h:73
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:70
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:75
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:57
@ DoubleTyID
64-bit floating point type
Definition Type.h:59
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:60
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:62
@ TokenTyID
Tokens.
Definition Type.h:67
@ PointerTyID
Pointers.
Definition Type.h:72
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:61
static LLVM_ABI Type * getFloatingPointTy(LLVMContext &C, const fltSemantics &S)
Definition Type.cpp:125
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:294
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:352
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:295
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:128
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:293
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
static LLVM_ABI Type * getDoubleTy(LLVMContext &C)
Definition Type.cpp:285
static LLVM_ABI Type * getFloatTy(LLVMContext &C)
Definition Type.cpp:284
'undef' values are things that do not have specified contents.
Definition Constants.h:1445
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:1446
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:256
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 subclass data that can be dropped.
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:712
LLVM_ABI const Value * stripInBoundsConstantOffsets() const
Strip off pointer casts and all-constant inbounds GEPs.
Definition Value.cpp:720
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
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:708
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:839
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))
class_match< Value > 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.
Definition Types.h:26
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:1739
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:2173
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:207
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:189
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt copy(R &&Range, OutputIt Out)
Definition STLExtras.h:1885
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:1917
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:870
#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