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