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