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
793 // Only constants other than globals can be dead users. Globals track whether
794 // they may have such users, which lets us skip walking the use list of a
795 // function that is only called.
796 const auto *GV = dyn_cast<GlobalValue>(this);
797 if (GV && !GV->mayHaveConstantUsers())
798 return;
799
800 bool HasLiveConstantUser = false;
802 Value::const_user_iterator LastNonDeadUser = E;
803 while (I != E) {
805 if (!User) {
806 LastNonDeadUser = I;
807 ++I;
808 continue;
809 }
810
811 if (!constantIsDead(User, /* RemoveDeadUsers= */ true)) {
812 // If the constant wasn't dead, remember that this was the last live use
813 // and move on to the next constant.
814 HasLiveConstantUser |= !isa<GlobalValue>(User);
815 LastNonDeadUser = I;
816 ++I;
817 continue;
818 }
819
820 // If the constant was dead, then the iterator is invalidated.
821 if (LastNonDeadUser == E)
822 I = user_begin();
823 else
824 I = std::next(LastNonDeadUser);
825 }
826
827 // Every remaining user is an instruction or a global, so later calls can
828 // return early until a new constant uses this global.
829 if (GV && !HasLiveConstantUser)
830 const_cast<GlobalValue *>(GV)->MayHaveConstantUsers = false;
831}
832
833bool Constant::hasOneLiveUse() const { return hasNLiveUses(1); }
834
835bool Constant::hasZeroLiveUses() const { return hasNLiveUses(0); }
836
837bool Constant::hasNLiveUses(unsigned N) const {
838 unsigned NumUses = 0;
839 for (const Use &U : uses()) {
840 const Constant *User = dyn_cast<Constant>(U.getUser());
841 if (!User || !constantIsDead(User, /* RemoveDeadUsers= */ false)) {
842 ++NumUses;
843
844 if (NumUses > N)
845 return false;
846 }
847 }
848 return NumUses == N;
849}
850
852 assert(C && Replacement && "Expected non-nullptr constant arguments");
853 Type *Ty = C->getType();
854 if (match(C, m_Undef())) {
855 assert(Ty == Replacement->getType() && "Expected matching types");
856 return Replacement;
857 }
858
859 // Don't know how to deal with this constant.
860 auto *VTy = dyn_cast<FixedVectorType>(Ty);
861 if (!VTy)
862 return C;
863
864 unsigned NumElts = VTy->getNumElements();
865 SmallVector<Constant *, 32> NewC(NumElts);
866 for (unsigned i = 0; i != NumElts; ++i) {
867 Constant *EltC = C->getAggregateElement(i);
868 assert((!EltC || EltC->getType() == Replacement->getType()) &&
869 "Expected matching types");
870 NewC[i] = EltC && match(EltC, m_Undef()) ? Replacement : EltC;
871 }
872 return ConstantVector::get(NewC);
873}
874
876 assert(C && Other && "Expected non-nullptr constant arguments");
877 if (match(C, m_Undef()))
878 return C;
879
880 Type *Ty = C->getType();
881 if (match(Other, m_Undef()))
882 return UndefValue::get(Ty);
883
884 auto *VTy = dyn_cast<FixedVectorType>(Ty);
885 if (!VTy)
886 return C;
887
888 Type *EltTy = VTy->getElementType();
889 unsigned NumElts = VTy->getNumElements();
890 assert(isa<FixedVectorType>(Other->getType()) &&
891 cast<FixedVectorType>(Other->getType())->getNumElements() == NumElts &&
892 "Type mismatch");
893
894 bool FoundExtraUndef = false;
895 SmallVector<Constant *, 32> NewC(NumElts);
896 for (unsigned I = 0; I != NumElts; ++I) {
897 NewC[I] = C->getAggregateElement(I);
898 Constant *OtherEltC = Other->getAggregateElement(I);
899 assert(NewC[I] && OtherEltC && "Unknown vector element");
900 if (!match(NewC[I], m_Undef()) && match(OtherEltC, m_Undef())) {
901 NewC[I] = UndefValue::get(EltTy);
902 FoundExtraUndef = true;
903 }
904 }
905 if (FoundExtraUndef)
906 return ConstantVector::get(NewC);
907 return C;
908}
909
911 if (isa<UndefValue>(this))
912 return false;
913 if (isa<ConstantData>(this))
914 return true;
915 if (isa<ConstantAggregate>(this) || isa<ConstantExpr>(this)) {
916 for (const Value *Op : operand_values())
918 return false;
919 return true;
920 }
921 return false;
922}
923
924//===----------------------------------------------------------------------===//
925// ConstantInt
926//===----------------------------------------------------------------------===//
927
928ConstantInt::ConstantInt(Type *Ty, const APInt &V)
929 : ConstantData(Ty, ConstantIntVal), Val(V) {
930 assert(V.getBitWidth() ==
931 cast<IntegerType>(Ty->getScalarType())->getBitWidth() &&
932 "Invalid constant for type");
933 if (V.isZero())
935}
936
937ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
938 LLVMContextImpl *pImpl = Context.pImpl;
939 if (!pImpl->TheTrueVal)
940 pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
941 return pImpl->TheTrueVal;
942}
943
944ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
945 LLVMContextImpl *pImpl = Context.pImpl;
946 if (!pImpl->TheFalseVal)
947 pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
948 return pImpl->TheFalseVal;
949}
950
951ConstantInt *ConstantInt::getBool(LLVMContext &Context, bool V) {
952 return V ? getTrue(Context) : getFalse(Context);
953}
954
956 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
957 ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
958 if (auto *VTy = dyn_cast<VectorType>(Ty))
959 return ConstantVector::getSplat(VTy->getElementCount(), TrueC);
960 return TrueC;
961}
962
964 assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
965 ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
966 if (auto *VTy = dyn_cast<VectorType>(Ty))
967 return ConstantVector::getSplat(VTy->getElementCount(), FalseC);
968 return FalseC;
969}
970
972 return V ? getTrue(Ty) : getFalse(Ty);
973}
974
975// Get a ConstantInt from an APInt.
976ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
977 // get an existing value or the insertion position
978 LLVMContextImpl *pImpl = Context.pImpl;
979 std::unique_ptr<ConstantInt> &Slot =
980 V.isZero() ? pImpl->IntZeroConstants[V.getBitWidth()]
981 : V.isOne() ? pImpl->IntOneConstants[V.getBitWidth()]
982 : pImpl->IntConstants[V];
983 if (!Slot) {
984 // Get the corresponding integer type for the bit width of the value.
985 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
986 Slot.reset(new ConstantInt(ITy, V));
987 }
988 assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
989 return Slot.get();
990}
991
992// Get a ConstantInt vector with each lane set to the same APInt.
993ConstantInt *ConstantInt::get(LLVMContext &Context, ElementCount EC,
994 const APInt &V) {
995 // Get an existing value or the insertion position.
996 std::unique_ptr<ConstantInt> &Slot =
997 Context.pImpl->IntSplatConstants[std::make_pair(EC, V)];
998 if (!Slot) {
999 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
1000 VectorType *VTy = VectorType::get(ITy, EC);
1001 Slot.reset(new ConstantInt(VTy, V));
1002 }
1003
1004#ifndef NDEBUG
1005 IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
1006 VectorType *VTy = VectorType::get(ITy, EC);
1007 assert(Slot->getType() == VTy);
1008#endif
1009 return Slot.get();
1010}
1011
1012Constant *ConstantInt::get(Type *Ty, uint64_t V, bool IsSigned,
1013 bool ImplicitTrunc) {
1014 Constant *C =
1015 get(cast<IntegerType>(Ty->getScalarType()), V, IsSigned, ImplicitTrunc);
1016
1017 // For vectors, broadcast the value.
1018 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1019 return ConstantVector::getSplat(VTy->getElementCount(), C);
1020
1021 return C;
1022}
1023
1024ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool IsSigned,
1025 bool ImplicitTrunc) {
1026 return get(Ty->getContext(),
1027 APInt(Ty->getBitWidth(), V, IsSigned, ImplicitTrunc));
1028}
1029
1030Constant *ConstantInt::get(Type *Ty, const APInt& V) {
1031 ConstantInt *C = get(Ty->getContext(), V);
1032 assert(C->getType() == Ty->getScalarType() &&
1033 "ConstantInt type doesn't match the type implied by its value!");
1034
1035 // For vectors, broadcast the value.
1036 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1037 return ConstantVector::getSplat(VTy->getElementCount(), C);
1038
1039 return C;
1040}
1041
1042ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
1043 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1044}
1045
1046/// Remove the constant from the constant table.
1047void ConstantInt::destroyConstantImpl() {
1048 llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
1049}
1050
1051//===----------------------------------------------------------------------===//
1052// ConstantByte
1053//===----------------------------------------------------------------------===//
1054
1055ConstantByte::ConstantByte(Type *Ty, const APInt &V)
1056 : ConstantData(Ty, ConstantByteVal), Val(V) {
1057 assert(V.getBitWidth() ==
1058 cast<ByteType>(Ty->getScalarType())->getBitWidth() &&
1059 "Invalid constant for type");
1060 if (V.isZero())
1062}
1063
1064// Get a ConstantByte from an APInt.
1065ConstantByte *ConstantByte::get(LLVMContext &Context, const APInt &V) {
1066 // get an existing value or the insertion position
1067 LLVMContextImpl *pImpl = Context.pImpl;
1068 std::unique_ptr<ConstantByte> &Slot =
1069 V.isZero() ? pImpl->ByteZeroConstants[V.getBitWidth()]
1070 : V.isOne() ? pImpl->ByteOneConstants[V.getBitWidth()]
1071 : pImpl->ByteConstants[V];
1072 if (!Slot) {
1073 // Get the corresponding byte type for the bit width of the value.
1074 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1075 Slot.reset(new ConstantByte(BTy, V));
1076 }
1077 assert(Slot->getType() == ByteType::get(Context, V.getBitWidth()));
1078 return Slot.get();
1079}
1080
1081// Get a ConstantByte vector with each lane set to the same APInt.
1082ConstantByte *ConstantByte::get(LLVMContext &Context, ElementCount EC,
1083 const APInt &V) {
1084 // Get an existing value or the insertion position.
1085 std::unique_ptr<ConstantByte> &Slot =
1086 Context.pImpl->ByteSplatConstants[std::make_pair(EC, V)];
1087 if (!Slot) {
1088 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1089 VectorType *VTy = VectorType::get(BTy, EC);
1090 Slot.reset(new ConstantByte(VTy, V));
1091 }
1092
1093#ifndef NDEBUG
1094 ByteType *BTy = ByteType::get(Context, V.getBitWidth());
1095 VectorType *VTy = VectorType::get(BTy, EC);
1096 assert(Slot->getType() == VTy);
1097#endif
1098 return Slot.get();
1099}
1100
1101Constant *ConstantByte::get(Type *Ty, uint64_t V, bool isSigned,
1102 bool ImplicitTrunc) {
1103 Constant *C =
1104 get(cast<ByteType>(Ty->getScalarType()), V, isSigned, ImplicitTrunc);
1105
1106 // For vectors, broadcast the value.
1107 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1108 return ConstantVector::getSplat(VTy->getElementCount(), C);
1109
1110 return C;
1111}
1112
1113ConstantByte *ConstantByte::get(ByteType *Ty, uint64_t V, bool isSigned,
1114 bool ImplicitTrunc) {
1115 return get(Ty->getContext(),
1116 APInt(Ty->getBitWidth(), V, isSigned, ImplicitTrunc));
1117}
1118
1119Constant *ConstantByte::get(Type *Ty, const APInt &V) {
1120 ConstantByte *C = get(Ty->getContext(), V);
1121 assert(C->getType() == Ty->getScalarType() &&
1122 "ConstantByte type doesn't match the type implied by its value!");
1123
1124 // For vectors, broadcast the value.
1125 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1126 return ConstantVector::getSplat(VTy->getElementCount(), C);
1127
1128 return C;
1129}
1130
1131ConstantByte *ConstantByte::get(ByteType *Ty, StringRef Str, uint8_t radix) {
1132 return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
1133}
1134
1135/// Remove the constant from the constant table.
1136void ConstantByte::destroyConstantImpl() {
1137 llvm_unreachable("You can't ConstantByte->destroyConstantImpl()!");
1138}
1139
1140//===----------------------------------------------------------------------===//
1141// ConstantFP
1142//===----------------------------------------------------------------------===//
1143
1144ConstantFP *ConstantFP::get(Type *Ty, double V) {
1145 LLVMContext &Context = Ty->getContext();
1146
1147 APFloat FV(V);
1148 bool ignored;
1149 FV.convert(Ty->getScalarType()->getFltSemantics(),
1151
1152 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1153 return get(Context, VTy->getElementCount(), FV);
1154
1155 return get(Context, FV);
1156}
1157
1158ConstantFP *ConstantFP::get(Type *Ty, const APFloat &V) {
1159 LLVMContext &Context = Ty->getContext();
1160 assert(Ty->getScalarType() ==
1161 Type::getFloatingPointTy(Context, V.getSemantics()) &&
1162 "ConstantFP type doesn't match the type implied by its value!");
1163
1164 if (auto *VTy = dyn_cast<VectorType>(Ty))
1165 return get(Context, VTy->getElementCount(), V);
1166
1167 return get(Ty->getContext(), V);
1168}
1169
1170ConstantFP *ConstantFP::get(Type *Ty, StringRef Str) {
1171 LLVMContext &Context = Ty->getContext();
1172 APFloat FV(Ty->getScalarType()->getFltSemantics(), Str);
1173
1174 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1175 return get(Context, VTy->getElementCount(), FV);
1176
1177 return get(Context, FV);
1178}
1179
1180ConstantFP *ConstantFP::getInfinity(Type *Ty, bool Negative) {
1181 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1182 return get(Ty, APFloat::getInf(Semantics, Negative));
1183}
1184
1185ConstantFP *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
1186 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1187 APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
1188 return get(Ty, NaN);
1189}
1190
1191ConstantFP *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
1192 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1193 APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
1194 return get(Ty, NaN);
1195}
1196
1197ConstantFP *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
1198 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1199 APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
1200 return get(Ty, NaN);
1201}
1202
1203ConstantFP *ConstantFP::getZero(Type *Ty, bool Negative) {
1204 const fltSemantics &Semantics = Ty->getScalarType()->getFltSemantics();
1205 APFloat NegZero = APFloat::getZero(Semantics, Negative);
1206 return get(Ty, NegZero);
1207}
1208
1209// ConstantFP accessors.
1210ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
1211 LLVMContextImpl* pImpl = Context.pImpl;
1212
1213 std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
1214
1215 if (!Slot) {
1216 Type *Ty = Type::getFloatingPointTy(Context, V.getSemantics());
1217 Slot.reset(new ConstantFP(Ty, V));
1218 }
1219
1220 return Slot.get();
1221}
1222
1223// Get a ConstantFP vector with each lane set to the same APFloat.
1224ConstantFP *ConstantFP::get(LLVMContext &Context, ElementCount EC,
1225 const APFloat &V) {
1226 // Get an existing value or the insertion position.
1227 std::unique_ptr<ConstantFP> &Slot =
1228 Context.pImpl->FPSplatConstants[std::make_pair(EC, V)];
1229 if (!Slot) {
1230 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1231 VectorType *VTy = VectorType::get(EltTy, EC);
1232 Slot.reset(new ConstantFP(VTy, V));
1233 }
1234
1235#ifndef NDEBUG
1236 Type *EltTy = Type::getFloatingPointTy(Context, V.getSemantics());
1237 VectorType *VTy = VectorType::get(EltTy, EC);
1238 assert(Slot->getType() == VTy);
1239#endif
1240 return Slot.get();
1241}
1242
1243ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
1244 : ConstantData(Ty, ConstantFPVal), Val(V) {
1245 assert(&V.getSemantics() == &Ty->getScalarType()->getFltSemantics() &&
1246 "FP type Mismatch");
1247 // ppc_fp128 determine isZero using high order double only
1248 // so check the bitwise value to make sure all bits are zero.
1249 if (V.bitcastToAPInt().isZero())
1251}
1252
1254 return Val.bitwiseIsEqual(V);
1255}
1256
1257/// Remove the constant from the constant table.
1258void ConstantFP::destroyConstantImpl() {
1259 llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
1260}
1261
1262//===----------------------------------------------------------------------===//
1263// ConstantAggregateZero Implementation
1264//===----------------------------------------------------------------------===//
1265
1267 if (auto *AT = dyn_cast<ArrayType>(getType()))
1268 return Constant::getNullValue(AT->getElementType());
1269 return Constant::getNullValue(cast<VectorType>(getType())->getElementType());
1270}
1271
1273 return Constant::getNullValue(getType()->getStructElementType(Elt));
1274}
1275
1281
1284 return getSequentialElement();
1285 return getStructElement(Idx);
1286}
1287
1289 Type *Ty = getType();
1290 if (auto *AT = dyn_cast<ArrayType>(Ty))
1291 return ElementCount::getFixed(AT->getNumElements());
1292 if (auto *VT = dyn_cast<VectorType>(Ty))
1293 return VT->getElementCount();
1294 return ElementCount::getFixed(Ty->getStructNumElements());
1295}
1296
1297//===----------------------------------------------------------------------===//
1298// UndefValue Implementation
1299//===----------------------------------------------------------------------===//
1300
1303 return UndefValue::get(ATy->getElementType());
1304 return UndefValue::get(cast<VectorType>(getType())->getElementType());
1305}
1306
1307UndefValue *UndefValue::getStructElement(unsigned Elt) const {
1308 return UndefValue::get(getType()->getStructElementType(Elt));
1309}
1310
1313 return getSequentialElement();
1314 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1315}
1316
1317UndefValue *UndefValue::getElementValue(unsigned Idx) const {
1319 return getSequentialElement();
1320 return getStructElement(Idx);
1321}
1322
1324 Type *Ty = getType();
1325 if (auto *AT = dyn_cast<ArrayType>(Ty))
1326 return AT->getNumElements();
1327 if (auto *VT = dyn_cast<VectorType>(Ty))
1328 return cast<FixedVectorType>(VT)->getNumElements();
1329 return Ty->getStructNumElements();
1330}
1331
1332//===----------------------------------------------------------------------===//
1333// PoisonValue Implementation
1334//===----------------------------------------------------------------------===//
1335
1338 return PoisonValue::get(ATy->getElementType());
1339 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1340}
1341
1342PoisonValue *PoisonValue::getStructElement(unsigned Elt) const {
1343 return PoisonValue::get(getType()->getStructElementType(Elt));
1344}
1345
1348 return getSequentialElement();
1349 return getStructElement(cast<ConstantInt>(C)->getZExtValue());
1350}
1351
1352PoisonValue *PoisonValue::getElementValue(unsigned Idx) const {
1354 return getSequentialElement();
1355 return getStructElement(Idx);
1356}
1357
1358//===----------------------------------------------------------------------===//
1359// ConstantXXX Classes
1360//===----------------------------------------------------------------------===//
1361
1362template <typename ItTy, typename EltTy>
1363static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
1364 for (; Start != End; ++Start)
1365 if (*Start != Elt)
1366 return false;
1367 return true;
1368}
1369
1370template <typename SequentialTy, typename ElementTy>
1372 assert(!V.empty() && "Cannot get empty int sequence.");
1373
1375 for (Constant *C : V)
1376 if (auto *CI = dyn_cast<ConstantInt>(C))
1377 Elts.push_back(CI->getZExtValue());
1378 else
1379 return nullptr;
1380 return SequentialTy::get(V[0]->getContext(), Elts);
1381}
1382
1383template <typename SequentialTy, typename ElementTy>
1385 assert(!V.empty() && "Cannot get empty byte sequence.");
1386
1388 for (Constant *C : V)
1389 if (auto *CI = dyn_cast<ConstantByte>(C))
1390 Elts.push_back(CI->getZExtValue());
1391 else
1392 return nullptr;
1393 return SequentialTy::getByte(V[0]->getType(), Elts);
1394}
1395
1396template <typename SequentialTy, typename ElementTy>
1398 assert(!V.empty() && "Cannot get empty FP sequence.");
1399
1401 for (Constant *C : V)
1402 if (auto *CFP = dyn_cast<ConstantFP>(C))
1403 Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
1404 else
1405 return nullptr;
1406 return SequentialTy::getFP(V[0]->getType(), Elts);
1407}
1408
1409template <typename SequenceTy>
1412 // We speculatively build the elements here even if it turns out that there is
1413 // a constantexpr or something else weird, since it is so uncommon for that to
1414 // happen.
1415 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
1416 if (CI->getType()->isIntegerTy(8))
1418 else if (CI->getType()->isIntegerTy(16))
1420 else if (CI->getType()->isIntegerTy(32))
1422 else if (CI->getType()->isIntegerTy(64))
1424 } else if (ConstantByte *CB = dyn_cast<ConstantByte>(C)) {
1425 if (CB->getType()->isByteTy(8))
1427 else if (CB->getType()->isByteTy(16))
1429 else if (CB->getType()->isByteTy(32))
1431 else if (CB->getType()->isByteTy(64))
1433 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
1434 if (CFP->getType()->isHalfTy() || CFP->getType()->isBFloatTy())
1436 else if (CFP->getType()->isFloatTy())
1438 else if (CFP->getType()->isDoubleTy())
1440 }
1441
1442 return nullptr;
1443}
1444
1448 : Constant(T, VT, AllocInfo) {
1449 llvm::copy(V, op_begin());
1450
1451 // Check that types match, unless this is an opaque struct.
1452 if (auto *ST = dyn_cast<StructType>(T)) {
1453 if (ST->isOpaque())
1454 return;
1455 for (unsigned I = 0, E = V.size(); I != E; ++I)
1456 assert(V[I]->getType() == ST->getTypeAtIndex(I) &&
1457 "Initializer for struct element doesn't match!");
1458 }
1459}
1460
1461ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V,
1463 : ConstantAggregate(T, ConstantArrayVal, V, AllocInfo) {
1464 assert(V.size() == T->getNumElements() &&
1465 "Invalid initializer for constant array");
1466}
1467
1469 if (Constant *C = getImpl(Ty, V))
1470 return C;
1471 return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
1472}
1473
1474Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
1475 // Empty arrays are canonicalized to ConstantAggregateZero.
1476 if (V.empty())
1477 return ConstantAggregateZero::get(Ty);
1478
1479 for (Constant *C : V) {
1480 assert(C->getType() == Ty->getElementType() &&
1481 "Wrong type in array element initializer");
1482 (void)C;
1483 }
1484
1485 // If this is an all-zero array, return a ConstantAggregateZero object. If
1486 // all undef, return an UndefValue, if "all simple", then return a
1487 // ConstantDataArray.
1488 Constant *C = V[0];
1489 if (isa<PoisonValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1490 return PoisonValue::get(Ty);
1491
1492 if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
1493 return UndefValue::get(Ty);
1494
1495 if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
1496 return ConstantAggregateZero::get(Ty);
1497
1498 // Check to see if all of the elements are ConstantFP or ConstantInt or
1499 // ConstantByte and if the element type is compatible with ConstantDataVector.
1500 // If so, use it.
1503
1504 // Otherwise, we really do want to create a ConstantArray.
1505 return nullptr;
1506}
1507
1510 bool Packed) {
1511 unsigned VecSize = V.size();
1512 SmallVector<Type*, 16> EltTypes(VecSize);
1513 for (unsigned i = 0; i != VecSize; ++i)
1514 EltTypes[i] = V[i]->getType();
1515
1516 return StructType::get(Context, EltTypes, Packed);
1517}
1518
1519
1521 bool Packed) {
1522 assert(!V.empty() &&
1523 "ConstantStruct::getTypeForElements cannot be called on empty list");
1524 return getTypeForElements(V[0]->getContext(), V, Packed);
1525}
1526
1527ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V,
1529 : ConstantAggregate(T, ConstantStructVal, V, AllocInfo) {
1530 assert((T->isOpaque() || V.size() == T->getNumElements()) &&
1531 "Invalid initializer for constant struct");
1532}
1533
1534// ConstantStruct accessors.
1536 assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
1537 "Incorrect # elements specified to ConstantStruct::get");
1538
1539 // Create a ConstantAggregateZero value if all elements are zeros.
1540 bool isZero = true;
1541 bool isUndef = false;
1542 bool isPoison = false;
1543
1544 if (!V.empty()) {
1545 isUndef = isa<UndefValue>(V[0]);
1546 isPoison = isa<PoisonValue>(V[0]);
1547 isZero = V[0]->isNullValue();
1548 // PoisonValue inherits UndefValue, so its check is not necessary.
1549 if (isUndef || isZero) {
1550 for (Constant *C : V) {
1551 if (!C->isNullValue())
1552 isZero = false;
1553 if (!isa<PoisonValue>(C))
1554 isPoison = false;
1556 isUndef = false;
1557 }
1558 }
1559 }
1560 if (isZero)
1561 return ConstantAggregateZero::get(ST);
1562 if (isPoison)
1563 return PoisonValue::get(ST);
1564 if (isUndef)
1565 return UndefValue::get(ST);
1566
1567 return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
1568}
1569
1570ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V,
1572 : ConstantAggregate(T, ConstantVectorVal, V, AllocInfo) {
1573 assert(V.size() == cast<FixedVectorType>(T)->getNumElements() &&
1574 "Invalid initializer for constant vector");
1575}
1576
1577// ConstantVector accessors.
1579 if (Constant *C = getImpl(V))
1580 return C;
1581 auto *Ty = FixedVectorType::get(V.front()->getType(), V.size());
1582 return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
1583}
1584
1585Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
1586 assert(!V.empty() && "Vectors can't be empty");
1587 auto *T = FixedVectorType::get(V.front()->getType(), V.size());
1588
1589 // If this is an all-undef or all-zero vector, return a
1590 // ConstantAggregateZero or UndefValue.
1591 Constant *C = V[0];
1592 bool isZero = C->isNullValue();
1593 bool isUndef = isa<UndefValue>(C);
1594 bool isPoison = isa<PoisonValue>(C);
1595 bool isSplatFP = isa<ConstantFP>(C);
1596 bool isSplatInt =
1598 getIROptions(C->getContext()).use_constant_int_for_fixed_length_splat;
1599 bool isSplatByte = isa<ConstantByte>(C);
1600 bool isSplatPtrNull = isa<ConstantPointerNull>(C);
1601
1602 if (isZero || isUndef || isSplatFP || isSplatInt || isSplatByte ||
1603 isSplatPtrNull) {
1604 for (unsigned i = 1, e = V.size(); i != e; ++i)
1605 if (V[i] != C) {
1606 isZero = isUndef = isPoison = isSplatFP = isSplatInt = isSplatByte =
1607 isSplatPtrNull = false;
1608 break;
1609 }
1610 }
1611
1612 if (isSplatPtrNull)
1614 if (isZero)
1616 if (isPoison)
1617 return PoisonValue::get(T);
1618 if (isUndef)
1619 return UndefValue::get(T);
1620 if (isSplatFP)
1621 return ConstantFP::get(C->getContext(), T->getElementCount(),
1622 cast<ConstantFP>(C)->getValue());
1623 if (isSplatInt)
1624 return ConstantInt::get(C->getContext(), T->getElementCount(),
1625 cast<ConstantInt>(C)->getValue());
1626 if (isSplatByte)
1627 return ConstantByte::get(C->getContext(), T->getElementCount(),
1628 cast<ConstantByte>(C)->getValue());
1629
1630 // Check to see if all of the elements are ConstantFP or ConstantInt and if
1631 // the element type is compatible with ConstantDataVector. If so, use it.
1634
1635 // Otherwise, the element type isn't compatible with ConstantDataVector, or
1636 // the operand list contains a ConstantExpr or something else strange.
1637 return nullptr;
1638}
1639
1641 if (isa<ConstantPointerNull>(V)) {
1642 VectorType *VTy = VectorType::get(V->getType(), EC);
1643 return ConstantPointerNull::get(VTy);
1644 }
1645
1646 if (auto *CB = dyn_cast<ConstantByte>(V))
1647 return ConstantByte::get(V->getContext(), EC, CB->getValue());
1648
1649 if (auto *CFP = dyn_cast<ConstantFP>(V))
1650 return ConstantFP::get(V->getContext(), EC, CFP->getValue());
1651
1652 if (!EC.isScalable()) {
1653 // Maintain special handling of zero.
1654 if (!V->isNullValue()) {
1655 if (isa<ConstantInt>(V) &&
1656 getIROptions(V->getContext()).use_constant_int_for_fixed_length_splat)
1657 return ConstantInt::get(V->getContext(), EC,
1658 cast<ConstantInt>(V)->getValue());
1659 }
1660
1661 // If this splat is compatible with ConstantDataVector, use it instead of
1662 // ConstantVector.
1663 if (isa<ConstantInt>(V) &&
1665 return ConstantDataVector::getSplat(EC.getKnownMinValue(), V);
1666
1667 SmallVector<Constant *, 32> Elts(EC.getKnownMinValue(), V);
1668 return get(Elts);
1669 }
1670
1671 // Maintain special handling of zero.
1672 if (!V->isNullValue()) {
1673 if (isa<ConstantInt>(V) &&
1674 getIROptions(V->getContext()).use_constant_int_for_scalable_splat)
1675 return ConstantInt::get(V->getContext(), EC,
1676 cast<ConstantInt>(V)->getValue());
1677 }
1678
1679 Type *VTy = VectorType::get(V->getType(), EC);
1680
1681 if (V->isNullValue())
1682 return ConstantAggregateZero::get(VTy);
1683 if (isa<PoisonValue>(V))
1684 return PoisonValue::get(VTy);
1685 if (isa<UndefValue>(V))
1686 return UndefValue::get(VTy);
1687
1688 Type *IdxTy = Type::getInt64Ty(VTy->getContext());
1689
1690 // Move scalar into vector.
1691 Constant *PoisonV = PoisonValue::get(VTy);
1692 V = ConstantExpr::getInsertElement(PoisonV, V, ConstantInt::get(IdxTy, 0));
1693 // Build shuffle mask to perform the splat.
1694 SmallVector<int, 8> Zeros(EC.getKnownMinValue(), 0);
1695 // Splat.
1696 return ConstantExpr::getShuffleVector(V, PoisonV, Zeros);
1697}
1698
1699ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
1700 LLVMContextImpl *pImpl = Context.pImpl;
1701 if (!pImpl->TheNoneToken)
1702 pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
1703 return pImpl->TheNoneToken.get();
1704}
1705
1706/// Remove the constant from the constant table.
1707void ConstantTokenNone::destroyConstantImpl() {
1708 llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
1709}
1710
1711// Utility function for determining if a ConstantExpr is a CastOp or not. This
1712// can't be inline because we don't want to #include Instruction.h into
1713// Constant.h
1715
1719
1721 return cast<ShuffleVectorConstantExpr>(this)->ShuffleMaskForBitcode;
1722}
1723
1725 bool OnlyIfReduced, Type *SrcTy) const {
1726 assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
1727
1728 // If no operands changed return self.
1729 if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
1730 return const_cast<ConstantExpr*>(this);
1731
1732 Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
1733 switch (getOpcode()) {
1734 case Instruction::Trunc:
1735 case Instruction::PtrToAddr:
1736 case Instruction::PtrToInt:
1737 case Instruction::IntToPtr:
1738 case Instruction::BitCast:
1739 case Instruction::AddrSpaceCast:
1740 return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
1741 case Instruction::InsertElement:
1742 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
1743 OnlyIfReducedTy);
1744 case Instruction::ExtractElement:
1745 return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
1746 case Instruction::ShuffleVector:
1748 OnlyIfReducedTy);
1749 case Instruction::GetElementPtr: {
1750 auto *GEPO = cast<GEPOperator>(this);
1751 assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
1754 SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
1755 GEPO->getNoWrapFlags(), GEPO->getInRange(), OnlyIfReducedTy);
1757 }
1758 default:
1759 assert(getNumOperands() == 2 && "Must be binary operator?");
1761 OnlyIfReducedTy);
1762 }
1763}
1764
1765
1766//===----------------------------------------------------------------------===//
1767// isValueValidForType implementations
1768
1770 unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
1771 if (Ty->isIntegerTy(1))
1772 return Val == 0 || Val == 1;
1773 return isUIntN(NumBits, Val);
1774}
1775
1777 unsigned NumBits = Ty->getIntegerBitWidth();
1778 if (Ty->isIntegerTy(1))
1779 return Val == 0 || Val == 1 || Val == -1;
1780 return isIntN(NumBits, Val);
1781}
1782
1784 // convert modifies in place, so make a copy.
1785 APFloat Val2 = APFloat(Val);
1786 bool losesInfo;
1787 switch (Ty->getTypeID()) {
1788 default:
1789 return false; // These can't be represented as floating point!
1790
1791 // FIXME rounding mode needs to be more flexible
1792 case Type::HalfTyID: {
1793 if (&Val2.getSemantics() == &APFloat::IEEEhalf())
1794 return true;
1796 return !losesInfo;
1797 }
1798 case Type::BFloatTyID: {
1799 if (&Val2.getSemantics() == &APFloat::BFloat())
1800 return true;
1802 return !losesInfo;
1803 }
1804 case Type::FloatTyID: {
1805 if (&Val2.getSemantics() == &APFloat::IEEEsingle())
1806 return true;
1808 return !losesInfo;
1809 }
1810 case Type::DoubleTyID: {
1811 if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
1812 &Val2.getSemantics() == &APFloat::BFloat() ||
1813 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1814 &Val2.getSemantics() == &APFloat::IEEEdouble())
1815 return true;
1817 return !losesInfo;
1818 }
1819 case Type::X86_FP80TyID:
1820 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1821 &Val2.getSemantics() == &APFloat::BFloat() ||
1822 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1823 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1825 case Type::FP128TyID:
1826 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1827 &Val2.getSemantics() == &APFloat::BFloat() ||
1828 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1829 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1830 &Val2.getSemantics() == &APFloat::IEEEquad();
1832 return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
1833 &Val2.getSemantics() == &APFloat::BFloat() ||
1834 &Val2.getSemantics() == &APFloat::IEEEsingle() ||
1835 &Val2.getSemantics() == &APFloat::IEEEdouble() ||
1837 }
1838}
1839
1840
1841//===----------------------------------------------------------------------===//
1842// Factory Function Implementation
1843
1844ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
1845 assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
1846 "Cannot create an aggregate zero of non-aggregate type!");
1847
1848 std::unique_ptr<ConstantAggregateZero> &Entry =
1849 Ty->getContext().pImpl->CAZConstants[Ty];
1850 if (!Entry)
1851 Entry.reset(new ConstantAggregateZero(Ty));
1852
1853 return Entry.get();
1854}
1855
1856/// Remove the constant from the constant table.
1857void ConstantAggregateZero::destroyConstantImpl() {
1859}
1860
1861/// Remove the constant from the constant table.
1862void ConstantArray::destroyConstantImpl() {
1864}
1865
1866
1867//---- ConstantStruct::get() implementation...
1868//
1869
1870/// Remove the constant from the constant table.
1871void ConstantStruct::destroyConstantImpl() {
1873}
1874
1875/// Remove the constant from the constant table.
1876void ConstantVector::destroyConstantImpl() {
1878}
1879
1880Constant *Constant::getSplatValue(bool AllowPoison) const {
1881 assert(this->getType()->isVectorTy() && "Only valid for vectors!");
1882 if (isa<PoisonValue>(this))
1883 return PoisonValue::get(cast<VectorType>(getType())->getElementType());
1885 return getNullValue(cast<VectorType>(getType())->getElementType());
1886 if (auto *CI = dyn_cast<ConstantInt>(this))
1887 return ConstantInt::get(getContext(), CI->getValue());
1888 if (auto *CB = dyn_cast<ConstantByte>(this))
1889 return ConstantByte::get(getContext(), CB->getValue());
1890 if (auto *CFP = dyn_cast<ConstantFP>(this))
1891 return ConstantFP::get(getContext(), CFP->getValue());
1892 if (auto *CPN = dyn_cast<ConstantPointerNull>(this))
1893 return ConstantPointerNull::get(CPN->getPointerType());
1895 return CV->getSplatValue();
1896 if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
1897 return CV->getSplatValue(AllowPoison);
1898
1899 // Check if this is a constant expression splat of the form returned by
1900 // ConstantVector::getSplat()
1901 const auto *Shuf = dyn_cast<ConstantExpr>(this);
1902 if (Shuf && Shuf->getOpcode() == Instruction::ShuffleVector &&
1903 isa<UndefValue>(Shuf->getOperand(1))) {
1904
1905 const auto *IElt = dyn_cast<ConstantExpr>(Shuf->getOperand(0));
1906 if (IElt && IElt->getOpcode() == Instruction::InsertElement &&
1907 isa<UndefValue>(IElt->getOperand(0))) {
1908
1909 ArrayRef<int> Mask = Shuf->getShuffleMask();
1910 Constant *SplatVal = IElt->getOperand(1);
1911 ConstantInt *Index = dyn_cast<ConstantInt>(IElt->getOperand(2));
1912
1913 if (Index && Index->getValue() == 0 && llvm::all_of(Mask, equal_to(0)))
1914 return SplatVal;
1915 }
1916 }
1917
1918 return nullptr;
1919}
1920
1921Constant *ConstantVector::getSplatValue(bool AllowPoison) const {
1922 // Check out first element.
1923 Constant *Elt = getOperand(0);
1924 // Then make sure all remaining elements point to the same value.
1925 for (unsigned I = 1, E = getNumOperands(); I < E; ++I) {
1926 Constant *OpC = getOperand(I);
1927 if (OpC == Elt)
1928 continue;
1929
1930 // Strict mode: any mismatch is not a splat.
1931 if (!AllowPoison)
1932 return nullptr;
1933
1934 // Allow poison mode: ignore poison elements.
1935 if (isa<PoisonValue>(OpC))
1936 continue;
1937
1938 // If we do not have a defined element yet, use the current operand.
1939 if (isa<PoisonValue>(Elt))
1940 Elt = OpC;
1941
1942 if (OpC != Elt)
1943 return nullptr;
1944 }
1945 return Elt;
1946}
1947
1949 if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
1950 return CI->getValue();
1951 if (const ConstantByte *CB = dyn_cast<ConstantByte>(this))
1952 return CB->getValue();
1953 // Scalable vectors can use a ConstantExpr to build a splat.
1954 if (isa<ConstantExpr>(this))
1955 return cast<ConstantInt>(this->getSplatValue())->getValue();
1956 // For non-ConstantExpr we use getAggregateElement as a fast path to avoid
1957 // calling getSplatValue in release builds.
1958 assert(this->getSplatValue() && "Doesn't contain a unique integer!");
1959 const Constant *C = this->getAggregateElement(0U);
1960 assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
1961 return cast<ConstantInt>(C)->getValue();
1962}
1963
1965 if (auto *CI = dyn_cast<ConstantInt>(this))
1966 return ConstantRange(CI->getValue());
1967
1968 unsigned BitWidth = getType()->getScalarSizeInBits();
1969 if (!getType()->isVectorTy())
1970 return ConstantRange::getFull(BitWidth);
1971
1972 if (auto *CI = dyn_cast_or_null<ConstantInt>(
1973 getSplatValue(/*AllowPoison=*/true)))
1974 return ConstantRange(CI->getValue());
1975
1976 if (auto *CB =
1977 dyn_cast_or_null<ConstantByte>(getSplatValue(/*AllowPoison=*/true)))
1978 return ConstantRange(CB->getValue());
1979
1980 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
1981 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1982 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
1983 CR = CR.unionWith(CDV->getElementAsAPInt(I));
1984 return CR;
1985 }
1986
1987 if (auto *CV = dyn_cast<ConstantVector>(this)) {
1988 ConstantRange CR = ConstantRange::getEmpty(BitWidth);
1989 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
1990 Constant *Elem = CV->getOperand(I);
1991 if (!Elem)
1992 return ConstantRange::getFull(BitWidth);
1993 if (isa<PoisonValue>(Elem))
1994 continue;
1995 auto *CI = dyn_cast<ConstantInt>(Elem);
1996 auto *CB = dyn_cast<ConstantByte>(Elem);
1997 if (!CI && !CB)
1998 return ConstantRange::getFull(BitWidth);
1999 CR = CR.unionWith(CI ? CI->getValue() : CB->getValue());
2000 }
2001 return CR;
2002 }
2003
2004 return ConstantRange::getFull(BitWidth);
2005}
2006
2008 if (auto *CFP = dyn_cast<ConstantFP>(this))
2009 return ConstantFPRange(CFP->getValue());
2010
2012 if (!getType()->isVectorTy())
2013 return ConstantFPRange::getFull(Sem);
2014
2015 if (auto *CFP =
2016 dyn_cast_or_null<ConstantFP>(getSplatValue(/*AllowPoison=*/true)))
2017 return ConstantFPRange(CFP->getValue());
2018
2019 if (auto *CDV = dyn_cast<ConstantDataVector>(this)) {
2020 ConstantFPRange CR = ConstantFPRange::getEmpty(Sem);
2021 for (unsigned I = 0, E = CDV->getNumElements(); I < E; ++I)
2022 CR = CR.unionWith(ConstantFPRange(CDV->getElementAsAPFloat(I)));
2023 return CR;
2024 }
2025
2026 if (auto *CV = dyn_cast<ConstantVector>(this)) {
2027 ConstantFPRange CR = ConstantFPRange::getEmpty(Sem);
2028 for (unsigned I = 0, E = CV->getNumOperands(); I < E; ++I) {
2029 Constant *Elem = CV->getOperand(I);
2030 if (!Elem)
2031 return ConstantFPRange::getFull(Sem);
2032 if (isa<PoisonValue>(Elem))
2033 continue;
2034 auto *CFP = dyn_cast<ConstantFP>(Elem);
2035 if (!CFP)
2036 return ConstantFPRange::getFull(Sem);
2037 CR = CR.unionWith(ConstantFPRange(CFP->getValue()));
2038 }
2039 return CR;
2040 }
2041
2042 return ConstantFPRange::getFull(Sem);
2043}
2044
2045//---- ConstantPointerNull::get() implementation.
2046//
2047
2048ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
2049 return get(static_cast<Type *>(Ty));
2050}
2051
2052ConstantPointerNull *ConstantPointerNull::get(Type *Ty) {
2053 assert(Ty->isPtrOrPtrVectorTy() && "invalid type for null pointer constant");
2054 std::unique_ptr<ConstantPointerNull> &Entry =
2055 Ty->getContext().pImpl->CPNConstants[Ty];
2056 if (!Entry)
2057 Entry.reset(new ConstantPointerNull(Ty));
2058
2059 assert(Entry->getType() == Ty);
2060 return Entry.get();
2061}
2062
2063/// Remove the constant from the constant table.
2064void ConstantPointerNull::destroyConstantImpl() {
2066}
2067
2068//---- ConstantTargetNone::get() implementation.
2069//
2070
2071ConstantTargetNone *ConstantTargetNone::get(TargetExtType *Ty) {
2072 assert(Ty->hasProperty(TargetExtType::HasZeroInit) &&
2073 "Target extension type not allowed to have a zeroinitializer");
2074 std::unique_ptr<ConstantTargetNone> &Entry =
2075 Ty->getContext().pImpl->CTNConstants[Ty];
2076 if (!Entry)
2077 Entry.reset(new ConstantTargetNone(Ty));
2078
2079 return Entry.get();
2080}
2081
2082/// Remove the constant from the constant table.
2083void ConstantTargetNone::destroyConstantImpl() {
2085}
2086
2087UndefValue *UndefValue::get(Type *Ty) {
2088 std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
2089 if (!Entry)
2090 Entry.reset(new UndefValue(Ty));
2091
2092 return Entry.get();
2093}
2094
2095/// Remove the constant from the constant table.
2096void UndefValue::destroyConstantImpl() {
2097 // Free the constant and any dangling references to it.
2098 if (getValueID() == UndefValueVal) {
2099 getContext().pImpl->UVConstants.erase(getType());
2100 } else if (getValueID() == PoisonValueVal) {
2101 getContext().pImpl->PVConstants.erase(getType());
2102 }
2103 llvm_unreachable("Not a undef or a poison!");
2104}
2105
2106PoisonValue *PoisonValue::get(Type *Ty) {
2107 std::unique_ptr<PoisonValue> &Entry = Ty->getContext().pImpl->PVConstants[Ty];
2108 if (!Entry)
2109 Entry.reset(new PoisonValue(Ty));
2110
2111 return Entry.get();
2112}
2113
2114/// Remove the constant from the constant table.
2115void PoisonValue::destroyConstantImpl() {
2116 // Free the constant and any dangling references to it.
2117 getContext().pImpl->PVConstants.erase(getType());
2118}
2119
2120BlockAddress *BlockAddress::get(Type *Ty, BasicBlock *BB) {
2121 BlockAddress *&BA = BB->getContext().pImpl->BlockAddresses[BB];
2122 if (!BA)
2123 BA = new BlockAddress(Ty, BB);
2124 return BA;
2125}
2126
2127BlockAddress *BlockAddress::get(BasicBlock *BB) {
2128 assert(BB->getParent() && "Block must have a parent");
2129 return get(BB->getParent()->getType(), BB);
2130}
2131
2133 assert(BB->getParent() == F && "Block not part of specified function");
2134 return get(BB->getParent()->getType(), BB);
2135}
2136
2137BlockAddress::BlockAddress(Type *Ty, BasicBlock *BB)
2138 : Constant(Ty, Value::BlockAddressVal, AllocMarker) {
2139 Block = BB;
2140 BB->setHasAddressTaken(true);
2141}
2142
2143BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
2144 if (!BB->hasAddressTaken())
2145 return nullptr;
2146
2147 BlockAddress *BA = BB->getContext().pImpl->BlockAddresses.lookup(BB);
2148 assert(BA && "Refcount and block address map disagree!");
2149 return BA;
2150}
2151
2152/// Remove the constant from the constant table.
2153void BlockAddress::destroyConstantImpl() {
2155 getBasicBlock()->setHasAddressTaken(false);
2156}
2157
2158Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
2159 assert(From == getBasicBlock());
2160 BasicBlock *NewBB = cast<BasicBlock>(To);
2161
2162 // See if the 'new' entry already exists, if not, just update this in place
2163 // and return early.
2164 if (BlockAddress *NewBA = getContext().pImpl->BlockAddresses.lookup(NewBB))
2165 return NewBA;
2166
2167 getBasicBlock()->setHasAddressTaken(false);
2168
2169 // erase invalidates iterators/references, hence the duplicate NewBB lookup.
2171 getContext().pImpl->BlockAddresses[NewBB] = this;
2172 Block = NewBB;
2173 getBasicBlock()->setHasAddressTaken(true);
2174
2175 // If we just want to keep the existing value, then return null.
2176 // Callers know that this means we shouldn't delete this value.
2177 return nullptr;
2178}
2179
2180DSOLocalEquivalent *DSOLocalEquivalent::get(GlobalValue *GV) {
2181 DSOLocalEquivalent *&Equiv = GV->getContext().pImpl->DSOLocalEquivalents[GV];
2182 if (!Equiv)
2183 Equiv = new DSOLocalEquivalent(GV);
2184
2185 assert(Equiv->getGlobalValue() == GV &&
2186 "DSOLocalFunction does not match the expected global value");
2187 return Equiv;
2188}
2189
2190DSOLocalEquivalent::DSOLocalEquivalent(GlobalValue *GV)
2191 : Constant(GV->getType(), Value::DSOLocalEquivalentVal, AllocMarker) {
2192 setOperand(0, GV);
2194}
2195
2196/// Remove the constant from the constant table.
2197void DSOLocalEquivalent::destroyConstantImpl() {
2198 const GlobalValue *GV = getGlobalValue();
2199 GV->getContext().pImpl->DSOLocalEquivalents.erase(GV);
2200}
2201
2202Value *DSOLocalEquivalent::handleOperandChangeImpl(Value *From, Value *To) {
2203 assert(From == getGlobalValue() && "Changing value does not match operand.");
2204 assert(isa<Constant>(To) && "Can only replace the operands with a constant");
2205
2206 // If the argument is replaced with a null value, just replace this constant
2207 // with a null value.
2209 return To;
2210
2211 // The replacement could be a bitcast to another GlobalValue. We can
2212 // replace it with a bitcast to the dso_local_equivalent of that GV.
2213 GlobalValue *GV = cast<GlobalValue>(To->stripPointerCasts());
2214 if (DSOLocalEquivalent *NewEquiv =
2215 getContext().pImpl->DSOLocalEquivalents.lookup(GV))
2216 return llvm::ConstantExpr::getBitCast(NewEquiv, getType());
2217
2218 // erase invalidates iterators/references, hence the duplicate GV lookup.
2220 getContext().pImpl->DSOLocalEquivalents[GV] = this;
2221 setOperand(0, GV);
2223
2224 if (GV->getType() != getType()) {
2225 // It is ok to mutate the type here because this constant should always
2226 // reflect the type of the function it's holding.
2227 mutateType(GV->getType());
2228 }
2229 return nullptr;
2230}
2231
2233 NoCFIValue *&NC = GV->getContext().pImpl->NoCFIValues[GV];
2234 if (!NC)
2235 NC = new NoCFIValue(GV);
2236
2237 assert(NC->getGlobalValue() == GV &&
2238 "NoCFIValue does not match the expected global value");
2239 return NC;
2240}
2241
2242NoCFIValue::NoCFIValue(GlobalValue *GV)
2243 : Constant(GV->getType(), Value::NoCFIValueVal, AllocMarker) {
2244 setOperand(0, GV);
2246}
2247
2248/// Remove the constant from the constant table.
2249void NoCFIValue::destroyConstantImpl() {
2250 const GlobalValue *GV = getGlobalValue();
2251 GV->getContext().pImpl->NoCFIValues.erase(GV);
2252}
2253
2254Value *NoCFIValue::handleOperandChangeImpl(Value *From, Value *To) {
2255 assert(From == getGlobalValue() && "Changing value does not match operand.");
2256
2257 GlobalValue *GV = dyn_cast<GlobalValue>(To->stripPointerCasts());
2258 assert(GV && "Can only replace the operands with a global value");
2259
2260 if (NoCFIValue *NewNC = getContext().pImpl->NoCFIValues.lookup(GV))
2261 return llvm::ConstantExpr::getBitCast(NewNC, getType());
2262
2263 // erase invalidates iterators/references, hence the duplicate GV lookup.
2265 getContext().pImpl->NoCFIValues[GV] = this;
2266 setOperand(0, GV);
2268
2269 if (GV->getType() != getType())
2270 mutateType(GV->getType());
2271
2272 return nullptr;
2273}
2274
2275//---- ConstantPtrAuth::get() implementations.
2276//
2277
2279 ConstantInt *Disc, Constant *AddrDisc,
2280 Constant *DeactivationSymbol) {
2281 Constant *ArgVec[] = {Ptr, Key, Disc, AddrDisc, DeactivationSymbol};
2282 ConstantPtrAuthKeyType MapKey(ArgVec);
2283 LLVMContextImpl *pImpl = Ptr->getContext().pImpl;
2284 return pImpl->ConstantPtrAuths.getOrCreate(Ptr->getType(), MapKey);
2285}
2286
2287ConstantPtrAuth *ConstantPtrAuth::getWithSameSchema(Constant *Pointer) const {
2288 return get(Pointer, getKey(), getDiscriminator(), getAddrDiscriminator(),
2290}
2291
2292ConstantPtrAuth::ConstantPtrAuth(Constant *Ptr, ConstantInt *Key,
2293 ConstantInt *Disc, Constant *AddrDisc,
2294 Constant *DeactivationSymbol)
2295 : Constant(Ptr->getType(), Value::ConstantPtrAuthVal, AllocMarker) {
2296 assert(Ptr->getType()->isPointerTy());
2297 assert(Key->getBitWidth() == 32);
2298 assert(Disc->getBitWidth() == 64);
2299 assert(AddrDisc->getType()->isPointerTy());
2300 assert(DeactivationSymbol->getType()->isPointerTy());
2301 setOperand(0, Ptr);
2302 setOperand(1, Key);
2303 setOperand(2, Disc);
2304 setOperand(3, AddrDisc);
2305 setOperand(4, DeactivationSymbol);
2306}
2307
2308/// Remove the constant from the constant table.
2309void ConstantPtrAuth::destroyConstantImpl() {
2310 getType()->getContext().pImpl->ConstantPtrAuths.remove(this);
2311}
2312
2313Value *ConstantPtrAuth::handleOperandChangeImpl(Value *From, Value *ToV) {
2314 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
2315 Constant *To = cast<Constant>(ToV);
2316
2317 SmallVector<Constant *, 4> Values;
2318 Values.reserve(getNumOperands());
2319
2320 unsigned NumUpdated = 0;
2321
2322 Use *OperandList = getOperandList();
2323 unsigned OperandNo = 0;
2324 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
2325 Constant *Val = cast<Constant>(O->get());
2326 if (Val == From) {
2327 OperandNo = (O - OperandList);
2328 Val = To;
2329 ++NumUpdated;
2330 }
2331 Values.push_back(Val);
2332 }
2333
2334 return getContext().pImpl->ConstantPtrAuths.replaceOperandsInPlace(
2335 Values, this, From, To, NumUpdated, OperandNo);
2336}
2337
2339 const auto *CastV = dyn_cast<ConstantExpr>(getAddrDiscriminator());
2340 if (!CastV || CastV->getOpcode() != Instruction::IntToPtr)
2341 return false;
2342
2343 const auto *IntVal = dyn_cast<ConstantInt>(CastV->getOperand(0));
2344 if (!IntVal)
2345 return false;
2346
2347 return IntVal->getValue() == Value;
2348}
2349
2351 const Value *Discriminator,
2352 const DataLayout &DL) const {
2353 // This function may only be validly called to analyze a ptrauth operation
2354 // with no deactivation symbol, so if we have one it isn't compatible.
2356 return false;
2357
2358 // If the keys are different, there's no chance for this to be compatible.
2359 if (getKey() != Key)
2360 return false;
2361
2362 // We can have 3 kinds of discriminators:
2363 // - simple, integer-only: `i64 x, ptr null` vs. `i64 x`
2364 // - address-only: `i64 0, ptr p` vs. `ptr p`
2365 // - blended address/integer: `i64 x, ptr p` vs. `@llvm.ptrauth.blend(p, x)`
2366
2367 // If this constant has a simple discriminator (integer, no address), easy:
2368 // it's compatible iff the provided full discriminator is also a simple
2369 // discriminator, identical to our integer discriminator.
2371 return getDiscriminator() == Discriminator;
2372
2373 // Otherwise, we can isolate address and integer discriminator components.
2374 const Value *AddrDiscriminator = nullptr;
2375
2376 // This constant may or may not have an integer discriminator (instead of 0).
2377 if (!getDiscriminator()->isNullValue()) {
2378 // If it does, there's an implicit blend. We need to have a matching blend
2379 // intrinsic in the provided full discriminator.
2380 if (!match(Discriminator,
2382 m_Value(AddrDiscriminator), m_Specific(getDiscriminator()))))
2383 return false;
2384 } else {
2385 // Otherwise, interpret the provided full discriminator as address-only.
2386 AddrDiscriminator = Discriminator;
2387 }
2388
2389 // Either way, we can now focus on comparing the address discriminators.
2390
2391 // Discriminators are i64, so the provided addr disc may be a ptrtoint.
2392 if (auto *Cast = dyn_cast<PtrToIntOperator>(AddrDiscriminator))
2393 AddrDiscriminator = Cast->getPointerOperand();
2394
2395 // Beyond that, we're only interested in compatible pointers.
2396 if (getAddrDiscriminator()->getType() != AddrDiscriminator->getType())
2397 return false;
2398
2399 // These are often the same constant GEP, making them trivially equivalent.
2400 if (getAddrDiscriminator() == AddrDiscriminator)
2401 return true;
2402
2403 // Finally, they may be equivalent base+offset expressions.
2404 APInt Off1(DL.getIndexTypeSizeInBits(getAddrDiscriminator()->getType()), 0);
2406 DL, Off1, /*AllowNonInbounds=*/true);
2407
2408 APInt Off2(DL.getIndexTypeSizeInBits(AddrDiscriminator->getType()), 0);
2409 auto *Base2 = AddrDiscriminator->stripAndAccumulateConstantOffsets(
2410 DL, Off2, /*AllowNonInbounds=*/true);
2411
2412 return Base1 == Base2 && Off1 == Off2;
2413}
2414
2415//---- ConstantExpr::get() implementations.
2416//
2417
2418/// This is a utility function to handle folding of casts and lookup of the
2419/// cast in the ExprConstants map. It is used by the various get* methods below.
2421 bool OnlyIfReduced = false) {
2422 assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
2423 // Fold a few common cases
2424 if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
2425 return FC;
2426
2427 if (OnlyIfReduced)
2428 return nullptr;
2429
2430 LLVMContextImpl *pImpl = Ty->getContext().pImpl;
2431
2432 // Look up the constant in the table first to ensure uniqueness.
2434
2435 return pImpl->ExprConstants.getOrCreate(Ty, Key);
2436}
2437
2439 bool OnlyIfReduced) {
2441 assert(Instruction::isCast(opc) && "opcode out of range");
2443 "Cast opcode not supported as constant expression");
2444 assert(C && Ty && "Null arguments to getCast");
2445 assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
2446
2447 switch (opc) {
2448 default:
2449 llvm_unreachable("Invalid cast opcode");
2450 case Instruction::Trunc:
2451 return getTrunc(C, Ty, OnlyIfReduced);
2452 case Instruction::PtrToAddr:
2453 return getPtrToAddr(C, Ty, OnlyIfReduced);
2454 case Instruction::PtrToInt:
2455 return getPtrToInt(C, Ty, OnlyIfReduced);
2456 case Instruction::IntToPtr:
2457 return getIntToPtr(C, Ty, OnlyIfReduced);
2458 case Instruction::BitCast:
2459 return getBitCast(C, Ty, OnlyIfReduced);
2460 case Instruction::AddrSpaceCast:
2461 return getAddrSpaceCast(C, Ty, OnlyIfReduced);
2462 }
2463}
2464
2466 if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2467 return getBitCast(C, Ty);
2468 return getTrunc(C, Ty);
2469}
2470
2472 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2473 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2474 "Invalid cast");
2475
2476 if (Ty->isIntOrIntVectorTy())
2477 return getPtrToInt(S, Ty);
2478
2479 unsigned SrcAS = S->getType()->getPointerAddressSpace();
2480 if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
2481 return getAddrSpaceCast(S, Ty);
2482
2483 return getBitCast(S, Ty);
2484}
2485
2487 Type *Ty) {
2488 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2489 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2490
2491 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2492 return getAddrSpaceCast(S, Ty);
2493
2494 return getBitCast(S, Ty);
2495}
2496
2497Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
2498#ifndef NDEBUG
2499 bool fromVec = isa<VectorType>(C->getType());
2500 bool toVec = isa<VectorType>(Ty);
2501#endif
2502 assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
2503 assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
2504 assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
2505 assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
2506 "SrcTy must be larger than DestTy for Trunc!");
2507
2508 return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
2509}
2510
2512 bool OnlyIfReduced) {
2513 assert(C->getType()->isPtrOrPtrVectorTy() &&
2514 "PtrToAddr source must be pointer or pointer vector");
2515 assert(DstTy->isIntOrIntVectorTy() &&
2516 "PtrToAddr destination must be integer or integer vector");
2517 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2518 if (isa<VectorType>(C->getType()))
2519 assert(cast<VectorType>(C->getType())->getElementCount() ==
2520 cast<VectorType>(DstTy)->getElementCount() &&
2521 "Invalid cast between a different number of vector elements");
2522 return getFoldedCast(Instruction::PtrToAddr, C, DstTy, OnlyIfReduced);
2523}
2524
2526 bool OnlyIfReduced) {
2527 assert(C->getType()->isPtrOrPtrVectorTy() &&
2528 "PtrToInt source must be pointer or pointer vector");
2529 assert(DstTy->isIntOrIntVectorTy() &&
2530 "PtrToInt destination must be integer or integer vector");
2531 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2532 if (isa<VectorType>(C->getType()))
2533 assert(cast<VectorType>(C->getType())->getElementCount() ==
2534 cast<VectorType>(DstTy)->getElementCount() &&
2535 "Invalid cast between a different number of vector elements");
2536 return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
2537}
2538
2540 bool OnlyIfReduced) {
2541 assert(C->getType()->isIntOrIntVectorTy() &&
2542 "IntToPtr source must be integer or integer vector");
2543 assert(DstTy->isPtrOrPtrVectorTy() &&
2544 "IntToPtr destination must be a pointer or pointer vector");
2545 assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
2546 if (isa<VectorType>(C->getType()))
2547 assert(cast<VectorType>(C->getType())->getElementCount() ==
2548 cast<VectorType>(DstTy)->getElementCount() &&
2549 "Invalid cast between a different number of vector elements");
2550 return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
2551}
2552
2554 bool OnlyIfReduced) {
2555 assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
2556 "Invalid constantexpr bitcast!");
2557
2558 // It is common to ask for a bitcast of a value to its own type, handle this
2559 // speedily.
2560 if (C->getType() == DstTy) return C;
2561
2562 return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
2563}
2564
2566 bool OnlyIfReduced) {
2567 assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
2568 "Invalid constantexpr addrspacecast!");
2569 return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
2570}
2571
2573 unsigned Flags, Type *OnlyIfReducedTy) {
2574 // Check the operands for consistency first.
2576 "Invalid opcode in binary constant expression");
2577 assert(isSupportedBinOp(Opcode) &&
2578 "Binop not supported as constant expression");
2579 assert(C1->getType() == C2->getType() &&
2580 "Operand types in binary constant expression should match");
2581
2582#ifndef NDEBUG
2583 switch (Opcode) {
2584 case Instruction::Add:
2585 case Instruction::Sub:
2586 case Instruction::Mul:
2587 assert(C1->getType()->isIntOrIntVectorTy() &&
2588 "Tried to create an integer operation on a non-integer type!");
2589 break;
2590 case Instruction::And:
2591 case Instruction::Or:
2592 case Instruction::Xor:
2593 assert(C1->getType()->isIntOrIntVectorTy() &&
2594 "Tried to create a logical operation on a non-integral type!");
2595 break;
2596 default:
2597 break;
2598 }
2599#endif
2600
2601 if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
2602 return FC;
2603
2604 if (OnlyIfReducedTy == C1->getType())
2605 return nullptr;
2606
2607 Constant *ArgVec[] = {C1, C2};
2608 ConstantExprKeyType Key(Opcode, ArgVec, Flags);
2609
2610 LLVMContextImpl *pImpl = C1->getContext().pImpl;
2611 return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
2612}
2613
2614bool ConstantExpr::isDesirableBinOp(unsigned Opcode) {
2615 switch (Opcode) {
2616 case Instruction::UDiv:
2617 case Instruction::SDiv:
2618 case Instruction::URem:
2619 case Instruction::SRem:
2620 case Instruction::FAdd:
2621 case Instruction::FSub:
2622 case Instruction::FMul:
2623 case Instruction::FDiv:
2624 case Instruction::FRem:
2625 case Instruction::And:
2626 case Instruction::Or:
2627 case Instruction::LShr:
2628 case Instruction::AShr:
2629 case Instruction::Shl:
2630 case Instruction::Mul:
2631 return false;
2632 case Instruction::Add:
2633 case Instruction::Sub:
2634 case Instruction::Xor:
2635 return true;
2636 default:
2637 llvm_unreachable("Argument must be binop opcode");
2638 }
2639}
2640
2641bool ConstantExpr::isSupportedBinOp(unsigned Opcode) {
2642 switch (Opcode) {
2643 case Instruction::UDiv:
2644 case Instruction::SDiv:
2645 case Instruction::URem:
2646 case Instruction::SRem:
2647 case Instruction::FAdd:
2648 case Instruction::FSub:
2649 case Instruction::FMul:
2650 case Instruction::FDiv:
2651 case Instruction::FRem:
2652 case Instruction::And:
2653 case Instruction::Or:
2654 case Instruction::LShr:
2655 case Instruction::AShr:
2656 case Instruction::Shl:
2657 case Instruction::Mul:
2658 return false;
2659 case Instruction::Add:
2660 case Instruction::Sub:
2661 case Instruction::Xor:
2662 return true;
2663 default:
2664 llvm_unreachable("Argument must be binop opcode");
2665 }
2666}
2667
2668bool ConstantExpr::isDesirableCastOp(unsigned Opcode) {
2669 switch (Opcode) {
2670 case Instruction::ZExt:
2671 case Instruction::SExt:
2672 case Instruction::FPTrunc:
2673 case Instruction::FPExt:
2674 case Instruction::UIToFP:
2675 case Instruction::SIToFP:
2676 case Instruction::FPToUI:
2677 case Instruction::FPToSI:
2678 return false;
2679 case Instruction::Trunc:
2680 case Instruction::PtrToAddr:
2681 case Instruction::PtrToInt:
2682 case Instruction::IntToPtr:
2683 case Instruction::BitCast:
2684 case Instruction::AddrSpaceCast:
2685 return true;
2686 default:
2687 llvm_unreachable("Argument must be cast opcode");
2688 }
2689}
2690
2691bool ConstantExpr::isSupportedCastOp(unsigned Opcode) {
2692 switch (Opcode) {
2693 case Instruction::ZExt:
2694 case Instruction::SExt:
2695 case Instruction::FPTrunc:
2696 case Instruction::FPExt:
2697 case Instruction::UIToFP:
2698 case Instruction::SIToFP:
2699 case Instruction::FPToUI:
2700 case Instruction::FPToSI:
2701 return false;
2702 case Instruction::Trunc:
2703 case Instruction::PtrToAddr:
2704 case Instruction::PtrToInt:
2705 case Instruction::IntToPtr:
2706 case Instruction::BitCast:
2707 case Instruction::AddrSpaceCast:
2708 return true;
2709 default:
2710 llvm_unreachable("Argument must be cast opcode");
2711 }
2712}
2713
2715 // sizeof is implemented as: (i64) gep (Ty*)null, 1
2716 // Note that a non-inbounds gep is used, as null isn't within any object.
2717 Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2720 Ty, Constant::getNullValue(PointerType::getUnqual(Ty->getContext())),
2721 GEPIdx);
2723 return getPtrToInt(GEP,
2724 Type::getInt64Ty(Ty->getContext()));
2725}
2726
2728 // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
2729 // Note that a non-inbounds gep is used, as null isn't within any object.
2730 Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
2731 Constant *NullPtr =
2733 Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
2734 Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
2735 Constant *Indices[2] = {Zero, One};
2737 Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
2739 return getPtrToInt(GEP, Type::getInt64Ty(Ty->getContext()));
2740}
2741
2743 ArrayRef<Value *> Idxs,
2744 GEPNoWrapFlags NW,
2745 std::optional<ConstantRange> InRange,
2746 Type *OnlyIfReducedTy) {
2747 assert(Ty && "Must specify element type");
2748 assert(isSupportedGetElementPtr(Ty) && "Element type is unsupported!");
2749
2750 if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InRange, Idxs))
2751 return FC; // Fold a few common cases.
2752
2753 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2754 ;
2755
2756 // Get the result type of the getelementptr!
2758 if (OnlyIfReducedTy == ReqTy)
2759 return nullptr;
2760
2761 auto EltCount = ElementCount::getFixed(0);
2762 if (VectorType *VecTy = dyn_cast<VectorType>(ReqTy))
2763 EltCount = VecTy->getElementCount();
2764
2765 // Look up the constant in the table first to ensure uniqueness
2766 std::vector<Constant*> ArgVec;
2767 ArgVec.reserve(1 + Idxs.size());
2768 ArgVec.push_back(C);
2769 auto GTI = gep_type_begin(Ty, Idxs), GTE = gep_type_end(Ty, Idxs);
2770 for (; GTI != GTE; ++GTI) {
2771 auto *Idx = cast<Constant>(GTI.getOperand());
2772 assert(
2773 (!isa<VectorType>(Idx->getType()) ||
2774 cast<VectorType>(Idx->getType())->getElementCount() == EltCount) &&
2775 "getelementptr index type missmatch");
2776
2777 if (GTI.isStruct() && Idx->getType()->isVectorTy()) {
2778 Idx = Idx->getSplatValue();
2779 } else if (GTI.isSequential() && EltCount.isNonZero() &&
2780 !Idx->getType()->isVectorTy()) {
2781 Idx = ConstantVector::getSplat(EltCount, Idx);
2782 }
2783 ArgVec.push_back(Idx);
2784 }
2785
2786 const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, NW.getRaw(),
2787 {}, Ty, InRange);
2788
2789 LLVMContextImpl *pImpl = C->getContext().pImpl;
2790 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2791}
2792
2795 GEPNoWrapFlags NW,
2796 std::optional<ConstantRange> InRange,
2797 Type *OnlyIfReducedTy) {
2798 // Handle already canonical GEP.
2799 if (Ty->isIntegerTy(8) && Idxs[0]->getType() == DL.getIndexType(C->getType()))
2800 return getPtrAdd(C, Idxs[0], NW, InRange, OnlyIfReducedTy);
2801
2802 // Some API require an ArrayRef of Value * instead of Constant *.
2803 ArrayRef<Value *> ValIdxs =
2804 ArrayRef((Value *const *)Idxs.data(), Idxs.size());
2805 assert(GetElementPtrInst::getIndexedType(Ty, Idxs) && "GEP indices invalid!");
2806
2807 if (!isSupportedGetElementPtr(Ty))
2808 return nullptr;
2809
2810 Type *RetTy = GetElementPtrInst::getGEPReturnType(C, ValIdxs);
2811 Type *IdxTy = DL.getIndexType(RetTy);
2812
2814 auto GTI = gep_type_begin(Ty, ValIdxs), GTE = gep_type_end(Ty, ValIdxs);
2815 for (; GTI != GTE; ++GTI) {
2816 auto *Idx = cast<Constant>(GTI.getOperand());
2817 if (Idx->isNullValue())
2818 continue;
2819
2820 if (StructType *STy = GTI.getStructTypeOrNull()) {
2821 uint64_t OpValue = Idx->getUniqueInteger().getZExtValue();
2822 uint64_t Size = DL.getStructLayout(STy)->getElementOffset(OpValue);
2823 if (!Size)
2824 continue;
2825
2826 Offset = ConstantFoldBinaryInstruction(Instruction::Add, Offset,
2827 ConstantInt::get(IdxTy, Size));
2828 if (!Offset)
2829 return nullptr;
2830
2831 continue;
2832 }
2833
2834 // Splat the index if needed.
2835 if (IdxTy->isVectorTy() && !Idx->getType()->isVectorTy())
2836 Idx = ConstantVector::getSplat(cast<VectorType>(IdxTy)->getElementCount(),
2837 Idx);
2838
2839 // Convert to correct type.
2840 if (Idx->getType() != IdxTy) {
2841 Idx = ConstantFoldCastInstruction(Idx->getType()->getScalarSizeInBits() <
2842 IdxTy->getScalarSizeInBits()
2843 ? Instruction::SExt
2844 : Instruction::Trunc,
2845 Idx, IdxTy);
2846 if (!Idx)
2847 return nullptr;
2848 }
2849
2850 TypeSize TySize = GTI.getSequentialElementStride(DL);
2851 if (TySize.isScalable())
2852 return nullptr;
2853
2854 // Multiply by scale.
2855 if (TySize != TypeSize::getFixed(1)) {
2856 Constant *Scale = ConstantInt::getSigned(IdxTy, TySize.getFixedValue(),
2857 /*ImplicitTrunc=*/true);
2858 Idx = ConstantFoldBinaryInstruction(Instruction::Mul, Idx, Scale);
2859 if (!Idx)
2860 return nullptr;
2861 }
2862
2863 Offset = ConstantFoldBinaryInstruction(Instruction::Add, Offset, Idx);
2864 if (!Offset)
2865 return nullptr;
2866 }
2867
2868 return getPtrAdd(C, Offset, NW, InRange, OnlyIfReducedTy);
2869}
2870
2872 Type *OnlyIfReducedTy) {
2873 assert(Val->getType()->isVectorTy() &&
2874 "Tried to create extractelement operation on non-vector type!");
2875 assert(Idx->getType()->isIntegerTy() &&
2876 "Extractelement index must be an integer type!");
2877
2879 return FC; // Fold a few common cases.
2880
2881 Type *ReqTy = cast<VectorType>(Val->getType())->getElementType();
2882 if (OnlyIfReducedTy == ReqTy)
2883 return nullptr;
2884
2885 // Look up the constant in the table first to ensure uniqueness
2886 Constant *ArgVec[] = { Val, Idx };
2887 const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
2888
2889 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2890 return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
2891}
2892
2894 Constant *Idx, Type *OnlyIfReducedTy) {
2895 assert(Val->getType()->isVectorTy() &&
2896 "Tried to create insertelement operation on non-vector type!");
2897 assert(Elt->getType() == cast<VectorType>(Val->getType())->getElementType() &&
2898 "Insertelement types must match!");
2899 assert(Idx->getType()->isIntegerTy() &&
2900 "Insertelement index must be i32 type!");
2901
2902 if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
2903 return FC; // Fold a few common cases.
2904
2905 if (OnlyIfReducedTy == Val->getType())
2906 return nullptr;
2907
2908 // Look up the constant in the table first to ensure uniqueness
2909 Constant *ArgVec[] = { Val, Elt, Idx };
2910 const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
2911
2912 LLVMContextImpl *pImpl = Val->getContext().pImpl;
2913 return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
2914}
2915
2917 ArrayRef<int> Mask,
2918 Type *OnlyIfReducedTy) {
2920 "Invalid shuffle vector constant expr operands!");
2921
2923 return FC; // Fold a few common cases.
2924
2925 unsigned NElts = Mask.size();
2926 auto V1VTy = cast<VectorType>(V1->getType());
2927 Type *EltTy = V1VTy->getElementType();
2928 bool TypeIsScalable = isa<ScalableVectorType>(V1VTy);
2929 Type *ShufTy = VectorType::get(EltTy, NElts, TypeIsScalable);
2930
2931 if (OnlyIfReducedTy == ShufTy)
2932 return nullptr;
2933
2934 // Look up the constant in the table first to ensure uniqueness
2935 Constant *ArgVec[] = {V1, V2};
2936 ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec, 0, Mask);
2937
2938 LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
2939 return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
2940}
2941
2943 assert(C->getType()->isIntOrIntVectorTy() &&
2944 "Cannot NEG a nonintegral value!");
2945 return getSub(ConstantInt::get(C->getType(), 0), C, /*HasNUW=*/false, HasNSW);
2946}
2947
2949 assert(C->getType()->isIntOrIntVectorTy() &&
2950 "Cannot NOT a nonintegral value!");
2951 return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
2952}
2953
2955 bool HasNUW, bool HasNSW) {
2956 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2958 return get(Instruction::Add, C1, C2, Flags);
2959}
2960
2962 bool HasNUW, bool HasNSW) {
2963 unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
2965 return get(Instruction::Sub, C1, C2, Flags);
2966}
2967
2969 return get(Instruction::Xor, C1, C2);
2970}
2971
2973 Type *Ty = C->getType();
2974 const APInt *IVal;
2975 if (match(C, m_APInt(IVal)) && IVal->isPowerOf2())
2976 return ConstantInt::get(Ty, IVal->logBase2());
2977
2978 // FIXME: We can extract pow of 2 of splat constant for scalable vectors.
2979 auto *VecTy = dyn_cast<FixedVectorType>(Ty);
2980 if (!VecTy)
2981 return nullptr;
2982
2984 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
2985 Constant *Elt = C->getAggregateElement(I);
2986 if (!Elt)
2987 return nullptr;
2988 // Note that log2(iN undef) is *NOT* iN undef, because log2(iN undef) u< N.
2989 if (isa<UndefValue>(Elt)) {
2990 Elts.push_back(Constant::getNullValue(Ty->getScalarType()));
2991 continue;
2992 }
2993 if (!match(Elt, m_APInt(IVal)) || !IVal->isPowerOf2())
2994 return nullptr;
2995 Elts.push_back(ConstantInt::get(Ty->getScalarType(), IVal->logBase2()));
2996 }
2997
2998 return ConstantVector::get(Elts);
2999}
3000
3002 bool AllowRHSConstant, bool NSZ) {
3003 assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
3004
3005 // Commutative opcodes: it does not matter if AllowRHSConstant is set.
3006 if (Instruction::isCommutative(Opcode)) {
3007 switch (Opcode) {
3008 case Instruction::Add: // X + 0 = X
3009 case Instruction::Or: // X | 0 = X
3010 case Instruction::Xor: // X ^ 0 = X
3011 return Constant::getNullValue(Ty);
3012 case Instruction::Mul: // X * 1 = X
3013 return ConstantInt::get(Ty, 1);
3014 case Instruction::And: // X & -1 = X
3015 return Constant::getAllOnesValue(Ty);
3016 case Instruction::FAdd: // X + -0.0 = X
3017 return ConstantFP::getZero(Ty, !NSZ);
3018 case Instruction::FMul: // X * 1.0 = X
3019 return ConstantFP::get(Ty, 1.0);
3020 default:
3021 llvm_unreachable("Every commutative binop has an identity constant");
3022 }
3023 }
3024
3025 // Non-commutative opcodes: AllowRHSConstant must be set.
3026 if (!AllowRHSConstant)
3027 return nullptr;
3028
3029 switch (Opcode) {
3030 case Instruction::Sub: // X - 0 = X
3031 case Instruction::Shl: // X << 0 = X
3032 case Instruction::LShr: // X >>u 0 = X
3033 case Instruction::AShr: // X >> 0 = X
3034 case Instruction::FSub: // X - 0.0 = X
3035 return Constant::getNullValue(Ty);
3036 case Instruction::SDiv: // X / 1 = X
3037 case Instruction::UDiv: // X /u 1 = X
3038 return ConstantInt::get(Ty, 1);
3039 case Instruction::FDiv: // X / 1.0 = X
3040 return ConstantFP::get(Ty, 1.0);
3041 default:
3042 return nullptr;
3043 }
3044}
3045
3047 switch (ID) {
3048 case Intrinsic::umax:
3049 return Constant::getNullValue(Ty);
3050 case Intrinsic::umin:
3051 return Constant::getAllOnesValue(Ty);
3052 case Intrinsic::smax:
3054 Ty, APInt::getSignedMinValue(Ty->getScalarSizeInBits()));
3055 case Intrinsic::smin:
3057 Ty, APInt::getSignedMaxValue(Ty->getScalarSizeInBits()));
3058 default:
3059 return nullptr;
3060 }
3061}
3062
3064 bool AllowRHSConstant, bool NSZ) {
3065 if (I->isBinaryOp())
3066 return getBinOpIdentity(I->getOpcode(), Ty, AllowRHSConstant, NSZ);
3068 return getIntrinsicIdentity(II->getIntrinsicID(), Ty);
3069 return nullptr;
3070}
3071
3073 bool AllowLHSConstant) {
3074 switch (Opcode) {
3075 default:
3076 break;
3077
3078 case Instruction::Or: // -1 | X = -1
3079 return Constant::getAllOnesValue(Ty);
3080
3081 case Instruction::And: // 0 & X = 0
3082 case Instruction::Mul: // 0 * X = 0
3083 return Constant::getNullValue(Ty);
3084 }
3085
3086 // AllowLHSConstant must be set.
3087 if (!AllowLHSConstant)
3088 return nullptr;
3089
3090 switch (Opcode) {
3091 default:
3092 return nullptr;
3093 case Instruction::Shl: // 0 << X = 0
3094 case Instruction::LShr: // 0 >>l X = 0
3095 case Instruction::AShr: // 0 >>a X = 0
3096 case Instruction::SDiv: // 0 /s X = 0
3097 case Instruction::UDiv: // 0 /u X = 0
3098 case Instruction::URem: // 0 %u X = 0
3099 case Instruction::SRem: // 0 %s X = 0
3100 return Constant::getNullValue(Ty);
3101 }
3102}
3103
3104/// Remove the constant from the constant table.
3105void ConstantExpr::destroyConstantImpl() {
3106 getType()->getContext().pImpl->ExprConstants.remove(this);
3107}
3108
3109const char *ConstantExpr::getOpcodeName() const {
3111}
3112
3113GetElementPtrConstantExpr::GetElementPtrConstantExpr(
3114 Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy,
3115 std::optional<ConstantRange> InRange, AllocInfo AllocInfo)
3116 : ConstantExpr(DestTy, Instruction::GetElementPtr, AllocInfo),
3117 SrcElementTy(SrcElementTy),
3118 ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)),
3119 InRange(std::move(InRange)) {
3120 Op<0>() = C;
3121 Use *OperandList = getOperandList();
3122 for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
3123 OperandList[i+1] = IdxList[i];
3124}
3125
3127 return SrcElementTy;
3128}
3129
3131 return ResElementTy;
3132}
3133
3134std::optional<ConstantRange> GetElementPtrConstantExpr::getInRange() const {
3135 return InRange;
3136}
3137
3138//===----------------------------------------------------------------------===//
3139// ConstantData* implementations
3140
3143 return ATy->getElementType();
3144 return cast<VectorType>(getType())->getElementType();
3145}
3146
3150
3152 if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() || Ty->isDoubleTy())
3153 return true;
3154 if (auto *IT = dyn_cast<IntegerType>(Ty)) {
3155 switch (IT->getBitWidth()) {
3156 case 8:
3157 case 16:
3158 case 32:
3159 case 64:
3160 return true;
3161 default: break;
3162 }
3163 }
3164 if (auto *IT = dyn_cast<ByteType>(Ty)) {
3165 switch (IT->getBitWidth()) {
3166 case 8:
3167 case 16:
3168 case 32:
3169 case 64:
3170 return true;
3171 default:
3172 break;
3173 }
3174 }
3175 return false;
3176}
3177
3180 return AT->getNumElements();
3181 return cast<FixedVectorType>(getType())->getNumElements();
3182}
3183
3187
3188/// Return the start of the specified element.
3189const char *ConstantDataSequential::getElementPointer(uint64_t Elt) const {
3190 assert(Elt < getNumElements() && "Invalid Elt");
3191 return DataElements + Elt * getElementByteSize();
3192}
3193
3194/// Return true if the array is empty or all zeros.
3195static bool isAllZeros(StringRef Arr) {
3196 for (char I : Arr)
3197 if (I != 0)
3198 return false;
3199 return true;
3200}
3201
3202/// This is the underlying implementation of all of the
3203/// ConstantDataSequential::get methods. They all thunk down to here, providing
3204/// the correct element type. We take the bytes in as a StringRef because
3205/// we *want* an underlying "char*" to avoid TBAA type punning violations.
3207#ifndef NDEBUG
3208 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty))
3209 assert(isElementTypeCompatible(ATy->getElementType()));
3210 else
3212#endif
3213 // If the elements are all zero or there are no elements, return a CAZ, which
3214 // is more dense and canonical.
3215 if (isAllZeros(Elements))
3216 return ConstantAggregateZero::get(Ty);
3217
3218 // Do a lookup to see if we have already formed one of these.
3219 auto &Slot =
3220 *Ty->getContext().pImpl->CDSConstants.try_emplace(Elements).first;
3221
3222 // The bucket can point to a linked list of different CDS's that have the same
3223 // body but different types. For example, 0,0,0,1 could be a 4 element array
3224 // of i8, or a 1-element array of i32. They'll both end up in the same
3225 /// StringMap bucket, linked up by their Next pointers. Walk the list.
3226 std::unique_ptr<ConstantDataSequential> *Entry = &Slot.second;
3227 for (; *Entry; Entry = &(*Entry)->Next)
3228 if ((*Entry)->getType() == Ty)
3229 return Entry->get();
3230
3231 // Okay, we didn't get a hit. Create a node of the right class, link it in,
3232 // and return it.
3233 if (isa<ArrayType>(Ty)) {
3234 // Use reset because std::make_unique can't access the constructor.
3235 Entry->reset(new ConstantDataArray(Ty, Slot.first().data()));
3236 return Entry->get();
3237 }
3238
3240 // Use reset because std::make_unique can't access the constructor.
3241 Entry->reset(new ConstantDataVector(Ty, Slot.first().data()));
3242 return Entry->get();
3243}
3244
3245void ConstantDataSequential::destroyConstantImpl() {
3246 // Remove the constant from the StringMap.
3249
3250 auto Slot = CDSConstants.find(getRawDataValues());
3251
3252 assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
3253
3254 std::unique_ptr<ConstantDataSequential> *Entry = &Slot->getValue();
3255
3256 // Remove the entry from the hash table.
3257 if (!(*Entry)->Next) {
3258 // If there is only one value in the bucket (common case) it must be this
3259 // entry, and removing the entry should remove the bucket completely.
3260 assert(Entry->get() == this && "Hash mismatch in ConstantDataSequential");
3261 getContext().pImpl->CDSConstants.erase(Slot);
3262 return;
3263 }
3264
3265 // Otherwise, there are multiple entries linked off the bucket, unlink the
3266 // node we care about but keep the bucket around.
3267 while (true) {
3268 std::unique_ptr<ConstantDataSequential> &Node = *Entry;
3269 assert(Node && "Didn't find entry in its uniquing hash table!");
3270 // If we found our entry, unlink it from the list and we're done.
3271 if (Node.get() == this) {
3272 Node = std::move(Node->Next);
3273 return;
3274 }
3275
3276 Entry = &Node->Next;
3277 }
3278}
3279
3280/// getFP() constructors - Return a constant of array type with a float
3281/// element type taken from argument `ElementType', and count taken from
3282/// argument `Elts'. The amount of bits of the contained type must match the
3283/// number of bits of the type contained in the passed in ArrayRef.
3284/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3285/// that this can return a ConstantAggregateZero object.
3287 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3288 "Element type is not a 16-bit float type");
3289 Type *Ty = ArrayType::get(ElementType, Elts.size());
3290 const char *Data = reinterpret_cast<const char *>(Elts.data());
3291 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3292}
3294 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3295 Type *Ty = ArrayType::get(ElementType, Elts.size());
3296 const char *Data = reinterpret_cast<const char *>(Elts.data());
3297 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3298}
3300 assert(ElementType->isDoubleTy() &&
3301 "Element type is not a 64-bit float type");
3302 Type *Ty = ArrayType::get(ElementType, Elts.size());
3303 const char *Data = reinterpret_cast<const char *>(Elts.data());
3304 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3305}
3306
3307/// getByte() constructors - Return a constant of array type with a byte
3308/// element type taken from argument `ElementType', and count taken from
3309/// argument `Elts'. The amount of bits of the contained type must match the
3310/// number of bits of the type contained in the passed in ArrayRef.
3311/// Note that this can return a ConstantAggregateZero object.
3313 ArrayRef<uint8_t> Elts) {
3314 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte type");
3315 Type *Ty = ArrayType::get(ElementType, Elts.size());
3316 const char *Data = reinterpret_cast<const char *>(Elts.data());
3317 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3318}
3320 ArrayRef<uint16_t> Elts) {
3321 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte type");
3322 Type *Ty = ArrayType::get(ElementType, Elts.size());
3323 const char *Data = reinterpret_cast<const char *>(Elts.data());
3324 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3325}
3327 ArrayRef<uint32_t> Elts) {
3328 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte type");
3329 Type *Ty = ArrayType::get(ElementType, Elts.size());
3330 const char *Data = reinterpret_cast<const char *>(Elts.data());
3331 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3332}
3334 ArrayRef<uint64_t> Elts) {
3335 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte type");
3336 Type *Ty = ArrayType::get(ElementType, Elts.size());
3337 const char *Data = reinterpret_cast<const char *>(Elts.data());
3338 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3339}
3340
3342 bool AddNull, bool ByteString) {
3343 if (!AddNull) {
3344 const uint8_t *Data = Str.bytes_begin();
3345 return ByteString
3346 ? getByte(Type::getByte8Ty(Context), ArrayRef(Data, Str.size()))
3347 : get(Context, ArrayRef(Data, Str.size()));
3348 }
3349
3350 SmallVector<uint8_t, 64> ElementVals;
3351 ElementVals.append(Str.begin(), Str.end());
3352 ElementVals.push_back(0);
3353 return ByteString ? getByte(Type::getByte8Ty(Context), ElementVals)
3354 : get(Context, ElementVals);
3355}
3356
3357/// get() constructors - Return a constant with vector type with an element
3358/// count and element type matching the ArrayRef passed in. Note that this
3359/// can return a ConstantAggregateZero object.
3361 auto *Ty = FixedVectorType::get(Type::getInt8Ty(Context), Elts.size());
3362 const char *Data = reinterpret_cast<const char *>(Elts.data());
3363 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3364}
3366 auto *Ty = FixedVectorType::get(Type::getInt16Ty(Context), Elts.size());
3367 const char *Data = reinterpret_cast<const char *>(Elts.data());
3368 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3369}
3371 auto *Ty = FixedVectorType::get(Type::getInt32Ty(Context), Elts.size());
3372 const char *Data = reinterpret_cast<const char *>(Elts.data());
3373 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3374}
3376 auto *Ty = FixedVectorType::get(Type::getInt64Ty(Context), Elts.size());
3377 const char *Data = reinterpret_cast<const char *>(Elts.data());
3378 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3379}
3381 auto *Ty = FixedVectorType::get(Type::getFloatTy(Context), Elts.size());
3382 const char *Data = reinterpret_cast<const char *>(Elts.data());
3383 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3384}
3386 auto *Ty = FixedVectorType::get(Type::getDoubleTy(Context), Elts.size());
3387 const char *Data = reinterpret_cast<const char *>(Elts.data());
3388 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3389}
3390
3391/// getByte() constructors - Return a constant of vector type with a byte
3392/// element type taken from argument `ElementType', and count taken from
3393/// argument `Elts'. The amount of bits of the contained type must match the
3394/// number of bits of the type contained in the passed in ArrayRef.
3395/// Note that this can return a ConstantAggregateZero object.
3397 ArrayRef<uint8_t> Elts) {
3398 assert(ElementType->isByteTy(8) && "Element type is not a 8-bit byte");
3399 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3400 const char *Data = reinterpret_cast<const char *>(Elts.data());
3401 return getImpl(StringRef(Data, Elts.size() * 1), Ty);
3402}
3404 ArrayRef<uint16_t> Elts) {
3405 assert(ElementType->isByteTy(16) && "Element type is not a 16-bit byte");
3406 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3407 const char *Data = reinterpret_cast<const char *>(Elts.data());
3408 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3409}
3411 ArrayRef<uint32_t> Elts) {
3412 assert(ElementType->isByteTy(32) && "Element type is not a 32-bit byte");
3413 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3414 const char *Data = reinterpret_cast<const char *>(Elts.data());
3415 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3416}
3418 ArrayRef<uint64_t> Elts) {
3419 assert(ElementType->isByteTy(64) && "Element type is not a 64-bit byte");
3420 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3421 const char *Data = reinterpret_cast<const char *>(Elts.data());
3422 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3423}
3424
3425/// getFP() constructors - Return a constant of vector type with a float
3426/// element type taken from argument `ElementType', and count taken from
3427/// argument `Elts'. The amount of bits of the contained type must match the
3428/// number of bits of the type contained in the passed in ArrayRef.
3429/// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
3430/// that this can return a ConstantAggregateZero object.
3432 ArrayRef<uint16_t> Elts) {
3433 assert((ElementType->isHalfTy() || ElementType->isBFloatTy()) &&
3434 "Element type is not a 16-bit float type");
3435 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3436 const char *Data = reinterpret_cast<const char *>(Elts.data());
3437 return getImpl(StringRef(Data, Elts.size() * 2), Ty);
3438}
3440 ArrayRef<uint32_t> Elts) {
3441 assert(ElementType->isFloatTy() && "Element type is not a 32-bit float type");
3442 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3443 const char *Data = reinterpret_cast<const char *>(Elts.data());
3444 return getImpl(StringRef(Data, Elts.size() * 4), Ty);
3445}
3447 ArrayRef<uint64_t> Elts) {
3448 assert(ElementType->isDoubleTy() &&
3449 "Element type is not a 64-bit float type");
3450 auto *Ty = FixedVectorType::get(ElementType, Elts.size());
3451 const char *Data = reinterpret_cast<const char *>(Elts.data());
3452 return getImpl(StringRef(Data, Elts.size() * 8), Ty);
3453}
3454
3456 assert(isElementTypeCompatible(V->getType()) &&
3457 "Element type not compatible with ConstantData");
3458 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
3459 if (CI->getType()->isIntegerTy(8)) {
3460 SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
3461 return get(V->getContext(), Elts);
3462 }
3463 if (CI->getType()->isIntegerTy(16)) {
3464 SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
3465 return get(V->getContext(), Elts);
3466 }
3467 if (CI->getType()->isIntegerTy(32)) {
3468 SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
3469 return get(V->getContext(), Elts);
3470 }
3471 assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
3472 SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
3473 return get(V->getContext(), Elts);
3474 }
3475
3476 if (ConstantByte *CB = dyn_cast<ConstantByte>(V)) {
3477 if (CB->getType()->isByteTy(8)) {
3478 SmallVector<uint8_t, 16> Elts(NumElts, CB->getZExtValue());
3479 return getByte(V->getType(), Elts);
3480 }
3481 if (CB->getType()->isByteTy(16)) {
3482 SmallVector<uint16_t, 16> Elts(NumElts, CB->getZExtValue());
3483 return getByte(V->getType(), Elts);
3484 }
3485 if (CB->getType()->isByteTy(32)) {
3486 SmallVector<uint32_t, 16> Elts(NumElts, CB->getZExtValue());
3487 return getByte(V->getType(), Elts);
3488 }
3489 assert(CB->getType()->isByteTy(64) && "Unsupported ConstantData type");
3490 SmallVector<uint64_t, 16> Elts(NumElts, CB->getZExtValue());
3491 return getByte(V->getType(), Elts);
3492 }
3493
3494 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
3495 if (CFP->getType()->isHalfTy()) {
3497 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3498 return getFP(V->getType(), Elts);
3499 }
3500 if (CFP->getType()->isBFloatTy()) {
3502 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3503 return getFP(V->getType(), Elts);
3504 }
3505 if (CFP->getType()->isFloatTy()) {
3507 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3508 return getFP(V->getType(), Elts);
3509 }
3510 if (CFP->getType()->isDoubleTy()) {
3512 NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
3513 return getFP(V->getType(), Elts);
3514 }
3515 }
3517}
3518
3520 assert(
3522 "Accessor can only be used when element is an integer or byte");
3523 const char *EltPtr = getElementPointer(Elt);
3524
3525 // The data is stored in host byte order, make sure to cast back to the right
3526 // type to load with the right endianness.
3527 switch (getElementByteSize()) {
3528 default: llvm_unreachable("Invalid bitwidth for CDS");
3529 case 1:
3530 return *reinterpret_cast<const uint8_t *>(EltPtr);
3531 case 2:
3532 return *reinterpret_cast<const uint16_t *>(EltPtr);
3533 case 4:
3534 return *reinterpret_cast<const uint32_t *>(EltPtr);
3535 case 8:
3536 return *reinterpret_cast<const uint64_t *>(EltPtr);
3537 }
3538}
3539
3541 assert(
3543 "Accessor can only be used when element is an integer or byte");
3544 const char *EltPtr = getElementPointer(Elt);
3545
3546 // The data is stored in host byte order, make sure to cast back to the right
3547 // type to load with the right endianness.
3548 switch (getElementByteSize()) {
3549 default: llvm_unreachable("Invalid bitwidth for CDS");
3550 case 1: {
3551 auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
3552 return APInt(8, EltVal);
3553 }
3554 case 2: {
3555 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3556 return APInt(16, EltVal);
3557 }
3558 case 4: {
3559 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3560 return APInt(32, EltVal);
3561 }
3562 case 8: {
3563 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3564 return APInt(64, EltVal);
3565 }
3566 }
3567}
3568
3570 const char *EltPtr = getElementPointer(Elt);
3571
3572 switch (getElementType()->getTypeID()) {
3573 default:
3574 llvm_unreachable("Accessor can only be used when element is float/double!");
3575 case Type::HalfTyID: {
3576 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3577 return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
3578 }
3579 case Type::BFloatTyID: {
3580 auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
3581 return APFloat(APFloat::BFloat(), APInt(16, EltVal));
3582 }
3583 case Type::FloatTyID: {
3584 auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
3585 return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
3586 }
3587 case Type::DoubleTyID: {
3588 auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
3589 return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
3590 }
3591 }
3592}
3593
3595 assert(getElementType()->isFloatTy() &&
3596 "Accessor can only be used when element is a 'float'");
3597 return *reinterpret_cast<const float *>(getElementPointer(Elt));
3598}
3599
3601 assert(getElementType()->isDoubleTy() &&
3602 "Accessor can only be used when element is a 'float'");
3603 return *reinterpret_cast<const double *>(getElementPointer(Elt));
3604}
3605
3607 if (getElementType()->isHalfTy() || getElementType()->isBFloatTy() ||
3608 getElementType()->isFloatTy() || getElementType()->isDoubleTy())
3609 return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
3610
3611 if (getElementType()->isByteTy())
3612 return ConstantByte::get(getElementType(), getElementAsInteger(Elt));
3613
3614 return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
3615}
3616
3617bool ConstantDataSequential::isString(unsigned CharSize) const {
3618 return isa<ArrayType>(getType()) &&
3619 (getElementType()->isIntegerTy(CharSize) ||
3620 getElementType()->isByteTy(CharSize));
3621}
3622
3624 if (!isString())
3625 return false;
3626
3627 StringRef Str = getAsString();
3628
3629 // The last value must be nul.
3630 if (Str.back() != 0) return false;
3631
3632 // Other elements must be non-nul.
3633 return !Str.drop_back().contains(0);
3634}
3635
3636bool ConstantDataVector::isSplatData() const {
3637 const char *Base = getRawDataValues().data();
3638
3639 // Compare elements 1+ to the 0'th element.
3640 unsigned EltSize = getElementByteSize();
3641 for (unsigned i = 1, e = getNumElements(); i != e; ++i)
3642 if (memcmp(Base, Base+i*EltSize, EltSize))
3643 return false;
3644
3645 return true;
3646}
3647
3649 if (!IsSplatSet) {
3650 IsSplatSet = true;
3651 IsSplat = isSplatData();
3652 }
3653 return IsSplat;
3654}
3655
3657 // If they're all the same, return the 0th one as a representative.
3658 return isSplat() ? getElementAsConstant(0) : nullptr;
3659}
3660
3661//===----------------------------------------------------------------------===//
3662// handleOperandChange implementations
3663
3664/// Update this constant array to change uses of
3665/// 'From' to be uses of 'To'. This must update the uniquing data structures
3666/// etc.
3667///
3668/// Note that we intentionally replace all uses of From with To here. Consider
3669/// a large array that uses 'From' 1000 times. By handling this case all here,
3670/// ConstantArray::handleOperandChange is only invoked once, and that
3671/// single invocation handles all 1000 uses. Handling them one at a time would
3672/// work, but would be really slow because it would have to unique each updated
3673/// array instance.
3674///
3676 Value *Replacement = nullptr;
3677 switch (getValueID()) {
3678 default:
3679 llvm_unreachable("Not a constant!");
3680#define HANDLE_CONSTANT(Name) \
3681 case Value::Name##Val: \
3682 Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
3683 break;
3684#include "llvm/IR/Value.def"
3685 }
3686
3687 // If handleOperandChangeImpl returned nullptr, then it handled
3688 // replacing itself and we don't want to delete or replace anything else here.
3689 if (!Replacement)
3690 return;
3691
3692 // I do need to replace this with an existing value.
3693 assert(Replacement != this && "I didn't contain From!");
3694
3695 // Everyone using this now uses the replacement.
3696 replaceAllUsesWith(Replacement);
3697
3698 // Delete the old constant!
3700}
3701
3702Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
3703 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3704 Constant *ToC = cast<Constant>(To);
3705
3707 Values.reserve(getNumOperands()); // Build replacement array.
3708
3709 // Fill values with the modified operands of the constant array. Also,
3710 // compute whether this turns into an all-zeros array.
3711 unsigned NumUpdated = 0;
3712
3713 // Keep track of whether all the values in the array are "ToC".
3714 bool AllSame = true;
3715 Use *OperandList = getOperandList();
3716 unsigned OperandNo = 0;
3717 for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
3718 Constant *Val = cast<Constant>(O->get());
3719 if (Val == From) {
3720 OperandNo = (O - OperandList);
3721 Val = ToC;
3722 ++NumUpdated;
3723 }
3724 Values.push_back(Val);
3725 AllSame &= Val == ToC;
3726 }
3727
3728 if (AllSame && ToC->isNullValue())
3730
3731 if (AllSame && isa<UndefValue>(ToC))
3732 return UndefValue::get(getType());
3733
3734 // Check for any other type of constant-folding.
3735 if (Constant *C = getImpl(getType(), Values))
3736 return C;
3737
3738 // Update to the new value.
3740 Values, this, From, ToC, NumUpdated, OperandNo);
3741}
3742
3743Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
3744 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3745 Constant *ToC = cast<Constant>(To);
3746
3747 Use *OperandList = getOperandList();
3748
3750 Values.reserve(getNumOperands()); // Build replacement struct.
3751
3752 // Fill values with the modified operands of the constant struct. Also,
3753 // compute whether this turns into an all-zeros struct.
3754 unsigned NumUpdated = 0;
3755 bool AllSame = true;
3756 unsigned OperandNo = 0;
3757 for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
3758 Constant *Val = cast<Constant>(O->get());
3759 if (Val == From) {
3760 OperandNo = (O - OperandList);
3761 Val = ToC;
3762 ++NumUpdated;
3763 }
3764 Values.push_back(Val);
3765 AllSame &= Val == ToC;
3766 }
3767
3768 if (AllSame && ToC->isNullValue())
3770
3771 if (AllSame && isa<UndefValue>(ToC))
3772 return UndefValue::get(getType());
3773
3774 // Update to the new value.
3776 Values, this, From, ToC, NumUpdated, OperandNo);
3777}
3778
3779Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
3780 assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
3781 Constant *ToC = cast<Constant>(To);
3782
3784 Values.reserve(getNumOperands()); // Build replacement array...
3785 unsigned NumUpdated = 0;
3786 unsigned OperandNo = 0;
3787 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3788 Constant *Val = getOperand(i);
3789 if (Val == From) {
3790 OperandNo = i;
3791 ++NumUpdated;
3792 Val = ToC;
3793 }
3794 Values.push_back(Val);
3795 }
3796
3797 if (Constant *C = getImpl(Values))
3798 return C;
3799
3800 // Update to the new value.
3802 Values, this, From, ToC, NumUpdated, OperandNo);
3803}
3804
3805Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
3806 assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
3807 Constant *To = cast<Constant>(ToV);
3808
3810 unsigned NumUpdated = 0;
3811 unsigned OperandNo = 0;
3812 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3813 Constant *Op = getOperand(i);
3814 if (Op == From) {
3815 OperandNo = i;
3816 ++NumUpdated;
3817 Op = To;
3818 }
3819 NewOps.push_back(Op);
3820 }
3821 assert(NumUpdated && "I didn't contain From!");
3822
3823 if (Constant *C = getWithOperands(NewOps, getType(), true))
3824 return C;
3825
3826 // Update to the new value.
3827 return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
3828 NewOps, this, From, To, NumUpdated, OperandNo);
3829}
3830
3832 SmallVector<Value *, 4> ValueOperands(operands());
3833 ArrayRef<Value*> Ops(ValueOperands);
3834
3835 switch (getOpcode()) {
3836 case Instruction::Trunc:
3837 case Instruction::PtrToAddr:
3838 case Instruction::PtrToInt:
3839 case Instruction::IntToPtr:
3840 case Instruction::BitCast:
3841 case Instruction::AddrSpaceCast:
3843 getType(), "");
3844 case Instruction::InsertElement:
3845 return InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "");
3846 case Instruction::ExtractElement:
3847 return ExtractElementInst::Create(Ops[0], Ops[1], "");
3848 case Instruction::ShuffleVector:
3849 return new ShuffleVectorInst(Ops[0], Ops[1], getShuffleMask(), "");
3850
3851 case Instruction::GetElementPtr: {
3852 const auto *GO = cast<GEPOperator>(this);
3853 return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
3854 Ops.slice(1), GO->getNoWrapFlags(), "");
3855 }
3856 default:
3857 assert(getNumOperands() == 2 && "Must be binary operator?");
3859 (Instruction::BinaryOps)getOpcode(), Ops[0], Ops[1], "");
3865 }
3868 return BO;
3869 }
3870}
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:550
#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:6045
static LLVM_ABI APFloat getAllOnesValue(const fltSemantics &Semantics)
Returns a float which is bitcasted from an all one value int.
Definition APFloat.cpp:6071
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.
void setMayHaveConstantUsers()
Record that a constant other than a GlobalValue now uses this global.
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:338
ShuffleVectorConstantExpr - This class is private to Constants.cpp, and is used behind the scenes to ...
This instruction constructs a fixed permutation of two input vectors.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void 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:352
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:49
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:719
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
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:707
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:320
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:879
#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