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