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