48#define DEBUG_TYPE "lazy-value-info"
57 "Lazy Value Information Analysis",
false,
true)
64 "lvi-per-pred-ranges",
cl::Hidden,
cl::init(
false),
65 cl::desc(
"Enable tracking of ranges for a value in a block for"
66 "each block predecessor (default = false)"));
96 class LazyValueInfoCache;
97 struct LVIValueHandle final :
public CallbackVH {
98 LazyValueInfoCache *Parent;
100 LVIValueHandle(
Value *V, LazyValueInfoCache *
P =
nullptr)
101 : CallbackVH(
V), Parent(
P) { }
103 void deleted()
override;
104 void allUsesReplacedWith(
Value *V)
override {
112using BBLatticeElementMap =
114using PredecessorValueLatticeMap =
119class LazyValueInfoCache {
124 struct BlockCacheEntry {
125 SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
126 SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
129 std::optional<NonNullPointerSet> NonNullPointers;
133 std::optional<PredecessorValueLatticeMap> PredecessorLatticeElements;
137 DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
140 DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
142 const BlockCacheEntry *getBlockEntry(BasicBlock *BB)
const {
143 auto It = BlockCache.
find_as(BB);
144 if (It == BlockCache.
end())
146 return It->second.get();
149 BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
150 auto It = BlockCache.
find_as(BB);
151 if (It == BlockCache.
end()) {
152 std::unique_ptr<BlockCacheEntry> BCE =
153 std::make_unique<BlockCacheEntry>();
155 BCE->PredecessorLatticeElements =
156 std::make_optional<PredecessorValueLatticeMap>();
157 It = BlockCache.
insert({BB, std::move(BCE)}).first;
160 return It->second.get();
163 void addValueHandle(
Value *Val) {
164 auto HandleIt = ValueHandles.
find_as(Val);
165 if (HandleIt == ValueHandles.
end())
166 ValueHandles.
insert({Val,
this});
170 void insertResult(
Value *Val, BasicBlock *BB,
171 const ValueLatticeElement &Result) {
172 BlockCacheEntry *
Entry = getOrCreateBlockEntry(BB);
176 if (
Result.isOverdefined())
177 Entry->OverDefined.insert(Val);
184 void insertPredecessorResults(
Value *Val, BasicBlock *BB,
185 BBLatticeElementMap &PredLatticeElements) {
186 BlockCacheEntry *
Entry = getOrCreateBlockEntry(BB);
188 Entry->PredecessorLatticeElements->insert({Val, PredLatticeElements});
193 std::optional<BBLatticeElementMap>
194 getCachedPredecessorInfo(
Value *V, BasicBlock *BB)
const {
195 const BlockCacheEntry *
Entry = getBlockEntry(BB);
199 auto LatticeIt =
Entry->PredecessorLatticeElements->find_as(V);
200 if (LatticeIt ==
Entry->PredecessorLatticeElements->end())
203 return LatticeIt->second;
206 std::optional<ValueLatticeElement> getCachedValueInfo(
Value *V,
207 BasicBlock *BB)
const {
208 const BlockCacheEntry *
Entry = getBlockEntry(BB);
212 if (
Entry->OverDefined.count(V))
215 auto LatticeIt =
Entry->LatticeElements.find_as(V);
216 if (LatticeIt ==
Entry->LatticeElements.end())
219 return LatticeIt->second;
223 isNonNullAtEndOfBlock(
Value *V, BasicBlock *BB,
224 function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
225 BlockCacheEntry *
Entry = getOrCreateBlockEntry(BB);
226 if (!
Entry->NonNullPointers) {
227 Entry->NonNullPointers = InitFn(BB);
232 return Entry->NonNullPointers->count(V);
238 ValueHandles.
clear();
242 void eraseValue(
Value *V);
246 void eraseBlock(BasicBlock *BB);
251 void threadEdgeImpl(BasicBlock *OldSucc, BasicBlock *NewSucc);
255void LazyValueInfoCache::eraseValue(
Value *V) {
256 for (
auto &Pair : BlockCache) {
257 Pair.second->LatticeElements.erase(V);
258 Pair.second->OverDefined.erase(V);
259 if (Pair.second->NonNullPointers)
260 Pair.second->NonNullPointers->erase(V);
262 Pair.second->PredecessorLatticeElements->erase(V);
265 auto HandleIt = ValueHandles.
find_as(V);
266 if (HandleIt != ValueHandles.
end())
267 ValueHandles.
erase(HandleIt);
270void LVIValueHandle::deleted() {
273 Parent->eraseValue(*
this);
276void LazyValueInfoCache::eraseBlock(
BasicBlock *BB) {
279 for (
auto &Pair : BlockCache)
280 Pair.second->PredecessorLatticeElements->clear();
281 BlockCache.erase(BB);
284void LazyValueInfoCache::threadEdgeImpl(
BasicBlock *OldSucc,
296 std::vector<BasicBlock*> worklist;
297 worklist.push_back(OldSucc);
299 const BlockCacheEntry *
Entry = getBlockEntry(OldSucc);
300 if (!Entry ||
Entry->OverDefined.empty())
303 Entry->OverDefined.end());
309 while (!worklist.empty()) {
314 if (ToUpdate == NewSucc)
continue;
317 auto OI = BlockCache.find_as(ToUpdate);
318 if (OI == BlockCache.end() || OI->second->OverDefined.empty())
320 auto &ValueSet = OI->second->OverDefined;
322 bool changed =
false;
323 for (
Value *V : ValsToClear) {
324 if (!ValueSet.erase(V))
332 if (!changed)
continue;
343 LazyValueInfoImpl *LVIImpl;
349 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
350 : LVIImpl(
L), DT(DTree) {}
352 void emitBasicBlockStartAnnot(
const BasicBlock *BB,
353 formatted_raw_ostream &OS)
override;
355 void emitInstructionAnnot(
const Instruction *
I,
356 formatted_raw_ostream &OS)
override;
363 LazyValueInfoCache TheCache;
375 bool pushBlockValue(
const std::pair<BasicBlock *, Value *> &BV) {
376 if (!BlockValueSet.insert(BV).second)
380 << BV.first->getName() <<
"\n");
381 BlockValueStack.push_back(BV);
392 std::optional<ValueLatticeElement> getBlockValue(
Value *Val,
BasicBlock *BB,
402 std::optional<ValueLatticeElement> solveBlockValueImpl(
Value *Val,
404 std::optional<ValueLatticeElement> solveBlockValueNonLocal(
Value *Val,
406 std::optional<ValueLatticeElement> solveBlockValuePHINode(
PHINode *PN,
408 std::optional<ValueLatticeElement> solveBlockValueSelect(
SelectInst *S,
412 std::optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
416 std::optional<ValueLatticeElement>
418 std::optional<ValueLatticeElement> solveBlockValueCast(
CastInst *CI,
420 std::optional<ValueLatticeElement>
422 std::optional<ValueLatticeElement> solveBlockValueIntrinsic(
IntrinsicInst *
II,
424 std::optional<ValueLatticeElement>
426 std::optional<ValueLatticeElement>
429 void intersectAssumeOrGuardBlockValueConstantRange(
Value *Val,
439 std::optional<ValueLatticeElement>
444 std::optional<ValueLatticeElement>
445 getValueFromICmpCondition(
Value *Val,
ICmpInst *ICI,
bool isTrueDest,
450 std::optional<ValueLatticeElement>
452 bool UseBlockValue,
unsigned Depth = 0);
454 std::optional<ValueLatticeElement> getEdgeValueLocal(
Value *Val,
487 LazyValueInfoAnnotatedWriter Writer(
this, DTree);
488 F.print(OS, &Writer);
498 TheCache.eraseBlock(BB);
507 : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
511void LazyValueInfoImpl::solve() {
515 unsigned processedCount = 0;
516 while (!BlockValueStack.empty()) {
528 dbgs() <<
"Giving up on stack because we are getting too deep\n");
530 while (!StartingStack.
empty()) {
531 std::pair<BasicBlock *, Value *> &
e = StartingStack.
back();
532 TheCache.insertResult(
e.second,
e.first,
536 BlockValueSet.clear();
537 BlockValueStack.clear();
540 std::pair<BasicBlock *, Value *>
e = BlockValueStack.back();
541 assert(BlockValueSet.count(e) &&
"Stack value should be in BlockValueSet!");
542 unsigned StackSize = BlockValueStack.size();
545 if (solveBlockValue(
e.second,
e.first)) {
547 assert(BlockValueStack.size() == StackSize &&
548 BlockValueStack.back() == e &&
"Nothing should have been pushed!");
550 std::optional<ValueLatticeElement> BBLV =
551 TheCache.getCachedValueInfo(
e.second,
e.first);
552 assert(BBLV &&
"Result should be in cache!");
554 dbgs() <<
"POP " << *
e.second <<
" in " <<
e.first->getName() <<
" = "
558 BlockValueStack.pop_back();
559 BlockValueSet.erase(e);
562 assert(BlockValueStack.size() == StackSize + 1 &&
563 "Exactly one element should have been pushed!");
568std::optional<ValueLatticeElement>
575 if (std::optional<ValueLatticeElement> OptLatticeVal =
576 TheCache.getCachedValueInfo(Val, BB)) {
577 intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
578 return OptLatticeVal;
582 if (!pushBlockValue({ BB, Val }))
593 case Instruction::Call:
594 case Instruction::Invoke:
598 case Instruction::Load:
612 assert(!TheCache.getCachedValueInfo(Val, BB) &&
613 "Value should not be in cache");
617 std::optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
622 TheCache.insertResult(Val, BB, *Res);
626std::optional<ValueLatticeElement>
630 return solveBlockValueNonLocal(Val, BB);
633 return solveBlockValuePHINode(PN, BB);
636 return solveBlockValueSelect(SI, BB);
653 return solveBlockValueCast(CI, BB);
656 return solveBlockValueBinaryOp(BO, BB);
659 return solveBlockValueInsertElement(IEI, BB);
662 return solveBlockValueExtractValue(EVI, BB);
665 return solveBlockValueIntrinsic(
II, BB);
669 <<
"' - unknown inst def found.\n");
674 bool IsDereferenced =
true) {
688 if (
MI->isVolatile())
return;
692 if (!Len || Len->isZero())
return;
698 for (
auto &U : CB->args()) {
699 if (U->getType()->isPointerTy() &&
700 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
707bool LazyValueInfoImpl::isNonNullAtEndOfBlock(
Value *Val,
BasicBlock *BB) {
713 return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
714 NonNullPointerSet NonNullPointers;
715 for (Instruction &
I : *BB)
717 return NonNullPointers;
721std::optional<ValueLatticeElement>
722LazyValueInfoImpl::solveBlockValueNonLocal(
Value *Val,
BasicBlock *BB) {
723 ValueLatticeElement
Result;
742 std::optional<BBLatticeElementMap> PredLatticeElements;
744 PredLatticeElements = std::make_optional<BBLatticeElementMap>();
749 std::optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
754 Result.mergeIn(*EdgeResult);
758 if (
Result.isOverdefined()) {
760 <<
"' - overdefined because of pred '"
761 << Pred->getName() <<
"' (non local).\n");
765 PredLatticeElements->insert({Pred, *EdgeResult});
769 TheCache.insertPredecessorResults(Val, BB, *PredLatticeElements);
776std::optional<ValueLatticeElement>
778 ValueLatticeElement
Result;
783 std::optional<BBLatticeElementMap> PredLatticeElements;
785 PredLatticeElements = std::make_optional<BBLatticeElementMap>();
792 std::optional<ValueLatticeElement> EdgeResult =
793 getEdgeValue(PhiVal, PhiBB, BB, PN);
798 Result.mergeIn(*EdgeResult);
802 if (
Result.isOverdefined()) {
804 <<
"' - overdefined because of pred (local).\n");
810 PredLatticeElements->insert({PhiBB, *EdgeResult});
814 TheCache.insertPredecessorResults(PN, BB, *PredLatticeElements);
817 assert(!
Result.isOverdefined() &&
"Possible PHI in entry block?");
823void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
830 for (
auto &AssumeVH : AC->assumptionsFor(Val)) {
844 *
I,
I->bundle_op_info_begin()[AssumeVH.Index])) {
847 switch (RK.AttrKind) {
848 case Attribute::NonNull:
853 case Attribute::Dereferenceable:
865 BBLV = BBLV.
intersect(*getValueFromCondition(Val,
I->getArgOperand(0),
872 if (GuardDecl && !GuardDecl->use_empty() &&
874 for (Instruction &
I :
889 isNonNullAtEndOfBlock(Val, BB))
894std::optional<ValueLatticeElement>
897 std::optional<ValueLatticeElement> OptTrueVal =
898 getBlockValue(
SI->getTrueValue(), BB, SI);
901 ValueLatticeElement &
TrueVal = *OptTrueVal;
903 std::optional<ValueLatticeElement> OptFalseVal =
904 getBlockValue(
SI->getFalseValue(), BB, SI);
907 ValueLatticeElement &
FalseVal = *OptFalseVal;
910 const ConstantRange &TrueCR =
TrueVal.asConstantRange(
SI->getType());
911 const ConstantRange &FalseCR =
FalseVal.asConstantRange(
SI->getType());
918 ((
LHS ==
SI->getTrueValue() &&
RHS ==
SI->getFalseValue()) ||
919 (
RHS ==
SI->getTrueValue() &&
LHS ==
SI->getFalseValue()))) {
920 ConstantRange ResultCR = [&]() {
925 return TrueCR.
smin(FalseCR);
927 return TrueCR.
umin(FalseCR);
929 return TrueCR.
smax(FalseCR);
931 return TrueCR.
umax(FalseCR);
935 ResultCR,
TrueVal.isConstantRangeIncludingUndef() ||
936 FalseVal.isConstantRangeIncludingUndef());
940 if (
LHS ==
SI->getTrueValue())
942 TrueCR.
abs(),
TrueVal.isConstantRangeIncludingUndef());
943 if (
LHS ==
SI->getFalseValue())
945 FalseCR.
abs(),
FalseVal.isConstantRangeIncludingUndef());
950 if (
LHS ==
SI->getTrueValue())
953 if (
LHS ==
SI->getFalseValue())
967 TrueVal.intersect(*getValueFromCondition(
SI->getTrueValue(),
Cond,
971 FalseVal.intersect(*getValueFromCondition(
SI->getFalseValue(),
Cond,
980std::optional<ConstantRange>
982 std::optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
985 return OptVal->asConstantRange(
V->getType());
988std::optional<ValueLatticeElement>
994 case Instruction::Trunc:
995 case Instruction::SExt:
996 case Instruction::ZExt:
1001 <<
"' - overdefined (unknown cast).\n");
1008 std::optional<ConstantRange> LHSRes = getRangeFor(CI->
getOperand(0), CI, BB);
1011 return std::nullopt;
1012 const ConstantRange &LHSRange = *LHSRes;
1019 ConstantRange Res = ConstantRange::getEmpty(ResultBitWidth);
1021 Res = LHSRange.
truncate(ResultBitWidth, Trunc->getNoWrapKind());
1028std::optional<ValueLatticeElement>
1029LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
1036 auto ThreadBinOpOverSelect =
1037 [&](
Value *
X,
const ConstantRange &CRX, SelectInst *
Y,
1038 bool XIsLHS) -> std::optional<ValueLatticeElement> {
1043 return std::nullopt;
1046 return std::nullopt;
1048 return std::nullopt;
1050 ConstantRange TrueX =
1051 CRX.intersectWith(getValueFromCondition(
X,
Cond,
true,
1053 ->asConstantRange(
X->getType()));
1054 ConstantRange FalseX =
1055 CRX.intersectWith(getValueFromCondition(
X,
Cond,
false,
1057 ->asConstantRange(
X->getType()));
1063 OpFn(TrueX, TrueY).unionWith(OpFn(FalseX, FalseY)));
1065 OpFn(TrueY, TrueX).unionWith(OpFn(FalseY, FalseX)));
1072 std::optional<ConstantRange> LHSRes = getRangeFor(
LHS,
I, BB);
1074 return std::nullopt;
1078 if (
auto Res = ThreadBinOpOverSelect(
LHS, *LHSRes, SI,
true))
1082 std::optional<ConstantRange> RHSRes = getRangeFor(
RHS,
I, BB);
1084 return std::nullopt;
1088 if (
auto Res = ThreadBinOpOverSelect(
RHS, *RHSRes, SI,
false))
1092 const ConstantRange &LHSRange = *LHSRes;
1093 const ConstantRange &RHSRange = *RHSRes;
1095 std::optional<ValueLatticeElement> MergedResult =
1099 return MergedResult;
1101 std::optional<BBLatticeElementMap> PredLHS =
1102 TheCache.getCachedPredecessorInfo(
LHS, BB);
1104 return MergedResult;
1105 std::optional<BBLatticeElementMap> PredRHS =
1106 TheCache.getCachedPredecessorInfo(
RHS, BB);
1108 return MergedResult;
1110 const BBLatticeElementMap &LHSPredMap = *PredLHS;
1111 const BBLatticeElementMap &RHSPredMap = *PredRHS;
1113 BBLatticeElementMap PredLatticeElements;
1114 ValueLatticeElement OverallPredResult;
1116 auto LHSIt = LHSPredMap.find_as(Pred);
1117 if (LHSIt == LHSPredMap.end())
1118 return MergedResult;
1119 const ValueLatticeElement &LHSFromPred = LHSIt->second;
1120 std::optional<ConstantRange> LHSFromPredRes =
1122 if (!LHSFromPredRes)
1123 return MergedResult;
1125 auto RHSIt = RHSPredMap.find_as(Pred);
1126 if (RHSIt == RHSPredMap.end())
1127 return MergedResult;
1128 const ValueLatticeElement &RHSFromPred = RHSIt->second;
1129 std::optional<ConstantRange> RHSFromPredRes =
1131 if (!RHSFromPredRes)
1132 return MergedResult;
1134 const ConstantRange &LHSFromPredRange = *LHSFromPredRes;
1135 const ConstantRange &RHSFromPredRange = *RHSFromPredRes;
1136 std::optional<ValueLatticeElement> PredResult =
1139 return MergedResult;
1140 if (PredResult->isOverdefined()) {
1142 dbgs() <<
" pred BB '" << Pred->getName() <<
"' for BB '"
1144 <<
"' overdefined. Discarding all predecessor intervals.\n");
1145 return MergedResult;
1147 PredLatticeElements.insert({Pred, *PredResult});
1148 OverallPredResult.
mergeIn(*PredResult);
1154 TheCache.insertPredecessorResults(
I, BB, PredLatticeElements);
1157 <<
" to: " << OverallPredResult <<
".\n");
1160 return OverallPredResult;
1163 << OverallPredResult <<
" and " << MergedResult <<
".\n");
1164 return MergedResult->intersect(OverallPredResult);
1167std::optional<ValueLatticeElement>
1170 "all operands to binary operators are sized");
1172 unsigned NoWrapKind = OBO->getNoWrapKind();
1173 return solveBlockValueBinaryOpImpl(
1175 [BO, NoWrapKind](
const ConstantRange &CR1,
const ConstantRange &CR2) {
1180 return solveBlockValueBinaryOpImpl(
1181 BO, BB, [BO](
const ConstantRange &CR1,
const ConstantRange &CR2) {
1186std::optional<ValueLatticeElement>
1189 return solveBlockValueBinaryOpImpl(
1190 WO, BB, [WO](
const ConstantRange &CR1,
const ConstantRange &CR2) {
1195std::optional<ValueLatticeElement>
1200 <<
"' - unknown intrinsic.\n");
1206 std::optional<ConstantRange>
Range = getRangeFor(
Op,
II, BB);
1208 return std::nullopt;
1217std::optional<ValueLatticeElement>
1220 std::optional<ValueLatticeElement> OptEltVal =
1223 return std::nullopt;
1224 ValueLatticeElement &Res = *OptEltVal;
1226 std::optional<ValueLatticeElement> OptVecVal =
1229 return std::nullopt;
1235 if (OptEltVal->isConstant())
1242std::optional<ValueLatticeElement>
1247 return solveBlockValueOverflowIntrinsic(WO, BB);
1254 return getBlockValue(V, BB, EVI);
1257 <<
"' - overdefined (unknown extractvalue).\n");
1295std::optional<ValueLatticeElement>
1300 bool UseBlockValue) {
1304 RHSRange = ConstantRange(CI->getValue());
1305 }
else if (UseBlockValue) {
1306 std::optional<ValueLatticeElement>
R =
1309 return std::nullopt;
1313 ConstantRange TrueValues =
1318static std::optional<ConstantRange>
1321 bool Invert =
false;
1328 if (
RHS.isMaxSignedValue())
1329 return std::nullopt;
1333 if (
auto CR = Fn(
RHS))
1334 return Invert ? CR->inverse() : CR;
1335 return std::nullopt;
1341 unsigned BitWidth =
RHS->getType()->getScalarSizeInBits();
1359std::optional<ValueLatticeElement> LazyValueInfoImpl::getValueFromICmpCondition(
1360 Value *Val,
ICmpInst *ICI,
bool isTrueDest,
bool UseBlockValue) {
1384 return getValueFromSimpleICmpCondition(EdgePred,
RHS,
Offset, ICI,
1389 return getValueFromSimpleICmpCondition(SwappedPred,
LHS,
Offset, ICI,
1395 const APInt *
Mask, *
C;
1429 const APInt *ShAmtC;
1434 EdgePred, *
C, [&](
const APInt &
RHS) -> std::optional<ConstantRange> {
1435 APInt
New =
RHS << *ShAmtC;
1436 if ((
New.ashr(*ShAmtC)) !=
RHS)
1437 return std::nullopt;
1505std::optional<ValueLatticeElement>
1507 bool IsTrueDest,
bool UseBlockValue,
1510 return getValueFromICmpCondition(Val, ICI, IsTrueDest, UseBlockValue);
1513 return getValueFromTrunc(Val, Trunc, IsTrueDest);
1525 return getValueFromCondition(Val,
N, !IsTrueDest, UseBlockValue,
Depth);
1536 std::optional<ValueLatticeElement> LV =
1537 getValueFromCondition(Val, L, IsTrueDest, UseBlockValue,
Depth);
1539 return std::nullopt;
1540 std::optional<ValueLatticeElement> RV =
1541 getValueFromCondition(Val, R, IsTrueDest, UseBlockValue,
Depth);
1543 return std::nullopt;
1549 if (IsTrueDest ^ IsAnd) {
1554 return LV->intersect(*RV);
1575 const APInt &OpConstVal,
1590 assert((Op0Match || Op1Match) &&
1591 "Operand 0 nor Operand 1 isn't a match");
1606std::optional<ValueLatticeElement>
1614 if (BI->isConditional() &&
1615 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1616 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1617 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1618 "BBTo isn't a successor of BBFrom");
1619 Value *Condition = BI->getCondition();
1624 if (Condition == Val)
1630 std::optional<ValueLatticeElement>
Result =
1631 getValueFromCondition(Val, Condition, isTrueDest, UseBlockValue);
1633 return std::nullopt;
1635 if (!
Result->isOverdefined())
1639 assert(
Result->isOverdefined() &&
"Result isn't overdefined");
1653 APInt ConditionVal(1, isTrueDest ? 1 : 0);
1656 ValueLatticeElement OpLatticeVal =
1657 *getValueFromCondition(Usr->getOperand(0), Condition,
1661 const unsigned ResultBitWidth =
1662 Usr->getType()->getScalarSizeInBits();
1687 for (
unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1688 Value *
Op = Usr->getOperand(i);
1689 ValueLatticeElement OpLatticeVal = *getValueFromCondition(
1690 Op, Condition, isTrueDest,
false);
1691 if (std::optional<APInt> OpConst =
1700 if (!
Result->isOverdefined())
1708 Value *Condition =
SI->getCondition();
1711 bool ValUsesConditionAndMayBeFoldable =
false;
1712 if (Condition != Val) {
1717 if (!ValUsesConditionAndMayBeFoldable)
1720 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1721 "Condition != Val nor Val doesn't use Condition");
1723 bool DefaultCase =
SI->getDefaultDest() == BBTo;
1725 ConstantRange EdgesVals(
BitWidth, DefaultCase);
1727 for (
auto Case :
SI->cases()) {
1728 APInt CaseValue = Case.getCaseValue()->getValue();
1729 ConstantRange EdgeVal(CaseValue);
1730 if (ValUsesConditionAndMayBeFoldable) {
1733 ValueLatticeElement EdgeLatticeVal =
1746 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1747 EdgesVals = EdgesVals.difference(EdgeVal);
1748 }
else if (Case.getCaseSuccessor() == BBTo)
1749 EdgesVals = EdgesVals.unionWith(EdgeVal);
1758std::optional<ValueLatticeElement>
1765 std::optional<ValueLatticeElement> LocalResult =
1766 getEdgeValueLocal(Val, BBFrom, BBTo,
true);
1768 return std::nullopt;
1774 std::optional<ValueLatticeElement> OptInBlock =
1777 return std::nullopt;
1778 ValueLatticeElement &
InBlock = *OptInBlock;
1788 intersectAssumeOrGuardBlockValueConstantRange(Val,
InBlock, CxtI);
1790 return LocalResult->intersect(
InBlock);
1795 LLVM_DEBUG(
dbgs() <<
"LVI Getting block end value " << *V <<
" at '"
1798 assert(BlockValueStack.empty() && BlockValueSet.empty());
1799 std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
1802 OptResult = getBlockValue(V, BB, CxtI);
1803 assert(OptResult &&
"Value not available after solving");
1820 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1829 LLVM_DEBUG(
dbgs() <<
"LVI Getting edge value " << *V <<
" from '"
1833 std::optional<ValueLatticeElement> Result =
1834 getEdgeValue(V, FromBB, ToBB, CxtI);
1840 Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1854 const Use *CurrU = &U;
1856 const unsigned MaxUsesToInspect = 3;
1857 for (
unsigned I = 0;
I < MaxUsesToInspect; ++
I) {
1858 std::optional<ValueLatticeElement> CondVal;
1865 if (CurrU->getOperandNo() == 1)
1867 *getValueFromCondition(V,
SI->getCondition(),
true,
1869 else if (CurrU->getOperandNo() == 2)
1871 *getValueFromCondition(V,
SI->getCondition(),
false,
1875 CondVal = *getEdgeValueLocal(V,
PHI->getIncomingBlock(*CurrU),
1876 PHI->getParent(),
false);
1890 if (!CurrI->hasOneUse() ||
1901 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1911 if (
auto *Impl = Info.getImpl())
1929 assert(M &&
"getCache() called with a null Module");
1944 if (
auto *Impl = getImpl()) {
1951 FunctionAnalysisManager::Invalidator &Inv) {
1977 V = V->stripPointerCasts();
1991 getOrCreateImpl(BB->
getModule()).getValueInBlock(V, BB, CxtI);
1993 if (Result.isConstant())
1994 return Result.getConstant();
1995 if (Result.isConstantRange()) {
1998 return ConstantInt::get(V->getType(), *SingleVal);
2004 bool UndefAllowed) {
2007 getOrCreateImpl(BB->
getModule()).getValueInBlock(V, BB, CxtI);
2008 return Result.asConstantRange(V->getType(), UndefAllowed);
2012 bool UndefAllowed) {
2015 getOrCreateImpl(Inst->getModule()).getValueAtUse(U);
2016 return Result.asConstantRange(U->getType(), UndefAllowed);
2026 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
2028 if (Result.isConstant())
2029 return Result.getConstant();
2030 if (Result.isConstantRange()) {
2033 return ConstantInt::get(V->getType(), *SingleVal);
2044 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
2046 return Result.asConstantRange(V->getType(),
true);
2097 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
2104 bool UseBlockValue) {
2111 if (V->getType()->isPointerTy() &&
C->isNullValue() &&
2120 auto &Impl = getOrCreateImpl(M);
2122 UseBlockValue ? Impl.getValueInBlock(V, CxtI->
getParent(), CxtI)
2123 : Impl.getValueAt(V, CxtI);
2163 if (
PHI->getParent() == BB) {
2165 for (
unsigned i = 0, e =
PHI->getNumIncomingValues(); i < e; i++) {
2174 Baseline = (i == 0) ? Result
2175 : (Baseline == Result ? Baseline
2194 while (++PI != PE) {
2196 if (Ret != Baseline)
2211 bool UseBlockValue) {
2221 if (UseBlockValue) {
2224 getOrCreateImpl(M).getValueInBlock(LHS, CxtI->
getParent(), CxtI);
2225 if (L.isOverdefined())
2229 getOrCreateImpl(M).getValueInBlock(RHS, CxtI->
getParent(), CxtI);
2231 return L.getCompare(Pred, Ty, R, M->getDataLayout());
2238 if (
auto *Impl = getImpl())
2239 Impl->threadEdge(PredBB, OldSucc, NewSucc);
2243 if (
auto *Impl = getImpl())
2244 Impl->forgetValue(V);
2248 if (
auto *Impl = getImpl())
2249 Impl->eraseBlock(BB);
2253 if (
auto *Impl = getImpl())
2258 if (
auto *Impl = getImpl())
2259 Impl->printLVI(
F, DTree, OS);
2263void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
2267 for (
const auto &Arg :
F->args()) {
2270 if (Result.isUnknown())
2272 OS <<
"; LatticeVal for: '" << Arg <<
"' is: " << Result <<
"\n";
2280void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2281 const Instruction *
I, formatted_raw_ostream &OS) {
2284 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2290 auto printResult = [&](
const BasicBlock *BB) {
2291 if (!BlocksContainingLVI.
insert(BB).second)
2295 OS <<
"; LatticeVal for: '" << *
I <<
"' in BB: '";
2297 OS <<
"' is: " <<
Result <<
"\n";
2300 printResult(ParentBB);
2303 for (
const auto *BBSucc :
successors(ParentBB))
2305 printResult(BBSucc);
2308 for (
const auto *U :
I->users())
2311 printResult(UseI->getParent());
2317 OS <<
"LVI for function '" <<
F.getName() <<
"':\n";
2320 LVI.printLVI(
F, DTree, OS);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseSet and SmallDenseSet classes.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
static bool isOperationFoldable(User *Usr)
static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet, bool IsDereferenced=true)
static void AddNonNullPointersByInstruction(Instruction *I, NonNullPointerSet &PtrSet)
static std::optional< ConstantRange > getRangeViaSLT(CmpInst::Predicate Pred, APInt RHS, function_ref< std::optional< ConstantRange >(const APInt &)> Fn)
static const unsigned MaxProcessedPerValue
static ValueLatticeElement getValueFromICmpCtpop(ICmpInst::Predicate Pred, Value *RHS)
Get value range for a "ctpop(Val) Pred RHS" condition.
static bool usesOperand(User *Usr, Value *Op)
static ValueLatticeElement constantFoldUser(User *Usr, Value *Op, const APInt &OpConstVal, const DataLayout &DL)
static ValueLatticeElement getFromRangeMetadata(Instruction *BBI)
lazy value Lazy Value Information static true cl::opt< bool > PerPredRanges("lvi-per-pred-ranges", cl::Hidden, cl::init(false), cl::desc("Enable tracking of ranges for a value in a block for" "each block predecessor (default = false)"))
static Constant * getPredicateResult(CmpInst::Predicate Pred, Constant *C, const ValueLatticeElement &Val, const DataLayout &DL)
static ValueLatticeElement getValueFromOverflowCondition(Value *Val, WithOverflowInst *WO, bool IsTrueDest)
static bool isKnownNonConstant(Value *V)
Returns true if we can statically tell that this value will never be a "useful" constant.
static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val, ICmpInst::Predicate Pred)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
const SmallVectorImpl< MachineOperand > & Cond
static bool InBlock(const Value *V, const BasicBlock *BB)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Class for arbitrary precision integers.
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
This class represents an incoming formal argument to a Function.
A function analysis which provides an AssumptionCache.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
LLVM_ABI unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Value handle with callbacks on RAUW and destruction.
This is the base class for all instructions that perform data casts.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getDestTy() const
Return the destination type, as a convenience.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Predicate getPredicate() const
Return the predicate for this instruction.
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
This class represents a range of values.
LLVM_ABI ConstantRange subtract(const APInt &CI) const
Subtract the specified constant from the endpoints of this constant range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI ConstantRange castOp(Instruction::CastOps CastOp, uint32_t BitWidth) const
Return a new range representing the possible values resulting from an application of the specified ca...
LLVM_ABI ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
LLVM_ABI APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
static LLVM_ABI ConstantRange intrinsic(Intrinsic::ID IntrinsicID, ArrayRef< ConstantRange > Ops)
Compute range of intrinsic result for the given operand ranges.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
LLVM_ABI ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
static LLVM_ABI bool isIntrinsicSupported(Intrinsic::ID IntrinsicID)
Returns true if ConstantRange calculations are supported for intrinsic with IntrinsicID.
LLVM_ABI ConstantRange overflowingBinaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other, unsigned NoWrapKind) const
Return a new range representing the possible values resulting from an application of the specified ov...
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
static LLVM_ABI ConstantRange makeMaskNotEqualRange(const APInt &Mask, const APInt &C)
Initialize a range containing all values X that satisfy (X & Mask) / != C.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
LLVM_ABI ConstantRange smin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed minimum of a value in thi...
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
LLVM_ABI ConstantRange binaryOp(Instruction::BinaryOps BinOp, const ConstantRange &Other) const
Return a new range representing the possible values resulting from an application of the specified bi...
static LLVM_ABI ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp, const APInt &Other, unsigned NoWrapKind)
Produce the range that contains X if and only if "X BinOp Other" does not wrap.
This is an important base class in LLVM.
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
LLVM_ABI ConstantRange toConstantRange() const
Convert constant to an approximate constant range.
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
A parsed version of the target data layout string in and methods for querying it.
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
FunctionPass class - This class is used to implement most global optimizations.
Module * getParent()
Get the module that this global value is contained inside of...
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
This instruction inserts a single (scalar) element into a VectorType value.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
Analysis to compute lazy value information.
Result run(Function &F, FunctionAnalysisManager &FAM)
ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
This is the query interface to determine the lattice value for the specified Value* that is true on t...
ValueLatticeElement getValueAt(Value *V, Instruction *CxtI)
This is the query interface to determine the lattice value for the specified Value* at the specified ...
void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc)
This is the update interface to inform the cache that an edge from PredBB to OldSucc has been threade...
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Printing the LazyValueInfo Analysis.
void forgetValue(Value *V)
This is part of the update interface to remove information related to this value from the cache.
void eraseBlock(BasicBlock *BB)
This is part of the update interface to inform the cache that a block has been deleted.
void clear()
Complete flush all previously computed values.
LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL, Function *GuardDecl)
ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB, Instruction *CxtI=nullptr)
This is the query interface to determine the lattice value for the specified Value* at the context in...
ValueLatticeElement getValueAtUse(const Use &U)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Wrapper around LazyValueInfo.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LazyValueInfoWrapperPass()
This pass computes, caches, and vends lazy value constraint information.
void eraseBlock(BasicBlock *BB)
Inform the analysis cache that we have erased a block.
ConstantRange getConstantRangeAtUse(const Use &U, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the value at a specific use-site.
ConstantRange getConstantRange(Value *V, Instruction *CxtI, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
void threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc, BasicBlock *NewSucc)
Inform the analysis cache that we have threaded an edge from PredBB to OldSucc to be from PredBB to N...
Constant * getPredicateOnEdge(CmpInst::Predicate Pred, Value *V, Constant *C, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value comparison with a constant is known to be true or false on the ...
Constant * getConstantOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Determine whether the specified value is known to be a constant on the specified edge.
ConstantRange getConstantRangeOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB, Instruction *CxtI=nullptr)
Return the ConstantRage constraint that is known to hold for the specified value on the specified edg...
Constant * getConstant(Value *V, Instruction *CxtI)
Determine whether the specified value is known to be a constant at the specified instruction.
void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS)
Print the \LazyValueInfo Analysis.
void forgetValue(Value *V)
Remove information related to this value from the cache.
void clear()
Complete flush all previously computed values.
Constant * getPredicateAt(CmpInst::Predicate Pred, Value *V, Constant *C, Instruction *CxtI, bool UseBlockValue)
Determine whether the specified value comparison with a constant is known to be true or false at the ...
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &Inv)
Handle invalidation events in the new pass manager.
An instruction for reading from memory.
This is the common base class for memset/memcpy/memmove.
This class wraps the llvm.memcpy/memmove intrinsics.
A Module instance is used to store all the information related to an LLVM module.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
AnalysisType & getAnalysis() const
getAnalysis<AnalysisType>() - This function is used by subclasses to get to the analysis information ...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
This class represents a truncation of integer types.
unsigned getNoWrapKind() const
Returns the no-wrap kind of the operation.
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property.
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
A Use represents the edge between a Value definition and its users.
Value * getOperand(unsigned i) const
This class represents lattice values for constants.
static ValueLatticeElement getRange(ConstantRange CR, bool MayIncludeUndef=false)
bool isOverdefined() const
static ValueLatticeElement getNot(Constant *C)
ConstantRange asConstantRange(unsigned BW, bool UndefAllowed=false) const
bool isNotConstant() const
std::optional< APInt > asConstantInteger() const
const ConstantRange & getConstantRange(bool UndefAllowed=true) const
Returns the constant range for this value.
bool isConstantRange(bool UndefAllowed=true) const
Returns true if this value is a constant range.
static ValueLatticeElement get(Constant *C)
Constant * getNotConstant() const
LLVM_ABI ValueLatticeElement intersect(const ValueLatticeElement &Other) const
Combine two sets of facts about the same value into a single set of facts.
Constant * getConstant() const
bool mergeIn(const ValueLatticeElement &RHS, MergeOptions Opts=MergeOptions())
Updates this object to approximate both this object and RHS.
static ValueLatticeElement getOverdefined()
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
iterator find_as(const LookupKeyT &Val)
Alternative version of find() which allows a different, and possibly less expensive,...
bool erase(const ValueT &V)
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
IntrinsicID_match m_Intrinsic()
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
This namespace contains all of the command line option processing machinery.
@ User
could "use" a pointer
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
static ConstantRange getRange(Value *Op, SCCPSolver &Solver, const SmallPtrSetImpl< Value * > &InsertedValues)
Helper for getting ranges from Solver.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
LLVM_ABI FunctionPass * createLazyValueInfoPass()
createLazyValueInfoPass - This creates an instance of the LazyValueInfo pass.
LLVM_ABI RetainedKnowledge getKnowledgeFromBundle(AssumeInst &Assume, const CallBase::BundleOpInfo &BOI)
This extracts the Knowledge from an element of an operand bundle.
auto dyn_cast_or_null(const Y &Val)
constexpr unsigned MaxAnalysisRecursionDepth
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
static bool hasSingleValue(const ValueLatticeElement &Val)
constexpr unsigned BitWidth
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
A special type used by analysis passes to provide an address that identifies that particular analysis...
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?