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