LLVM 20.0.0git
LazyValueInfo.cpp
Go to the documentation of this file.
1//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
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 defines the interface for lazy computation of value constraint
10// information.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/STLExtras.h"
25#include "llvm/IR/CFG.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/Module.h"
37#include "llvm/IR/ValueHandle.h"
39#include "llvm/Support/Debug.h"
43#include <optional>
44using namespace llvm;
45using namespace PatternMatch;
46
47#define DEBUG_TYPE "lazy-value-info"
48
49// This is the number of worklist items we will process to try to discover an
50// answer for a given value.
51static const unsigned MaxProcessedPerValue = 500;
52
56}
58 "Lazy Value Information Analysis", false, true)
63
64namespace llvm {
66 return new LazyValueInfoWrapperPass();
67}
68} // namespace llvm
69
70AnalysisKey LazyValueAnalysis::Key;
71
72/// Returns true if this lattice value represents at most one possible value.
73/// This is as precise as any lattice value can get while still representing
74/// reachable code.
75static bool hasSingleValue(const ValueLatticeElement &Val) {
76 if (Val.isConstantRange() &&
78 // Integer constants are single element ranges
79 return true;
80 if (Val.isConstant())
81 // Non integer constants
82 return true;
83 return false;
84}
85
86//===----------------------------------------------------------------------===//
87// LazyValueInfoCache Decl
88//===----------------------------------------------------------------------===//
89
90namespace {
91 /// A callback value handle updates the cache when values are erased.
92 class LazyValueInfoCache;
93 struct LVIValueHandle final : public CallbackVH {
94 LazyValueInfoCache *Parent;
95
96 LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
97 : CallbackVH(V), Parent(P) { }
98
99 void deleted() override;
100 void allUsesReplacedWith(Value *V) override {
101 deleted();
102 }
103 };
104} // end anonymous namespace
105
106namespace {
107using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
108
109/// This is the cache kept by LazyValueInfo which
110/// maintains information about queries across the clients' queries.
111class LazyValueInfoCache {
112 /// This is all of the cached information for one basic block. It contains
113 /// the per-value lattice elements, as well as a separate set for
114 /// overdefined values to reduce memory usage. Additionally pointers
115 /// dereferenced in the block are cached for nullability queries.
116 struct BlockCacheEntry {
118 SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
119 // std::nullopt indicates that the nonnull pointers for this basic block
120 // block have not been computed yet.
121 std::optional<NonNullPointerSet> NonNullPointers;
122 };
123
124 /// Cached information per basic block.
125 DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
126 BlockCache;
127 /// Set of value handles used to erase values from the cache on deletion.
129
130 const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
131 auto It = BlockCache.find_as(BB);
132 if (It == BlockCache.end())
133 return nullptr;
134 return It->second.get();
135 }
136
137 BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
138 auto It = BlockCache.find_as(BB);
139 if (It == BlockCache.end())
140 It = BlockCache.insert({BB, std::make_unique<BlockCacheEntry>()}).first;
141
142 return It->second.get();
143 }
144
145 void addValueHandle(Value *Val) {
146 auto HandleIt = ValueHandles.find_as(Val);
147 if (HandleIt == ValueHandles.end())
148 ValueHandles.insert({Val, this});
149 }
150
151public:
152 void insertResult(Value *Val, BasicBlock *BB,
153 const ValueLatticeElement &Result) {
154 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
155
156 // Insert over-defined values into their own cache to reduce memory
157 // overhead.
158 if (Result.isOverdefined())
159 Entry->OverDefined.insert(Val);
160 else
161 Entry->LatticeElements.insert({Val, Result});
162
163 addValueHandle(Val);
164 }
165
166 std::optional<ValueLatticeElement> getCachedValueInfo(Value *V,
167 BasicBlock *BB) const {
168 const BlockCacheEntry *Entry = getBlockEntry(BB);
169 if (!Entry)
170 return std::nullopt;
171
172 if (Entry->OverDefined.count(V))
174
175 auto LatticeIt = Entry->LatticeElements.find_as(V);
176 if (LatticeIt == Entry->LatticeElements.end())
177 return std::nullopt;
178
179 return LatticeIt->second;
180 }
181
182 bool
183 isNonNullAtEndOfBlock(Value *V, BasicBlock *BB,
184 function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
185 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
186 if (!Entry->NonNullPointers) {
187 Entry->NonNullPointers = InitFn(BB);
188 for (Value *V : *Entry->NonNullPointers)
189 addValueHandle(V);
190 }
191
192 return Entry->NonNullPointers->count(V);
193 }
194
195 /// clear - Empty the cache.
196 void clear() {
197 BlockCache.clear();
198 ValueHandles.clear();
199 }
200
201 /// Inform the cache that a given value has been deleted.
202 void eraseValue(Value *V);
203
204 /// This is part of the update interface to inform the cache
205 /// that a block has been deleted.
206 void eraseBlock(BasicBlock *BB);
207
208 /// Updates the cache to remove any influence an overdefined value in
209 /// OldSucc might have (unless also overdefined in NewSucc). This just
210 /// flushes elements from the cache and does not add any.
211 void threadEdgeImpl(BasicBlock *OldSucc, BasicBlock *NewSucc);
212};
213} // namespace
214
215void LazyValueInfoCache::eraseValue(Value *V) {
216 for (auto &Pair : BlockCache) {
217 Pair.second->LatticeElements.erase(V);
218 Pair.second->OverDefined.erase(V);
219 if (Pair.second->NonNullPointers)
220 Pair.second->NonNullPointers->erase(V);
221 }
222
223 auto HandleIt = ValueHandles.find_as(V);
224 if (HandleIt != ValueHandles.end())
225 ValueHandles.erase(HandleIt);
226}
227
228void LVIValueHandle::deleted() {
229 // This erasure deallocates *this, so it MUST happen after we're done
230 // using any and all members of *this.
231 Parent->eraseValue(*this);
232}
233
234void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
235 BlockCache.erase(BB);
236}
237
238void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
239 BasicBlock *NewSucc) {
240 // When an edge in the graph has been threaded, values that we could not
241 // determine a value for before (i.e. were marked overdefined) may be
242 // possible to solve now. We do NOT try to proactively update these values.
243 // Instead, we clear their entries from the cache, and allow lazy updating to
244 // recompute them when needed.
245
246 // The updating process is fairly simple: we need to drop cached info
247 // for all values that were marked overdefined in OldSucc, and for those same
248 // values in any successor of OldSucc (except NewSucc) in which they were
249 // also marked overdefined.
250 std::vector<BasicBlock*> worklist;
251 worklist.push_back(OldSucc);
252
253 const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
254 if (!Entry || Entry->OverDefined.empty())
255 return; // Nothing to process here.
256 SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
257 Entry->OverDefined.end());
258
259 // Use a worklist to perform a depth-first search of OldSucc's successors.
260 // NOTE: We do not need a visited list since any blocks we have already
261 // visited will have had their overdefined markers cleared already, and we
262 // thus won't loop to their successors.
263 while (!worklist.empty()) {
264 BasicBlock *ToUpdate = worklist.back();
265 worklist.pop_back();
266
267 // Skip blocks only accessible through NewSucc.
268 if (ToUpdate == NewSucc) continue;
269
270 // If a value was marked overdefined in OldSucc, and is here too...
271 auto OI = BlockCache.find_as(ToUpdate);
272 if (OI == BlockCache.end() || OI->second->OverDefined.empty())
273 continue;
274 auto &ValueSet = OI->second->OverDefined;
275
276 bool changed = false;
277 for (Value *V : ValsToClear) {
278 if (!ValueSet.erase(V))
279 continue;
280
281 // If we removed anything, then we potentially need to update
282 // blocks successors too.
283 changed = true;
284 }
285
286 if (!changed) continue;
287
288 llvm::append_range(worklist, successors(ToUpdate));
289 }
290}
291
292namespace llvm {
293namespace {
294/// An assembly annotator class to print LazyValueCache information in
295/// comments.
296class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
297 LazyValueInfoImpl *LVIImpl;
298 // While analyzing which blocks we can solve values for, we need the dominator
299 // information.
300 DominatorTree &DT;
301
302public:
303 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
304 : LVIImpl(L), DT(DTree) {}
305
306 void emitBasicBlockStartAnnot(const BasicBlock *BB,
307 formatted_raw_ostream &OS) override;
308
309 void emitInstructionAnnot(const Instruction *I,
310 formatted_raw_ostream &OS) override;
311};
312} // namespace
313// The actual implementation of the lazy analysis and update.
315
316 /// Cached results from previous queries
317 LazyValueInfoCache TheCache;
318
319 /// This stack holds the state of the value solver during a query.
320 /// It basically emulates the callstack of the naive
321 /// recursive value lookup process.
323
324 /// Keeps track of which block-value pairs are in BlockValueStack.
326
327 /// Push BV onto BlockValueStack unless it's already in there.
328 /// Returns true on success.
329 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
330 if (!BlockValueSet.insert(BV).second)
331 return false; // It's already in the stack.
332
333 LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
334 << BV.first->getName() << "\n");
335 BlockValueStack.push_back(BV);
336 return true;
337 }
338
339 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
340 const DataLayout &DL; ///< A mandatory DataLayout
341
342 /// Declaration of the llvm.experimental.guard() intrinsic,
343 /// if it exists in the module.
344 Function *GuardDecl;
345
346 std::optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
347 Instruction *CxtI);
348 std::optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
349 BasicBlock *T,
350 Instruction *CxtI = nullptr);
351
352 // These methods process one work item and may add more. A false value
353 // returned means that the work item was not completely processed and must
354 // be revisited after going through the new items.
355 bool solveBlockValue(Value *Val, BasicBlock *BB);
356 std::optional<ValueLatticeElement> solveBlockValueImpl(Value *Val,
357 BasicBlock *BB);
358 std::optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
359 BasicBlock *BB);
360 std::optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
361 BasicBlock *BB);
362 std::optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
363 BasicBlock *BB);
364 std::optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
365 BasicBlock *BB);
366 std::optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
368 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
369 OpFn);
370 std::optional<ValueLatticeElement>
371 solveBlockValueBinaryOp(BinaryOperator *BBI, BasicBlock *BB);
372 std::optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
373 BasicBlock *BB);
374 std::optional<ValueLatticeElement>
375 solveBlockValueOverflowIntrinsic(WithOverflowInst *WO, BasicBlock *BB);
376 std::optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
377 BasicBlock *BB);
378 std::optional<ValueLatticeElement>
379 solveBlockValueInsertElement(InsertElementInst *IEI, BasicBlock *BB);
380 std::optional<ValueLatticeElement>
381 solveBlockValueExtractValue(ExtractValueInst *EVI, BasicBlock *BB);
382 bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
383 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
385 Instruction *BBI);
386
387 void solve();
388
389 // For the following methods, if UseBlockValue is true, the function may
390 // push additional values to the worklist and return nullopt. If
391 // UseBlockValue is false, it will never return nullopt.
392
393 std::optional<ValueLatticeElement>
394 getValueFromSimpleICmpCondition(CmpInst::Predicate Pred, Value *RHS,
395 const APInt &Offset, Instruction *CxtI,
396 bool UseBlockValue);
397
398 std::optional<ValueLatticeElement>
399 getValueFromICmpCondition(Value *Val, ICmpInst *ICI, bool isTrueDest,
400 bool UseBlockValue);
401
402 std::optional<ValueLatticeElement>
403 getValueFromCondition(Value *Val, Value *Cond, bool IsTrueDest,
404 bool UseBlockValue, unsigned Depth = 0);
405
406 std::optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
407 BasicBlock *BBFrom,
408 BasicBlock *BBTo,
409 bool UseBlockValue);
410
411public:
412 /// This is the query interface to determine the lattice value for the
413 /// specified Value* at the context instruction (if specified) or at the
414 /// start of the block.
416 Instruction *CxtI = nullptr);
417
418 /// This is the query interface to determine the lattice value for the
419 /// specified Value* at the specified instruction using only information
420 /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
421 /// recursive query is performed.
423
424 /// This is the query interface to determine the lattice
425 /// value for the specified Value* that is true on the specified edge.
427 BasicBlock *ToBB,
428 Instruction *CxtI = nullptr);
429
431
432 /// Complete flush all previously computed values
433 void clear() {
434 TheCache.clear();
435 }
436
437 /// Printing the LazyValueInfo Analysis.
439 LazyValueInfoAnnotatedWriter Writer(this, DTree);
440 F.print(OS, &Writer);
441 }
442
443 /// This is part of the update interface to remove information related to this
444 /// value from the cache.
445 void forgetValue(Value *V) { TheCache.eraseValue(V); }
446
447 /// This is part of the update interface to inform the cache
448 /// that a block has been deleted.
450 TheCache.eraseBlock(BB);
451 }
452
453 /// This is the update interface to inform the cache that an edge from
454 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
455 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
456
458 Function *GuardDecl)
459 : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
460};
461} // namespace llvm
462
463void LazyValueInfoImpl::solve() {
465 BlockValueStack;
466
467 unsigned processedCount = 0;
468 while (!BlockValueStack.empty()) {
469 processedCount++;
470 // Abort if we have to process too many values to get a result for this one.
471 // Because of the design of the overdefined cache currently being per-block
472 // to avoid naming-related issues (IE it wants to try to give different
473 // results for the same name in different blocks), overdefined results don't
474 // get cached globally, which in turn means we will often try to rediscover
475 // the same overdefined result again and again. Once something like
476 // PredicateInfo is used in LVI or CVP, we should be able to make the
477 // overdefined cache global, and remove this throttle.
478 if (processedCount > MaxProcessedPerValue) {
480 dbgs() << "Giving up on stack because we are getting too deep\n");
481 // Fill in the original values
482 while (!StartingStack.empty()) {
483 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
484 TheCache.insertResult(e.second, e.first,
486 StartingStack.pop_back();
487 }
488 BlockValueSet.clear();
489 BlockValueStack.clear();
490 return;
491 }
492 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
493 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
494 unsigned StackSize = BlockValueStack.size();
495 (void) StackSize;
496
497 if (solveBlockValue(e.second, e.first)) {
498 // The work item was completely processed.
499 assert(BlockValueStack.size() == StackSize &&
500 BlockValueStack.back() == e && "Nothing should have been pushed!");
501#ifndef NDEBUG
502 std::optional<ValueLatticeElement> BBLV =
503 TheCache.getCachedValueInfo(e.second, e.first);
504 assert(BBLV && "Result should be in cache!");
506 dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
507 << *BBLV << "\n");
508#endif
509
510 BlockValueStack.pop_back();
511 BlockValueSet.erase(e);
512 } else {
513 // More work needs to be done before revisiting.
514 assert(BlockValueStack.size() == StackSize + 1 &&
515 "Exactly one element should have been pushed!");
516 }
517 }
518}
519
520std::optional<ValueLatticeElement>
521LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB,
522 Instruction *CxtI) {
523 // If already a constant, there is nothing to compute.
524 if (Constant *VC = dyn_cast<Constant>(Val))
525 return ValueLatticeElement::get(VC);
526
527 if (std::optional<ValueLatticeElement> OptLatticeVal =
528 TheCache.getCachedValueInfo(Val, BB)) {
529 intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
530 return OptLatticeVal;
531 }
532
533 // We have hit a cycle, assume overdefined.
534 if (!pushBlockValue({ BB, Val }))
536
537 // Yet to be resolved.
538 return std::nullopt;
539}
540
542 switch (BBI->getOpcode()) {
543 default:
544 break;
545 case Instruction::Call:
546 case Instruction::Invoke:
547 if (std::optional<ConstantRange> Range = cast<CallBase>(BBI)->getRange())
549 [[fallthrough]];
550 case Instruction::Load:
551 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
552 if (isa<IntegerType>(BBI->getType())) {
555 }
556 break;
557 };
558 // Nothing known - will be intersected with other facts
560}
561
562bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
563 assert(!isa<Constant>(Val) && "Value should not be constant");
564 assert(!TheCache.getCachedValueInfo(Val, BB) &&
565 "Value should not be in cache");
566
567 // Hold off inserting this value into the Cache in case we have to return
568 // false and come back later.
569 std::optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
570 if (!Res)
571 // Work pushed, will revisit
572 return false;
573
574 TheCache.insertResult(Val, BB, *Res);
575 return true;
576}
577
578std::optional<ValueLatticeElement>
579LazyValueInfoImpl::solveBlockValueImpl(Value *Val, BasicBlock *BB) {
580 Instruction *BBI = dyn_cast<Instruction>(Val);
581 if (!BBI || BBI->getParent() != BB)
582 return solveBlockValueNonLocal(Val, BB);
583
584 if (PHINode *PN = dyn_cast<PHINode>(BBI))
585 return solveBlockValuePHINode(PN, BB);
586
587 if (auto *SI = dyn_cast<SelectInst>(BBI))
588 return solveBlockValueSelect(SI, BB);
589
590 // If this value is a nonnull pointer, record it's range and bailout. Note
591 // that for all other pointer typed values, we terminate the search at the
592 // definition. We could easily extend this to look through geps, bitcasts,
593 // and the like to prove non-nullness, but it's not clear that's worth it
594 // compile time wise. The context-insensitive value walk done inside
595 // isKnownNonZero gets most of the profitable cases at much less expense.
596 // This does mean that we have a sensitivity to where the defining
597 // instruction is placed, even if it could legally be hoisted much higher.
598 // That is unfortunate.
599 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
600 if (PT && isKnownNonZero(BBI, DL))
602
603 if (BBI->getType()->isIntOrIntVectorTy()) {
604 if (auto *CI = dyn_cast<CastInst>(BBI))
605 return solveBlockValueCast(CI, BB);
606
607 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
608 return solveBlockValueBinaryOp(BO, BB);
609
610 if (auto *IEI = dyn_cast<InsertElementInst>(BBI))
611 return solveBlockValueInsertElement(IEI, BB);
612
613 if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
614 return solveBlockValueExtractValue(EVI, BB);
615
616 if (auto *II = dyn_cast<IntrinsicInst>(BBI))
617 return solveBlockValueIntrinsic(II, BB);
618 }
619
620 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
621 << "' - unknown inst def found.\n");
622 return getFromRangeMetadata(BBI);
623}
624
625static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
626 // TODO: Use NullPointerIsDefined instead.
627 if (Ptr->getType()->getPointerAddressSpace() == 0)
628 PtrSet.insert(getUnderlyingObject(Ptr));
629}
630
632 Instruction *I, NonNullPointerSet &PtrSet) {
633 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
634 AddNonNullPointer(L->getPointerOperand(), PtrSet);
635 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
636 AddNonNullPointer(S->getPointerOperand(), PtrSet);
637 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
638 if (MI->isVolatile()) return;
639
640 // FIXME: check whether it has a valuerange that excludes zero?
641 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
642 if (!Len || Len->isZero()) return;
643
644 AddNonNullPointer(MI->getRawDest(), PtrSet);
645 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
646 AddNonNullPointer(MTI->getRawSource(), PtrSet);
647 }
648}
649
650bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
653 return false;
654
655 Val = Val->stripInBoundsOffsets();
656 return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
657 NonNullPointerSet NonNullPointers;
658 for (Instruction &I : *BB)
659 AddNonNullPointersByInstruction(&I, NonNullPointers);
660 return NonNullPointers;
661 });
662}
663
664std::optional<ValueLatticeElement>
665LazyValueInfoImpl::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
666 ValueLatticeElement Result; // Start Undefined.
667
668 // If this is the entry block, we must be asking about an argument.
669 if (BB->isEntryBlock()) {
670 assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
671 if (std::optional<ConstantRange> Range = cast<Argument>(Val)->getRange())
674 }
675
676 // Loop over all of our predecessors, merging what we know from them into
677 // result. If we encounter an unexplored predecessor, we eagerly explore it
678 // in a depth first manner. In practice, this has the effect of discovering
679 // paths we can't analyze eagerly without spending compile times analyzing
680 // other paths. This heuristic benefits from the fact that predecessors are
681 // frequently arranged such that dominating ones come first and we quickly
682 // find a path to function entry. TODO: We should consider explicitly
683 // canonicalizing to make this true rather than relying on this happy
684 // accident.
685 for (BasicBlock *Pred : predecessors(BB)) {
686 std::optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
687 if (!EdgeResult)
688 // Explore that input, then return here
689 return std::nullopt;
690
691 Result.mergeIn(*EdgeResult);
692
693 // If we hit overdefined, exit early. The BlockVals entry is already set
694 // to overdefined.
695 if (Result.isOverdefined()) {
696 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
697 << "' - overdefined because of pred '"
698 << Pred->getName() << "' (non local).\n");
699 return Result;
700 }
701 }
702
703 // Return the merged value, which is more precise than 'overdefined'.
704 assert(!Result.isOverdefined());
705 return Result;
706}
707
708std::optional<ValueLatticeElement>
709LazyValueInfoImpl::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
710 ValueLatticeElement Result; // Start Undefined.
711
712 // Loop over all of our predecessors, merging what we know from them into
713 // result. See the comment about the chosen traversal order in
714 // solveBlockValueNonLocal; the same reasoning applies here.
715 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
716 BasicBlock *PhiBB = PN->getIncomingBlock(i);
717 Value *PhiVal = PN->getIncomingValue(i);
718 // Note that we can provide PN as the context value to getEdgeValue, even
719 // though the results will be cached, because PN is the value being used as
720 // the cache key in the caller.
721 std::optional<ValueLatticeElement> EdgeResult =
722 getEdgeValue(PhiVal, PhiBB, BB, PN);
723 if (!EdgeResult)
724 // Explore that input, then return here
725 return std::nullopt;
726
727 Result.mergeIn(*EdgeResult);
728
729 // If we hit overdefined, exit early. The BlockVals entry is already set
730 // to overdefined.
731 if (Result.isOverdefined()) {
732 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
733 << "' - overdefined because of pred (local).\n");
734
735 return Result;
736 }
737 }
738
739 // Return the merged value, which is more precise than 'overdefined'.
740 assert(!Result.isOverdefined() && "Possible PHI in entry block?");
741 return Result;
742}
743
744// If we can determine a constraint on the value given conditions assumed by
745// the program, intersect those constraints with BBLV
746void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
747 Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
748 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
749 if (!BBI)
750 return;
751
752 BasicBlock *BB = BBI->getParent();
753 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
754 if (!AssumeVH)
755 continue;
756
757 // Only check assumes in the block of the context instruction. Other
758 // assumes will have already been taken into account when the value was
759 // propagated from predecessor blocks.
760 auto *I = cast<CallInst>(AssumeVH);
761 if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
762 continue;
763
764 BBLV = BBLV.intersect(*getValueFromCondition(Val, I->getArgOperand(0),
765 /*IsTrueDest*/ true,
766 /*UseBlockValue*/ false));
767 }
768
769 // If guards are not used in the module, don't spend time looking for them
770 if (GuardDecl && !GuardDecl->use_empty() &&
771 BBI->getIterator() != BB->begin()) {
772 for (Instruction &I :
773 make_range(std::next(BBI->getIterator().getReverse()), BB->rend())) {
774 Value *Cond = nullptr;
775 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
776 BBLV = BBLV.intersect(*getValueFromCondition(Val, Cond,
777 /*IsTrueDest*/ true,
778 /*UseBlockValue*/ false));
779 }
780 }
781
782 if (BBLV.isOverdefined()) {
783 // Check whether we're checking at the terminator, and the pointer has
784 // been dereferenced in this block.
785 PointerType *PTy = dyn_cast<PointerType>(Val->getType());
786 if (PTy && BB->getTerminator() == BBI &&
787 isNonNullAtEndOfBlock(Val, BB))
789 }
790}
791
792std::optional<ValueLatticeElement>
793LazyValueInfoImpl::solveBlockValueSelect(SelectInst *SI, BasicBlock *BB) {
794 // Recurse on our inputs if needed
795 std::optional<ValueLatticeElement> OptTrueVal =
796 getBlockValue(SI->getTrueValue(), BB, SI);
797 if (!OptTrueVal)
798 return std::nullopt;
799 ValueLatticeElement &TrueVal = *OptTrueVal;
800
801 std::optional<ValueLatticeElement> OptFalseVal =
802 getBlockValue(SI->getFalseValue(), BB, SI);
803 if (!OptFalseVal)
804 return std::nullopt;
805 ValueLatticeElement &FalseVal = *OptFalseVal;
806
807 if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
808 const ConstantRange &TrueCR = TrueVal.asConstantRange(SI->getType());
809 const ConstantRange &FalseCR = FalseVal.asConstantRange(SI->getType());
810 Value *LHS = nullptr;
811 Value *RHS = nullptr;
812 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
813 // Is this a min specifically of our two inputs? (Avoid the risk of
814 // ValueTracking getting smarter looking back past our immediate inputs.)
816 ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
817 (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
818 ConstantRange ResultCR = [&]() {
819 switch (SPR.Flavor) {
820 default:
821 llvm_unreachable("unexpected minmax type!");
822 case SPF_SMIN: /// Signed minimum
823 return TrueCR.smin(FalseCR);
824 case SPF_UMIN: /// Unsigned minimum
825 return TrueCR.umin(FalseCR);
826 case SPF_SMAX: /// Signed maximum
827 return TrueCR.smax(FalseCR);
828 case SPF_UMAX: /// Unsigned maximum
829 return TrueCR.umax(FalseCR);
830 };
831 }();
833 ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
834 FalseVal.isConstantRangeIncludingUndef());
835 }
836
837 if (SPR.Flavor == SPF_ABS) {
838 if (LHS == SI->getTrueValue())
840 TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
841 if (LHS == SI->getFalseValue())
843 FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
844 }
845
846 if (SPR.Flavor == SPF_NABS) {
848 if (LHS == SI->getTrueValue())
850 Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
851 if (LHS == SI->getFalseValue())
853 Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
854 }
855 }
856
857 // Can we constrain the facts about the true and false values by using the
858 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
859 // TODO: We could potentially refine an overdefined true value above.
860 Value *Cond = SI->getCondition();
861 // If the value is undef, a different value may be chosen in
862 // the select condition.
864 TrueVal =
865 TrueVal.intersect(*getValueFromCondition(SI->getTrueValue(), Cond,
866 /*IsTrueDest*/ true,
867 /*UseBlockValue*/ false));
868 FalseVal =
869 FalseVal.intersect(*getValueFromCondition(SI->getFalseValue(), Cond,
870 /*IsTrueDest*/ false,
871 /*UseBlockValue*/ false));
872 }
873
875 Result.mergeIn(FalseVal);
876 return Result;
877}
878
879std::optional<ConstantRange>
880LazyValueInfoImpl::getRangeFor(Value *V, Instruction *CxtI, BasicBlock *BB) {
881 std::optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
882 if (!OptVal)
883 return std::nullopt;
884 return OptVal->asConstantRange(V->getType());
885}
886
887std::optional<ValueLatticeElement>
888LazyValueInfoImpl::solveBlockValueCast(CastInst *CI, BasicBlock *BB) {
889 // Filter out casts we don't know how to reason about before attempting to
890 // recurse on our operand. This can cut a long search short if we know we're
891 // not going to be able to get any useful information anways.
892 switch (CI->getOpcode()) {
893 case Instruction::Trunc:
894 case Instruction::SExt:
895 case Instruction::ZExt:
896 break;
897 default:
898 // Unhandled instructions are overdefined.
899 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
900 << "' - overdefined (unknown cast).\n");
902 }
903
904 // Figure out the range of the LHS. If that fails, we still apply the
905 // transfer rule on the full set since we may be able to locally infer
906 // interesting facts.
907 std::optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
908 if (!LHSRes)
909 // More work to do before applying this transfer rule.
910 return std::nullopt;
911 const ConstantRange &LHSRange = *LHSRes;
912
913 const unsigned ResultBitWidth = CI->getType()->getScalarSizeInBits();
914
915 // NOTE: We're currently limited by the set of operations that ConstantRange
916 // can evaluate symbolically. Enhancing that set will allows us to analyze
917 // more definitions.
918 return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
919 ResultBitWidth));
920}
921
922std::optional<ValueLatticeElement>
923LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
925 std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
926 OpFn) {
927 Value *LHS = I->getOperand(0);
928 Value *RHS = I->getOperand(1);
929
930 auto ThreadBinOpOverSelect =
931 [&](Value *X, const ConstantRange &CRX, SelectInst *Y,
932 bool XIsLHS) -> std::optional<ValueLatticeElement> {
933 Value *Cond = Y->getCondition();
934 // Only handle selects with constant values.
935 Constant *TrueC = dyn_cast<Constant>(Y->getTrueValue());
936 if (!TrueC)
937 return std::nullopt;
938 Constant *FalseC = dyn_cast<Constant>(Y->getFalseValue());
939 if (!FalseC)
940 return std::nullopt;
942 return std::nullopt;
943
944 ConstantRange TrueX =
945 CRX.intersectWith(getValueFromCondition(X, Cond, /*CondIsTrue=*/true,
946 /*UseBlockValue=*/false)
947 ->asConstantRange(X->getType()));
948 ConstantRange FalseX =
949 CRX.intersectWith(getValueFromCondition(X, Cond, /*CondIsTrue=*/false,
950 /*UseBlockValue=*/false)
951 ->asConstantRange(X->getType()));
952 ConstantRange TrueY = TrueC->toConstantRange();
953 ConstantRange FalseY = FalseC->toConstantRange();
954
955 if (XIsLHS)
957 OpFn(TrueX, TrueY).unionWith(OpFn(FalseX, FalseY)));
959 OpFn(TrueY, TrueX).unionWith(OpFn(FalseY, FalseX)));
960 };
961
962 // Figure out the ranges of the operands. If that fails, use a
963 // conservative range, but apply the transfer rule anyways. This
964 // lets us pick up facts from expressions like "and i32 (call i32
965 // @foo()), 32"
966 std::optional<ConstantRange> LHSRes = getRangeFor(LHS, I, BB);
967 if (!LHSRes)
968 return std::nullopt;
969
970 // Try to thread binop over rhs select
971 if (auto *SI = dyn_cast<SelectInst>(RHS)) {
972 if (auto Res = ThreadBinOpOverSelect(LHS, *LHSRes, SI, /*XIsLHS=*/true))
973 return *Res;
974 }
975
976 std::optional<ConstantRange> RHSRes = getRangeFor(RHS, I, BB);
977 if (!RHSRes)
978 return std::nullopt;
979
980 // Try to thread binop over lhs select
981 if (auto *SI = dyn_cast<SelectInst>(LHS)) {
982 if (auto Res = ThreadBinOpOverSelect(RHS, *RHSRes, SI, /*XIsLHS=*/false))
983 return *Res;
984 }
985
986 const ConstantRange &LHSRange = *LHSRes;
987 const ConstantRange &RHSRange = *RHSRes;
988 return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
989}
990
991std::optional<ValueLatticeElement>
992LazyValueInfoImpl::solveBlockValueBinaryOp(BinaryOperator *BO, BasicBlock *BB) {
993 assert(BO->getOperand(0)->getType()->isSized() &&
994 "all operands to binary operators are sized");
995 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
996 unsigned NoWrapKind = OBO->getNoWrapKind();
997 return solveBlockValueBinaryOpImpl(
998 BO, BB,
999 [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
1000 return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
1001 });
1002 }
1003
1004 return solveBlockValueBinaryOpImpl(
1005 BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
1006 return CR1.binaryOp(BO->getOpcode(), CR2);
1007 });
1008}
1009
1010std::optional<ValueLatticeElement>
1011LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
1012 BasicBlock *BB) {
1013 return solveBlockValueBinaryOpImpl(
1014 WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
1015 return CR1.binaryOp(WO->getBinaryOp(), CR2);
1016 });
1017}
1018
1019std::optional<ValueLatticeElement>
1020LazyValueInfoImpl::solveBlockValueIntrinsic(IntrinsicInst *II, BasicBlock *BB) {
1022 if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1023 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1024 << "' - unknown intrinsic.\n");
1025 return MetadataVal;
1026 }
1027
1029 for (Value *Op : II->args()) {
1030 std::optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1031 if (!Range)
1032 return std::nullopt;
1033 OpRanges.push_back(*Range);
1034 }
1035
1037 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges))
1038 .intersect(MetadataVal);
1039}
1040
1041std::optional<ValueLatticeElement>
1042LazyValueInfoImpl::solveBlockValueInsertElement(InsertElementInst *IEI,
1043 BasicBlock *BB) {
1044 std::optional<ValueLatticeElement> OptEltVal =
1045 getBlockValue(IEI->getOperand(1), BB, IEI);
1046 if (!OptEltVal)
1047 return std::nullopt;
1048 ValueLatticeElement &Res = *OptEltVal;
1049
1050 std::optional<ValueLatticeElement> OptVecVal =
1051 getBlockValue(IEI->getOperand(0), BB, IEI);
1052 if (!OptVecVal)
1053 return std::nullopt;
1054
1055 // Bail out if the inserted element is a constant expression. Unlike other
1056 // ValueLattice types, these are not considered an implicit splat when a
1057 // vector type is used.
1058 // We could call ConstantFoldInsertElementInstruction here to handle these.
1059 if (OptEltVal->isConstant())
1061
1062 Res.mergeIn(*OptVecVal);
1063 return Res;
1064}
1065
1066std::optional<ValueLatticeElement>
1067LazyValueInfoImpl::solveBlockValueExtractValue(ExtractValueInst *EVI,
1068 BasicBlock *BB) {
1069 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1070 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1071 return solveBlockValueOverflowIntrinsic(WO, BB);
1072
1073 // Handle extractvalue of insertvalue to allow further simplification
1074 // based on replaced with.overflow intrinsics.
1076 EVI->getAggregateOperand(), EVI->getIndices(),
1077 EVI->getDataLayout()))
1078 return getBlockValue(V, BB, EVI);
1079
1080 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1081 << "' - overdefined (unknown extractvalue).\n");
1083}
1084
1085static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val,
1086 ICmpInst::Predicate Pred) {
1087 if (LHS == Val)
1088 return true;
1089
1090 // Handle range checking idiom produced by InstCombine. We will subtract the
1091 // offset from the allowed range for RHS in this case.
1092 const APInt *C;
1093 if (match(LHS, m_AddLike(m_Specific(Val), m_APInt(C)))) {
1094 Offset = *C;
1095 return true;
1096 }
1097
1098 // Handle the symmetric case. This appears in saturation patterns like
1099 // (x == 16) ? 16 : (x + 1).
1100 if (match(Val, m_AddLike(m_Specific(LHS), m_APInt(C)))) {
1101 Offset = -*C;
1102 return true;
1103 }
1104
1105 // If (x | y) < C, then (x < C) && (y < C).
1106 if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1107 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
1108 return true;
1109
1110 // If (x & y) > C, then (x > C) && (y > C).
1111 if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1112 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
1113 return true;
1114
1115 return false;
1116}
1117
1118/// Get value range for a "(Val + Offset) Pred RHS" condition.
1119std::optional<ValueLatticeElement>
1120LazyValueInfoImpl::getValueFromSimpleICmpCondition(CmpInst::Predicate Pred,
1121 Value *RHS,
1122 const APInt &Offset,
1123 Instruction *CxtI,
1124 bool UseBlockValue) {
1126 /*isFullSet=*/true);
1127 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1128 RHSRange = ConstantRange(CI->getValue());
1129 } else if (UseBlockValue) {
1130 std::optional<ValueLatticeElement> R =
1131 getBlockValue(RHS, CxtI->getParent(), CxtI);
1132 if (!R)
1133 return std::nullopt;
1134 RHSRange = R->asConstantRange(RHS->getType());
1135 }
1136
1137 ConstantRange TrueValues =
1139 return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1140}
1141
1142static std::optional<ConstantRange>
1144 function_ref<std::optional<ConstantRange>(const APInt &)> Fn) {
1145 bool Invert = false;
1146 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
1147 Pred = ICmpInst::getInversePredicate(Pred);
1148 Invert = true;
1149 }
1150 if (Pred == ICmpInst::ICMP_SLE) {
1151 Pred = ICmpInst::ICMP_SLT;
1152 if (RHS.isMaxSignedValue())
1153 return std::nullopt; // Could also return full/empty here, if we wanted.
1154 ++RHS;
1155 }
1156 assert(Pred == ICmpInst::ICMP_SLT && "Must be signed predicate");
1157 if (auto CR = Fn(RHS))
1158 return Invert ? CR->inverse() : CR;
1159 return std::nullopt;
1160}
1161
1162std::optional<ValueLatticeElement> LazyValueInfoImpl::getValueFromICmpCondition(
1163 Value *Val, ICmpInst *ICI, bool isTrueDest, bool UseBlockValue) {
1164 Value *LHS = ICI->getOperand(0);
1165 Value *RHS = ICI->getOperand(1);
1166
1167 // Get the predicate that must hold along the considered edge.
1168 CmpInst::Predicate EdgePred =
1169 isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1170
1171 if (isa<Constant>(RHS)) {
1172 if (ICI->isEquality() && LHS == Val) {
1173 if (EdgePred == ICmpInst::ICMP_EQ)
1174 return ValueLatticeElement::get(cast<Constant>(RHS));
1175 else if (!isa<UndefValue>(RHS))
1176 return ValueLatticeElement::getNot(cast<Constant>(RHS));
1177 }
1178 }
1179
1180 Type *Ty = Val->getType();
1181 if (!Ty->isIntegerTy())
1183
1184 unsigned BitWidth = Ty->getScalarSizeInBits();
1185 APInt Offset(BitWidth, 0);
1186 if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1187 return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset, ICI,
1188 UseBlockValue);
1189
1190 CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1191 if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1192 return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset, ICI,
1193 UseBlockValue);
1194
1195 const APInt *Mask, *C;
1196 if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1197 match(RHS, m_APInt(C))) {
1198 // If (Val & Mask) == C then all the masked bits are known and we can
1199 // compute a value range based on that.
1200 if (EdgePred == ICmpInst::ICMP_EQ) {
1201 KnownBits Known;
1202 Known.Zero = ~*C & *Mask;
1203 Known.One = *C & *Mask;
1205 ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1206 }
1207
1208 if (EdgePred == ICmpInst::ICMP_NE)
1211 }
1212
1213 // If (X urem Modulus) >= C, then X >= C.
1214 // If trunc X >= C, then X >= C.
1215 // TODO: An upper bound could be computed as well.
1216 if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
1217 m_Trunc(m_Specific(Val)))) &&
1218 match(RHS, m_APInt(C))) {
1219 // Use the icmp region so we don't have to deal with different predicates.
1221 if (!CR.isEmptySet())
1224 }
1225
1226 // Recognize:
1227 // icmp slt (ashr X, ShAmtC), C --> icmp slt X, C << ShAmtC
1228 // Preconditions: (C << ShAmtC) >> ShAmtC == C
1229 const APInt *ShAmtC;
1230 if (CmpInst::isSigned(EdgePred) &&
1231 match(LHS, m_AShr(m_Specific(Val), m_APInt(ShAmtC))) &&
1232 match(RHS, m_APInt(C))) {
1233 auto CR = getRangeViaSLT(
1234 EdgePred, *C, [&](const APInt &RHS) -> std::optional<ConstantRange> {
1235 APInt New = RHS << *ShAmtC;
1236 if ((New.ashr(*ShAmtC)) != RHS)
1237 return std::nullopt;
1239 APInt::getSignedMinValue(New.getBitWidth()), New);
1240 });
1241 if (CR)
1243 }
1244
1245 // a - b or ptrtoint(a) - ptrtoint(b) ==/!= 0 if a ==/!= b
1246 Value *X, *Y;
1247 if (ICI->isEquality() && match(Val, m_Sub(m_Value(X), m_Value(Y)))) {
1248 // Peek through ptrtoints
1251 if ((X == LHS && Y == RHS) || (X == RHS && Y == LHS)) {
1252 Constant *NullVal = Constant::getNullValue(Val->getType());
1253 if (EdgePred == ICmpInst::ICMP_EQ)
1254 return ValueLatticeElement::get(NullVal);
1255 return ValueLatticeElement::getNot(NullVal);
1256 }
1257 }
1258
1260}
1261
1262// Handle conditions of the form
1263// extractvalue(op.with.overflow(%x, C), 1).
1265 Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1266 // TODO: This only works with a constant RHS for now. We could also compute
1267 // the range of the RHS, but this doesn't fit into the current structure of
1268 // the edge value calculation.
1269 const APInt *C;
1270 if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1272
1273 // Calculate the possible values of %x for which no overflow occurs.
1275 WO->getBinaryOp(), *C, WO->getNoWrapKind());
1276
1277 // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1278 // constrained to it's inverse (all values that might cause overflow).
1279 if (IsTrueDest)
1280 NWR = NWR.inverse();
1282}
1283
1284std::optional<ValueLatticeElement>
1285LazyValueInfoImpl::getValueFromCondition(Value *Val, Value *Cond,
1286 bool IsTrueDest, bool UseBlockValue,
1287 unsigned Depth) {
1288 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1289 return getValueFromICmpCondition(Val, ICI, IsTrueDest, UseBlockValue);
1290
1291 if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1292 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1293 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1294 return getValueFromOverflowCondition(Val, WO, IsTrueDest);
1295
1298
1299 Value *N;
1300 if (match(Cond, m_Not(m_Value(N))))
1301 return getValueFromCondition(Val, N, !IsTrueDest, UseBlockValue, Depth);
1302
1303 Value *L, *R;
1304 bool IsAnd;
1305 if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1306 IsAnd = true;
1307 else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1308 IsAnd = false;
1309 else
1311
1312 std::optional<ValueLatticeElement> LV =
1313 getValueFromCondition(Val, L, IsTrueDest, UseBlockValue, Depth);
1314 if (!LV)
1315 return std::nullopt;
1316 std::optional<ValueLatticeElement> RV =
1317 getValueFromCondition(Val, R, IsTrueDest, UseBlockValue, Depth);
1318 if (!RV)
1319 return std::nullopt;
1320
1321 // if (L && R) -> intersect L and R
1322 // if (!(L || R)) -> intersect !L and !R
1323 // if (L || R) -> union L and R
1324 // if (!(L && R)) -> union !L and !R
1325 if (IsTrueDest ^ IsAnd) {
1326 LV->mergeIn(*RV);
1327 return *LV;
1328 }
1329
1330 return LV->intersect(*RV);
1331}
1332
1333// Return true if Usr has Op as an operand, otherwise false.
1334static bool usesOperand(User *Usr, Value *Op) {
1335 return is_contained(Usr->operands(), Op);
1336}
1337
1338// Return true if the instruction type of Val is supported by
1339// constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1340// Call this before calling constantFoldUser() to find out if it's even worth
1341// attempting to call it.
1342static bool isOperationFoldable(User *Usr) {
1343 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1344}
1345
1346// Check if Usr can be simplified to an integer constant when the value of one
1347// of its operands Op is an integer constant OpConstVal. If so, return it as an
1348// lattice value range with a single element or otherwise return an overdefined
1349// lattice value.
1351 const APInt &OpConstVal,
1352 const DataLayout &DL) {
1353 assert(isOperationFoldable(Usr) && "Precondition");
1354 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1355 // Check if Usr can be simplified to a constant.
1356 if (auto *CI = dyn_cast<CastInst>(Usr)) {
1357 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1358 if (auto *C = dyn_cast_or_null<ConstantInt>(
1359 simplifyCastInst(CI->getOpcode(), OpConst,
1360 CI->getDestTy(), DL))) {
1361 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1362 }
1363 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1364 bool Op0Match = BO->getOperand(0) == Op;
1365 bool Op1Match = BO->getOperand(1) == Op;
1366 assert((Op0Match || Op1Match) &&
1367 "Operand 0 nor Operand 1 isn't a match");
1368 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1369 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1370 if (auto *C = dyn_cast_or_null<ConstantInt>(
1371 simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1372 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1373 }
1374 } else if (isa<FreezeInst>(Usr)) {
1375 assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1376 return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1377 }
1379}
1380
1381/// Compute the value of Val on the edge BBFrom -> BBTo.
1382std::optional<ValueLatticeElement>
1383LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1384 BasicBlock *BBTo, bool UseBlockValue) {
1385 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1386 // know that v != 0.
1387 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1388 // If this is a conditional branch and only one successor goes to BBTo, then
1389 // we may be able to infer something from the condition.
1390 if (BI->isConditional() &&
1391 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1392 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1393 assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1394 "BBTo isn't a successor of BBFrom");
1395 Value *Condition = BI->getCondition();
1396
1397 // If V is the condition of the branch itself, then we know exactly what
1398 // it is.
1399 // NB: The condition on a `br` can't be a vector type.
1400 if (Condition == Val)
1401 return ValueLatticeElement::get(ConstantInt::get(
1402 Type::getInt1Ty(Val->getContext()), isTrueDest));
1403
1404 // If the condition of the branch is an equality comparison, we may be
1405 // able to infer the value.
1406 std::optional<ValueLatticeElement> Result =
1407 getValueFromCondition(Val, Condition, isTrueDest, UseBlockValue);
1408 if (!Result)
1409 return std::nullopt;
1410
1411 if (!Result->isOverdefined())
1412 return Result;
1413
1414 if (User *Usr = dyn_cast<User>(Val)) {
1415 assert(Result->isOverdefined() && "Result isn't overdefined");
1416 // Check with isOperationFoldable() first to avoid linearly iterating
1417 // over the operands unnecessarily which can be expensive for
1418 // instructions with many operands.
1419 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1420 const DataLayout &DL = BBTo->getDataLayout();
1421 if (usesOperand(Usr, Condition)) {
1422 // If Val has Condition as an operand and Val can be folded into a
1423 // constant with either Condition == true or Condition == false,
1424 // propagate the constant.
1425 // eg.
1426 // ; %Val is true on the edge to %then.
1427 // %Val = and i1 %Condition, true.
1428 // br %Condition, label %then, label %else
1429 APInt ConditionVal(1, isTrueDest ? 1 : 0);
1430 Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1431 } else {
1432 // If one of Val's operand has an inferred value, we may be able to
1433 // infer the value of Val.
1434 // eg.
1435 // ; %Val is 94 on the edge to %then.
1436 // %Val = add i8 %Op, 1
1437 // %Condition = icmp eq i8 %Op, 93
1438 // br i1 %Condition, label %then, label %else
1439 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1440 Value *Op = Usr->getOperand(i);
1441 ValueLatticeElement OpLatticeVal = *getValueFromCondition(
1442 Op, Condition, isTrueDest, /*UseBlockValue*/ false);
1443 if (std::optional<APInt> OpConst =
1444 OpLatticeVal.asConstantInteger()) {
1445 Result = constantFoldUser(Usr, Op, *OpConst, DL);
1446 break;
1447 }
1448 }
1449 }
1450 }
1451 }
1452 if (!Result->isOverdefined())
1453 return Result;
1454 }
1455 }
1456
1457 // If the edge was formed by a switch on the value, then we may know exactly
1458 // what it is.
1459 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1460 Value *Condition = SI->getCondition();
1461 if (!isa<IntegerType>(Val->getType()))
1463 bool ValUsesConditionAndMayBeFoldable = false;
1464 if (Condition != Val) {
1465 // Check if Val has Condition as an operand.
1466 if (User *Usr = dyn_cast<User>(Val))
1467 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1468 usesOperand(Usr, Condition);
1469 if (!ValUsesConditionAndMayBeFoldable)
1471 }
1472 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1473 "Condition != Val nor Val doesn't use Condition");
1474
1475 bool DefaultCase = SI->getDefaultDest() == BBTo;
1476 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1477 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1478
1479 for (auto Case : SI->cases()) {
1480 APInt CaseValue = Case.getCaseValue()->getValue();
1481 ConstantRange EdgeVal(CaseValue);
1482 if (ValUsesConditionAndMayBeFoldable) {
1483 User *Usr = cast<User>(Val);
1484 const DataLayout &DL = BBTo->getDataLayout();
1485 ValueLatticeElement EdgeLatticeVal =
1486 constantFoldUser(Usr, Condition, CaseValue, DL);
1487 if (EdgeLatticeVal.isOverdefined())
1489 EdgeVal = EdgeLatticeVal.getConstantRange();
1490 }
1491 if (DefaultCase) {
1492 // It is possible that the default destination is the destination of
1493 // some cases. We cannot perform difference for those cases.
1494 // We know Condition != CaseValue in BBTo. In some cases we can use
1495 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1496 // only do this when f is identity (i.e. Val == Condition), but we
1497 // should be able to do this for any injective f.
1498 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1499 EdgesVals = EdgesVals.difference(EdgeVal);
1500 } else if (Case.getCaseSuccessor() == BBTo)
1501 EdgesVals = EdgesVals.unionWith(EdgeVal);
1502 }
1503 return ValueLatticeElement::getRange(std::move(EdgesVals));
1504 }
1506}
1507
1508/// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1509/// the basic block if the edge does not constrain Val.
1510std::optional<ValueLatticeElement>
1511LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1512 BasicBlock *BBTo, Instruction *CxtI) {
1513 // If already a constant, there is nothing to compute.
1514 if (Constant *VC = dyn_cast<Constant>(Val))
1515 return ValueLatticeElement::get(VC);
1516
1517 std::optional<ValueLatticeElement> LocalResult =
1518 getEdgeValueLocal(Val, BBFrom, BBTo, /*UseBlockValue*/ true);
1519 if (!LocalResult)
1520 return std::nullopt;
1521
1522 if (hasSingleValue(*LocalResult))
1523 // Can't get any more precise here
1524 return LocalResult;
1525
1526 std::optional<ValueLatticeElement> OptInBlock =
1527 getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1528 if (!OptInBlock)
1529 return std::nullopt;
1530 ValueLatticeElement &InBlock = *OptInBlock;
1531
1532 // We can use the context instruction (generically the ultimate instruction
1533 // the calling pass is trying to simplify) here, even though the result of
1534 // this function is generally cached when called from the solve* functions
1535 // (and that cached result might be used with queries using a different
1536 // context instruction), because when this function is called from the solve*
1537 // functions, the context instruction is not provided. When called from
1538 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1539 // but then the result is not cached.
1540 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1541
1542 return LocalResult->intersect(InBlock);
1543}
1544
1546 Instruction *CxtI) {
1547 LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1548 << BB->getName() << "'\n");
1549
1550 assert(BlockValueStack.empty() && BlockValueSet.empty());
1551 std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
1552 if (!OptResult) {
1553 solve();
1554 OptResult = getBlockValue(V, BB, CxtI);
1555 assert(OptResult && "Value not available after solving");
1556 }
1557
1558 ValueLatticeElement Result = *OptResult;
1559 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
1560 return Result;
1561}
1562
1564 LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
1565 << "'\n");
1566
1567 if (auto *C = dyn_cast<Constant>(V))
1569
1571 if (auto *I = dyn_cast<Instruction>(V))
1572 Result = getFromRangeMetadata(I);
1573 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1574
1575 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n");
1576 return Result;
1577}
1578
1580getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1581 Instruction *CxtI) {
1582 LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1583 << FromBB->getName() << "' to '" << ToBB->getName()
1584 << "'\n");
1585
1586 std::optional<ValueLatticeElement> Result =
1587 getEdgeValue(V, FromBB, ToBB, CxtI);
1588 while (!Result) {
1589 // As the worklist only explicitly tracks block values (but not edge values)
1590 // we may have to call solve() multiple times, as the edge value calculation
1591 // may request additional block values.
1592 solve();
1593 Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1594 }
1595
1596 LLVM_DEBUG(dbgs() << " Result = " << *Result << "\n");
1597 return *Result;
1598}
1599
1601 Value *V = U.get();
1602 auto *CxtI = cast<Instruction>(U.getUser());
1603 ValueLatticeElement VL = getValueInBlock(V, CxtI->getParent(), CxtI);
1604
1605 // Check whether the only (possibly transitive) use of the value is in a
1606 // position where V can be constrained by a select or branch condition.
1607 const Use *CurrU = &U;
1608 // TODO: Increase limit?
1609 const unsigned MaxUsesToInspect = 3;
1610 for (unsigned I = 0; I < MaxUsesToInspect; ++I) {
1611 std::optional<ValueLatticeElement> CondVal;
1612 auto *CurrI = cast<Instruction>(CurrU->getUser());
1613 if (auto *SI = dyn_cast<SelectInst>(CurrI)) {
1614 // If the value is undef, a different value may be chosen in
1615 // the select condition and at use.
1616 if (!isGuaranteedNotToBeUndef(SI->getCondition(), AC))
1617 break;
1618 if (CurrU->getOperandNo() == 1)
1619 CondVal =
1620 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ true,
1621 /*UseBlockValue*/ false);
1622 else if (CurrU->getOperandNo() == 2)
1623 CondVal =
1624 *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ false,
1625 /*UseBlockValue*/ false);
1626 } else if (auto *PHI = dyn_cast<PHINode>(CurrI)) {
1627 // TODO: Use non-local query?
1628 CondVal = *getEdgeValueLocal(V, PHI->getIncomingBlock(*CurrU),
1629 PHI->getParent(), /*UseBlockValue*/ false);
1630 }
1631 if (CondVal)
1632 VL = VL.intersect(*CondVal);
1633
1634 // Only follow one-use chain, to allow direct intersection of conditions.
1635 // If there are multiple uses, we would have to intersect with the union of
1636 // all conditions at different uses.
1637 // Stop walking if we hit a non-speculatable instruction. Even if the
1638 // result is only used under a specific condition, executing the
1639 // instruction itself may cause side effects or UB already.
1640 // This also disallows looking through phi nodes: If the phi node is part
1641 // of a cycle, we might end up reasoning about values from different cycle
1642 // iterations (PR60629).
1643 if (!CurrI->hasOneUse() ||
1645 break;
1646 CurrU = &*CurrI->use_begin();
1647 }
1648 return VL;
1649}
1650
1652 BasicBlock *NewSucc) {
1653 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1654}
1655
1656//===----------------------------------------------------------------------===//
1657// LazyValueInfo Impl
1658//===----------------------------------------------------------------------===//
1659
1661 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1662
1663 if (auto *Impl = Info.getImpl())
1664 Impl->clear();
1665
1666 // Fully lazy.
1667 return false;
1668}
1669
1671 AU.setPreservesAll();
1674}
1675
1677
1678/// This lazily constructs the LazyValueInfoImpl.
1679LazyValueInfoImpl &LazyValueInfo::getOrCreateImpl(const Module *M) {
1680 if (!PImpl) {
1681 assert(M && "getCache() called with a null Module");
1682 const DataLayout &DL = M->getDataLayout();
1683 Function *GuardDecl =
1684 Intrinsic::getDeclarationIfExists(M, Intrinsic::experimental_guard);
1685 PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
1686 }
1687 return *static_cast<LazyValueInfoImpl *>(PImpl);
1688}
1689
1690LazyValueInfoImpl *LazyValueInfo::getImpl() {
1691 if (!PImpl)
1692 return nullptr;
1693 return static_cast<LazyValueInfoImpl *>(PImpl);
1694}
1695
1697
1699 // If the cache was allocated, free it.
1700 if (auto *Impl = getImpl()) {
1701 delete &*Impl;
1702 PImpl = nullptr;
1703 }
1704}
1705
1708 // We need to invalidate if we have either failed to preserve this analyses
1709 // result directly or if any of its dependencies have been invalidated.
1710 auto PAC = PA.getChecker<LazyValueAnalysis>();
1711 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
1712 return true;
1713
1714 return false;
1715}
1716
1718
1721 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1722
1723 return LazyValueInfo(&AC, &F.getDataLayout());
1724}
1725
1726/// Returns true if we can statically tell that this value will never be a
1727/// "useful" constant. In practice, this means we've got something like an
1728/// alloca or a malloc call for which a comparison against a constant can
1729/// only be guarding dead code. Note that we are potentially giving up some
1730/// precision in dead code (a constant result) in favour of avoiding a
1731/// expensive search for a easily answered common query.
1732static bool isKnownNonConstant(Value *V) {
1733 V = V->stripPointerCasts();
1734 // The return val of alloc cannot be a Constant.
1735 if (isa<AllocaInst>(V))
1736 return true;
1737 return false;
1738}
1739
1741 // Bail out early if V is known not to be a Constant.
1742 if (isKnownNonConstant(V))
1743 return nullptr;
1744
1745 BasicBlock *BB = CxtI->getParent();
1746 ValueLatticeElement Result =
1747 getOrCreateImpl(BB->getModule()).getValueInBlock(V, BB, CxtI);
1748
1749 if (Result.isConstant())
1750 return Result.getConstant();
1751 if (Result.isConstantRange()) {
1752 const ConstantRange &CR = Result.getConstantRange();
1753 if (const APInt *SingleVal = CR.getSingleElement())
1754 return ConstantInt::get(V->getType(), *SingleVal);
1755 }
1756 return nullptr;
1757}
1758
1760 bool UndefAllowed) {
1761 BasicBlock *BB = CxtI->getParent();
1762 ValueLatticeElement Result =
1763 getOrCreateImpl(BB->getModule()).getValueInBlock(V, BB, CxtI);
1764 return Result.asConstantRange(V->getType(), UndefAllowed);
1765}
1766
1768 bool UndefAllowed) {
1769 auto *Inst = cast<Instruction>(U.getUser());
1770 ValueLatticeElement Result =
1771 getOrCreateImpl(Inst->getModule()).getValueAtUse(U);
1772 return Result.asConstantRange(U->getType(), UndefAllowed);
1773}
1774
1775/// Determine whether the specified value is known to be a
1776/// constant on the specified edge. Return null if not.
1778 BasicBlock *ToBB,
1779 Instruction *CxtI) {
1780 Module *M = FromBB->getModule();
1781 ValueLatticeElement Result =
1782 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1783
1784 if (Result.isConstant())
1785 return Result.getConstant();
1786 if (Result.isConstantRange()) {
1787 const ConstantRange &CR = Result.getConstantRange();
1788 if (const APInt *SingleVal = CR.getSingleElement())
1789 return ConstantInt::get(V->getType(), *SingleVal);
1790 }
1791 return nullptr;
1792}
1793
1795 BasicBlock *FromBB,
1796 BasicBlock *ToBB,
1797 Instruction *CxtI) {
1798 Module *M = FromBB->getModule();
1799 ValueLatticeElement Result =
1800 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1801 // TODO: Should undef be allowed here?
1802 return Result.asConstantRange(V->getType(), /*UndefAllowed*/ true);
1803}
1804
1806 const ValueLatticeElement &Val,
1807 const DataLayout &DL) {
1808 // If we know the value is a constant, evaluate the conditional.
1809 if (Val.isConstant())
1810 return ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL);
1811
1812 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
1813 if (Val.isConstantRange()) {
1814 const ConstantRange &CR = Val.getConstantRange();
1815 ConstantRange RHS = C->toConstantRange();
1816 if (CR.icmp(Pred, RHS))
1817 return ConstantInt::getTrue(ResTy);
1818 if (CR.icmp(CmpInst::getInversePredicate(Pred), RHS))
1819 return ConstantInt::getFalse(ResTy);
1820 return nullptr;
1821 }
1822
1823 if (Val.isNotConstant()) {
1824 // If this is an equality comparison, we can try to fold it knowing that
1825 // "V != C1".
1826 if (Pred == ICmpInst::ICMP_EQ) {
1827 // !C1 == C -> false iff C1 == C.
1830 if (Res && Res->isNullValue())
1831 return ConstantInt::getFalse(ResTy);
1832 } else if (Pred == ICmpInst::ICMP_NE) {
1833 // !C1 != C -> true iff C1 == C.
1836 if (Res && Res->isNullValue())
1837 return ConstantInt::getTrue(ResTy);
1838 }
1839 return nullptr;
1840 }
1841
1842 return nullptr;
1843}
1844
1845/// Determine whether the specified value comparison with a constant is known to
1846/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1848 Constant *C, BasicBlock *FromBB,
1849 BasicBlock *ToBB,
1850 Instruction *CxtI) {
1851 Module *M = FromBB->getModule();
1852 ValueLatticeElement Result =
1853 getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1854
1855 return getPredicateResult(Pred, C, Result, M->getDataLayout());
1856}
1857
1859 Constant *C, Instruction *CxtI,
1860 bool UseBlockValue) {
1861 // Is or is not NonNull are common predicates being queried. If
1862 // isKnownNonZero can tell us the result of the predicate, we can
1863 // return it quickly. But this is only a fastpath, and falling
1864 // through would still be correct.
1865 Module *M = CxtI->getModule();
1866 const DataLayout &DL = M->getDataLayout();
1867 if (V->getType()->isPointerTy() && C->isNullValue() &&
1868 isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1869 Type *ResTy = CmpInst::makeCmpResultType(C->getType());
1870 if (Pred == ICmpInst::ICMP_EQ)
1871 return ConstantInt::getFalse(ResTy);
1872 else if (Pred == ICmpInst::ICMP_NE)
1873 return ConstantInt::getTrue(ResTy);
1874 }
1875
1876 auto &Impl = getOrCreateImpl(M);
1877 ValueLatticeElement Result =
1878 UseBlockValue ? Impl.getValueInBlock(V, CxtI->getParent(), CxtI)
1879 : Impl.getValueAt(V, CxtI);
1880 Constant *Ret = getPredicateResult(Pred, C, Result, DL);
1881 if (Ret)
1882 return Ret;
1883
1884 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1885 // LVI as a whole tries to compute a lattice value which is conservatively
1886 // correct at a given location. In this case, we have a predicate which we
1887 // weren't able to prove about the merged result, and we're pushing that
1888 // predicate back along each incoming edge to see if we can prove it
1889 // separately for each input. As a motivating example, consider:
1890 // bb1:
1891 // %v1 = ... ; constantrange<1, 5>
1892 // br label %merge
1893 // bb2:
1894 // %v2 = ... ; constantrange<10, 20>
1895 // br label %merge
1896 // merge:
1897 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1898 // %pred = icmp eq i32 %phi, 8
1899 // We can't tell from the lattice value for '%phi' that '%pred' is false
1900 // along each path, but by checking the predicate over each input separately,
1901 // we can.
1902 // We limit the search to one step backwards from the current BB and value.
1903 // We could consider extending this to search further backwards through the
1904 // CFG and/or value graph, but there are non-obvious compile time vs quality
1905 // tradeoffs.
1906 BasicBlock *BB = CxtI->getParent();
1907
1908 // Function entry or an unreachable block. Bail to avoid confusing
1909 // analysis below.
1910 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1911 if (PI == PE)
1912 return nullptr;
1913
1914 // If V is a PHI node in the same block as the context, we need to ask
1915 // questions about the predicate as applied to the incoming value along
1916 // each edge. This is useful for eliminating cases where the predicate is
1917 // known along all incoming edges.
1918 if (auto *PHI = dyn_cast<PHINode>(V))
1919 if (PHI->getParent() == BB) {
1920 Constant *Baseline = nullptr;
1921 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1922 Value *Incoming = PHI->getIncomingValue(i);
1923 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1924 // Note that PredBB may be BB itself.
1925 Constant *Result =
1926 getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
1927
1928 // Keep going as long as we've seen a consistent known result for
1929 // all inputs.
1930 Baseline = (i == 0) ? Result /* First iteration */
1931 : (Baseline == Result ? Baseline
1932 : nullptr); /* All others */
1933 if (!Baseline)
1934 break;
1935 }
1936 if (Baseline)
1937 return Baseline;
1938 }
1939
1940 // For a comparison where the V is outside this block, it's possible
1941 // that we've branched on it before. Look to see if the value is known
1942 // on all incoming edges.
1943 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
1944 // For predecessor edge, determine if the comparison is true or false
1945 // on that edge. If they're all true or all false, we can conclude
1946 // the value of the comparison in this block.
1947 Constant *Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1948 if (Baseline) {
1949 // Check that all remaining incoming values match the first one.
1950 while (++PI != PE) {
1951 Constant *Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1952 if (Ret != Baseline)
1953 break;
1954 }
1955 // If we terminated early, then one of the values didn't match.
1956 if (PI == PE) {
1957 return Baseline;
1958 }
1959 }
1960 }
1961
1962 return nullptr;
1963}
1964
1966 Value *RHS, Instruction *CxtI,
1967 bool UseBlockValue) {
1968 if (auto *C = dyn_cast<Constant>(RHS))
1969 return getPredicateAt(Pred, LHS, C, CxtI, UseBlockValue);
1970 if (auto *C = dyn_cast<Constant>(LHS))
1971 return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
1972 UseBlockValue);
1973
1974 // Got two non-Constant values. Try to determine the comparison results based
1975 // on the block values of the two operands, e.g. because they have
1976 // non-overlapping ranges.
1977 if (UseBlockValue) {
1978 Module *M = CxtI->getModule();
1980 getOrCreateImpl(M).getValueInBlock(LHS, CxtI->getParent(), CxtI);
1981 if (L.isOverdefined())
1982 return nullptr;
1983
1985 getOrCreateImpl(M).getValueInBlock(RHS, CxtI->getParent(), CxtI);
1987 return L.getCompare(Pred, Ty, R, M->getDataLayout());
1988 }
1989 return nullptr;
1990}
1991
1993 BasicBlock *NewSucc) {
1994 if (auto *Impl = getImpl())
1995 Impl->threadEdge(PredBB, OldSucc, NewSucc);
1996}
1997
1999 if (auto *Impl = getImpl())
2000 Impl->forgetValue(V);
2001}
2002
2004 if (auto *Impl = getImpl())
2005 Impl->eraseBlock(BB);
2006}
2007
2009 if (auto *Impl = getImpl())
2010 Impl->clear();
2011}
2012
2014 if (auto *Impl = getImpl())
2015 Impl->printLVI(F, DTree, OS);
2016}
2017
2018// Print the LVI for the function arguments at the start of each basic block.
2019void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
2020 const BasicBlock *BB, formatted_raw_ostream &OS) {
2021 // Find if there are latticevalues defined for arguments of the function.
2022 auto *F = BB->getParent();
2023 for (const auto &Arg : F->args()) {
2024 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2025 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2026 if (Result.isUnknown())
2027 continue;
2028 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
2029 }
2030}
2031
2032// This function prints the LVI analysis for the instruction I at the beginning
2033// of various basic blocks. It relies on calculated values that are stored in
2034// the LazyValueInfoCache, and in the absence of cached values, recalculate the
2035// LazyValueInfo for `I`, and print that info.
2036void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2038
2039 auto *ParentBB = I->getParent();
2040 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2041 // We can generate (solve) LVI values only for blocks that are dominated by
2042 // the I's parent. However, to avoid generating LVI for all dominating blocks,
2043 // that contain redundant/uninteresting information, we print LVI for
2044 // blocks that may use this LVI information (such as immediate successor
2045 // blocks, and blocks that contain uses of `I`).
2046 auto printResult = [&](const BasicBlock *BB) {
2047 if (!BlocksContainingLVI.insert(BB).second)
2048 return;
2049 ValueLatticeElement Result = LVIImpl->getValueInBlock(
2050 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2051 OS << "; LatticeVal for: '" << *I << "' in BB: '";
2052 BB->printAsOperand(OS, false);
2053 OS << "' is: " << Result << "\n";
2054 };
2055
2056 printResult(ParentBB);
2057 // Print the LVI analysis results for the immediate successor blocks, that
2058 // are dominated by `ParentBB`.
2059 for (const auto *BBSucc : successors(ParentBB))
2060 if (DT.dominates(ParentBB, BBSucc))
2061 printResult(BBSucc);
2062
2063 // Print LVI in blocks where `I` is used.
2064 for (const auto *U : I->users())
2065 if (auto *UseI = dyn_cast<Instruction>(U))
2066 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2067 printResult(UseI->getParent());
2068
2069}
2070
2073 OS << "LVI for function '" << F.getName() << "':\n";
2074 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
2075 auto &DTree = AM.getResult<DominatorTreeAnalysis>(F);
2076 LVI.printLVI(F, DTree, OS);
2077 return PreservedAnalyses::all();
2078}
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
basic Basic Alias true
block Block Frequency Analysis
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Given that RA is a live value
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file defines the DenseSet and SmallDenseSet classes.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
IRTranslator LLVM IR MI
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 std::optional< ConstantRange > getRange(Value *V, const InstrInfoQuery &IIQ)
Helper method to get range from metadata or attribute.
static bool isOperationFoldable(User *Usr)
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 bool usesOperand(User *Usr, Value *Op)
static ValueLatticeElement constantFoldUser(User *Usr, Value *Op, const APInt &OpConstVal, const DataLayout &DL)
static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet)
static ValueLatticeElement getFromRangeMetadata(Instruction *BBI)
static Constant * getPredicateResult(CmpInst::Predicate Pred, Constant *C, const ValueLatticeElement &Val, const DataLayout &DL)
static ValueLatticeElement getValueFromOverflowCondition(Value *Val, WithOverflowInst *WO, bool IsTrueDest)
lazy value info
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)
Natural Loop Information
Definition: LoopInfo.cpp:1209
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
#define P(N)
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:55
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:57
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:52
const SmallVectorImpl< MachineOperand > & Cond
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
static bool InBlock(const Value *V, const BasicBlock *BB)
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:986
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:219
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:200
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
Definition: Analysis.h:49
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:292
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
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.
Definition: Argument.h:31
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.
void clear()
Clear the cache of @llvm.assume intrinsics for a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:448
bool isEntryBlock() const
Return true if this is the entry block of the containing function.
Definition: BasicBlock.cpp:571
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:219
const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Definition: BasicBlock.cpp:296
reverse_iterator rend()
Definition: BasicBlock.h:466
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...
Definition: BasicBlock.h:239
const Instruction & back() const
Definition: BasicBlock.h:473
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:292
Value * getRHS() const
unsigned getNoWrapKind() const
Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
Value * getLHS() const
BinaryOps getOpcode() const
Definition: InstrTypes.h:370
Conditional or Unconditional Branch instruction.
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:383
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:444
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition: InstrTypes.h:608
Type * getDestTy() const
Return the destination type, as a convenience.
Definition: InstrTypes.h:615
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:988
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:673
@ ICMP_SLT
signed less than
Definition: InstrTypes.h:702
@ ICMP_SLE
signed less or equal
Definition: InstrTypes.h:703
@ ICMP_UGE
unsigned greater or equal
Definition: InstrTypes.h:697
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:696
@ ICMP_SGT
signed greater than
Definition: InstrTypes.h:700
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:698
@ ICMP_EQ
equal
Definition: InstrTypes.h:694
@ ICMP_NE
not equal
Definition: InstrTypes.h:695
@ ICMP_SGE
signed greater or equal
Definition: InstrTypes.h:701
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:699
bool isSigned() const
Definition: InstrTypes.h:928
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:825
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:787
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:763
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:866
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:873
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Definition: Constants.cpp:1826
This class represents a range of values.
Definition: ConstantRange.h:47
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 ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
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...
ConstantRange umin(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned minimum of a value in ...
APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
ConstantRange difference(const ConstantRange &CR) const
Subtract the specified range from this range (aka relative complement of the sets).
bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other? NOTE: false does not mean that inverse pr...
static ConstantRange intrinsic(Intrinsic::ID IntrinsicID, ArrayRef< ConstantRange > Ops)
Compute range of intrinsic result for the given operand ranges.
bool isEmptySet() const
Return true if this set contains no members.
ConstantRange abs(bool IntMinIsPoison=false) const
Calculate absolute value range.
static bool isIntrinsicSupported(Intrinsic::ID IntrinsicID)
Returns true if ConstantRange calculations are supported for intrinsic with IntrinsicID.
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.
ConstantRange umax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned maximum of a value in ...
static 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...
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static 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...
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static 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.
Definition: ConstantRange.h:84
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.
ConstantRange smax(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a signed maximum of a value in thi...
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 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.
Definition: Constant.h:42
static Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
Definition: Constants.cpp:403
ConstantRange toConstantRange() const
Convert constant to an approximate constant range.
Definition: Constants.cpp:1785
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:373
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:90
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive,...
Definition: DenseMap.h:176
iterator end()
Definition: DenseMap.h:84
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:211
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
Definition: Dominators.cpp:122
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
idx_iterator idx_begin() const
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:310
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.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:66
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:386
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:274
const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
Definition: Instruction.cpp:74
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:48
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...
This pass computes, caches, and vends lazy value constraint information.
Definition: LazyValueInfo.h:32
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.
Definition: Instructions.h:176
Metadata node.
Definition: Metadata.h:1069
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.
Definition: Module.h:65
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.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: Analysis.h:264
This class represents the LLVM 'select' instruction.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition: DenseSet.h:298
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:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
An instruction for storing to memory.
Definition: Instructions.h:292
Multiway switch.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getIntegerBitWidth() const
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:243
static IntegerType * getInt1Ty(LLVMContext &C)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:310
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:237
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:288
Value * getOperand(unsigned i) const
Definition: User.h:228
This class represents lattice values for constants.
Definition: ValueLattice.h:26
static ValueLatticeElement getRange(ConstantRange CR, bool MayIncludeUndef=false)
Definition: ValueLattice.h:211
static ValueLatticeElement getNot(Constant *C)
Definition: ValueLattice.h:205
std::optional< APInt > asConstantInteger() const
Definition: ValueLattice.h:272
const ConstantRange & getConstantRange(bool UndefAllowed=true) const
Returns the constant range for this value.
Definition: ValueLattice.h:266
bool isConstantRange(bool UndefAllowed=true) const
Returns true if this value is a constant range.
Definition: ValueLattice.h:246
static ValueLatticeElement get(Constant *C)
Definition: ValueLattice.h:200
Constant * getNotConstant() const
Definition: ValueLattice.h:257
ValueLatticeElement intersect(const ValueLatticeElement &Other) const
Combine two sets of facts about the same value into a single set of facts.
Constant * getConstant() const
Definition: ValueLattice.h:252
bool mergeIn(const ValueLatticeElement &RHS, MergeOptions Opts=MergeOptions())
Updates this object to approximate both this object and RHS.
Definition: ValueLattice.h:399
static ValueLatticeElement getOverdefined()
Definition: ValueLattice.h:228
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition: Value.cpp:786
use_iterator use_begin()
Definition: Value.h:360
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.
Definition: AsmWriter.cpp:5144
bool use_empty() const
Definition: Value.h:344
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
iterator find_as(const LookupKeyT &Val)
Alternative version of find() which allows a different, and possibly less expensive,...
Definition: DenseSet.h:202
bool erase(const ValueT &V)
Definition: DenseSet.h:97
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition: ilist_node.h:32
self_iterator getIterator()
Definition: ilist_node.h:132
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
#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.
Definition: BitmaskEnum.h:125
@ Entry
Definition: COFF.h:844
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
Function * getDeclarationIfExists(Module *M, ID id, ArrayRef< Type * > Tys, FunctionType *FT=nullptr)
This version supports overloaded intrinsics.
Definition: Intrinsics.cpp:746
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)
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)
Definition: PatternMatch.h:49
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:885
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".
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
Definition: PatternMatch.h:299
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
BinaryOp_match< cst_pred_ty< is_all_ones >, ValTy, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
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.
Definition: PatternMatch.h:239
constexpr double e
Definition: MathExtras.h:47
@ FalseVal
Definition: TGLexer.h:59
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
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,...
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I)
Don't use information from its non-constant operands.
auto pred_end(const MachineBasicBlock *BB)
auto successors(const MachineBasicBlock *BB)
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.
Definition: STLExtras.h:2115
const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=6)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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.
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.
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
Value * simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
FunctionPass * createLazyValueInfoPass()
createLazyValueInfoPass - This creates an instance of the LazyValueInfo pass.
constexpr unsigned MaxAnalysisRecursionDepth
Definition: ValueTracking.h:44
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
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...
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition: Function.cpp:1187
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
Value * simplifyExtractValueInst(Value *Agg, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an ExtractValueInst, fold the result or return null.
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.
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
static bool hasSingleValue(const ValueLatticeElement &Val)
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:217
auto pred_begin(const MachineBasicBlock *BB)
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
void initializeLazyValueInfoWrapperPassPass(PassRegistry &)
#define N
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:28
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?