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