xref: /llvm-project/llvm/lib/Analysis/LazyValueInfo.cpp (revision af656a8d4245069f70f5b5e1f654ec9291d3b0a3)
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 
14 #include "llvm/Analysis/LazyValueInfo.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Analysis/AssumptionCache.h"
18 #include "llvm/Analysis/ConstantFolding.h"
19 #include "llvm/Analysis/InstructionSimplify.h"
20 #include "llvm/Analysis/Passes.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/ValueLattice.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/IR/AssemblyAnnotationWriter.h"
25 #include "llvm/IR/CFG.h"
26 #include "llvm/IR/ConstantRange.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"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/IR/ValueHandle.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/KnownBits.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <optional>
44 using namespace llvm;
45 using 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.
51 static const unsigned MaxProcessedPerValue = 500;
52 
53 char LazyValueInfoWrapperPass::ID = 0;
54 LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
55   initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
56 }
57 INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
58                 "Lazy Value Information Analysis", false, true)
59 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
60 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
61 INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
62                 "Lazy Value Information Analysis", false, true)
63 
64 namespace llvm {
65 FunctionPass *createLazyValueInfoPass() {
66   return new LazyValueInfoWrapperPass();
67 }
68 } // namespace llvm
69 
70 AnalysisKey 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.
75 static bool hasSingleValue(const ValueLatticeElement &Val) {
76   if (Val.isConstantRange() &&
77       Val.getConstantRange().isSingleElement())
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 
90 namespace {
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 
106 namespace {
107 using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
108 
109 /// This is the cache kept by LazyValueInfo which
110 /// maintains information about queries across the clients' queries.
111 class 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 {
117     SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
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.
128   DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
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 
151 public:
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))
173       return ValueLatticeElement::getOverdefined();
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 
215 void 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 
228 void 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 
234 void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
235   BlockCache.erase(BB);
236 }
237 
238 void 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 
292 namespace llvm {
293 namespace {
294 /// An assembly annotator class to print LazyValueCache information in
295 /// comments.
296 class 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 
302 public:
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.
314 class LazyValueInfoImpl {
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.
322   SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
323 
324   /// Keeps track of which block-value pairs are in BlockValueStack.
325   DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
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(
367       Instruction *I, BasicBlock *BB,
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,
384                                                      ValueLatticeElement &BBLV,
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 
411 public:
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.
415   ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
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.
422   ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
423 
424   /// This is the query interface to determine the lattice
425   /// value for the specified Value* that is true on the specified edge.
426   ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
427                                      BasicBlock *ToBB,
428                                      Instruction *CxtI = nullptr);
429 
430   ValueLatticeElement getValueAtUse(const Use &U);
431 
432   /// Complete flush all previously computed values
433   void clear() {
434     TheCache.clear();
435   }
436 
437   /// Printing the LazyValueInfo Analysis.
438   void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
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.
449   void eraseBlock(BasicBlock *BB) {
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 
457   LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
458                     Function *GuardDecl)
459       : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
460 };
461 } // namespace llvm
462 
463 void LazyValueInfoImpl::solve() {
464   SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack =
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) {
479       LLVM_DEBUG(
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,
485                               ValueLatticeElement::getOverdefined());
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!");
505       LLVM_DEBUG(
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 
520 std::optional<ValueLatticeElement>
521 LazyValueInfoImpl::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 }))
535     return ValueLatticeElement::getOverdefined();
536 
537   // Yet to be resolved.
538   return std::nullopt;
539 }
540 
541 static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
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())
548       return ValueLatticeElement::getRange(*Range);
549     [[fallthrough]];
550   case Instruction::Load:
551     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
552       if (isa<IntegerType>(BBI->getType())) {
553         return ValueLatticeElement::getRange(
554             getConstantRangeFromMetadata(*Ranges));
555       }
556     break;
557   };
558   // Nothing known - will be intersected with other facts
559   return ValueLatticeElement::getOverdefined();
560 }
561 
562 bool 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 
578 std::optional<ValueLatticeElement>
579 LazyValueInfoImpl::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))
601     return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
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 
625 static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
626   // TODO: Use NullPointerIsDefined instead.
627   if (Ptr->getType()->getPointerAddressSpace() == 0)
628     PtrSet.insert(getUnderlyingObject(Ptr));
629 }
630 
631 static void AddNonNullPointersByInstruction(
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 
650 bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
651   if (NullPointerIsDefined(BB->getParent(),
652                            Val->getType()->getPointerAddressSpace()))
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 
664 std::optional<ValueLatticeElement>
665 LazyValueInfoImpl::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())
672       return ValueLatticeElement::getRange(*Range);
673     return ValueLatticeElement::getOverdefined();
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 
708 std::optional<ValueLatticeElement>
709 LazyValueInfoImpl::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
746 void 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))
788       BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
789   }
790 }
791 
792 std::optional<ValueLatticeElement>
793 LazyValueInfoImpl::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.)
815     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
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       }();
832       return ValueLatticeElement::getRange(
833           ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
834                         FalseVal.isConstantRangeIncludingUndef());
835     }
836 
837     if (SPR.Flavor == SPF_ABS) {
838       if (LHS == SI->getTrueValue())
839         return ValueLatticeElement::getRange(
840             TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
841       if (LHS == SI->getFalseValue())
842         return ValueLatticeElement::getRange(
843             FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
844     }
845 
846     if (SPR.Flavor == SPF_NABS) {
847       ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
848       if (LHS == SI->getTrueValue())
849         return ValueLatticeElement::getRange(
850             Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
851       if (LHS == SI->getFalseValue())
852         return ValueLatticeElement::getRange(
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.
863   if (isGuaranteedNotToBeUndef(Cond, AC)) {
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 
874   ValueLatticeElement Result = TrueVal;
875   Result.mergeIn(FalseVal);
876   return Result;
877 }
878 
879 std::optional<ConstantRange>
880 LazyValueInfoImpl::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 
887 std::optional<ValueLatticeElement>
888 LazyValueInfoImpl::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");
901     return ValueLatticeElement::getOverdefined();
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 
922 std::optional<ValueLatticeElement>
923 LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
924     Instruction *I, BasicBlock *BB,
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;
941     if (!isGuaranteedNotToBeUndef(Cond, AC))
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)
956       return ValueLatticeElement::getRange(
957           OpFn(TrueX, TrueY).unionWith(OpFn(FalseX, FalseY)));
958     return ValueLatticeElement::getRange(
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 
991 std::optional<ValueLatticeElement>
992 LazyValueInfoImpl::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 
1010 std::optional<ValueLatticeElement>
1011 LazyValueInfoImpl::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 
1019 std::optional<ValueLatticeElement>
1020 LazyValueInfoImpl::solveBlockValueIntrinsic(IntrinsicInst *II, BasicBlock *BB) {
1021   ValueLatticeElement MetadataVal = getFromRangeMetadata(II);
1022   if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1023     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1024                       << "' - unknown intrinsic.\n");
1025     return MetadataVal;
1026   }
1027 
1028   SmallVector<ConstantRange, 2> OpRanges;
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 
1036   return ValueLatticeElement::getRange(
1037              ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges))
1038       .intersect(MetadataVal);
1039 }
1040 
1041 std::optional<ValueLatticeElement>
1042 LazyValueInfoImpl::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())
1060     return ValueLatticeElement::getOverdefined();
1061 
1062   Res.mergeIn(*OptVecVal);
1063   return Res;
1064 }
1065 
1066 std::optional<ValueLatticeElement>
1067 LazyValueInfoImpl::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.
1075   if (Value *V = simplifyExtractValueInst(
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");
1082   return ValueLatticeElement::getOverdefined();
1083 }
1084 
1085 static 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.
1119 std::optional<ValueLatticeElement>
1120 LazyValueInfoImpl::getValueFromSimpleICmpCondition(CmpInst::Predicate Pred,
1121                                                    Value *RHS,
1122                                                    const APInt &Offset,
1123                                                    Instruction *CxtI,
1124                                                    bool UseBlockValue) {
1125   ConstantRange RHSRange(RHS->getType()->getScalarSizeInBits(),
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 =
1138       ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1139   return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1140 }
1141 
1142 static std::optional<ConstantRange>
1143 getRangeViaSLT(CmpInst::Predicate Pred, APInt RHS,
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 
1162 /// Get value range for a "ctpop(Val) Pred RHS" condition.
1163 static ValueLatticeElement getValueFromICmpCtpop(ICmpInst::Predicate Pred,
1164                                                  Value *RHS) {
1165   unsigned BitWidth = RHS->getType()->getScalarSizeInBits();
1166 
1167   auto *RHSConst = dyn_cast<ConstantInt>(RHS);
1168   if (!RHSConst)
1169     return ValueLatticeElement::getOverdefined();
1170 
1171   ConstantRange ResValRange =
1172       ConstantRange::makeExactICmpRegion(Pred, RHSConst->getValue());
1173 
1174   unsigned ResMin = ResValRange.getUnsignedMin().getLimitedValue(BitWidth);
1175   unsigned ResMax = ResValRange.getUnsignedMax().getLimitedValue(BitWidth);
1176 
1177   APInt ValMin = APInt::getLowBitsSet(BitWidth, ResMin);
1178   APInt ValMax = APInt::getHighBitsSet(BitWidth, ResMax);
1179   return ValueLatticeElement::getRange(
1180       ConstantRange::getNonEmpty(std::move(ValMin), ValMax + 1));
1181 }
1182 
1183 std::optional<ValueLatticeElement> LazyValueInfoImpl::getValueFromICmpCondition(
1184     Value *Val, ICmpInst *ICI, bool isTrueDest, bool UseBlockValue) {
1185   Value *LHS = ICI->getOperand(0);
1186   Value *RHS = ICI->getOperand(1);
1187 
1188   // Get the predicate that must hold along the considered edge.
1189   CmpInst::Predicate EdgePred =
1190       isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1191 
1192   if (isa<Constant>(RHS)) {
1193     if (ICI->isEquality() && LHS == Val) {
1194       if (EdgePred == ICmpInst::ICMP_EQ)
1195         return ValueLatticeElement::get(cast<Constant>(RHS));
1196       else if (!isa<UndefValue>(RHS))
1197         return ValueLatticeElement::getNot(cast<Constant>(RHS));
1198     }
1199   }
1200 
1201   Type *Ty = Val->getType();
1202   if (!Ty->isIntegerTy())
1203     return ValueLatticeElement::getOverdefined();
1204 
1205   unsigned BitWidth = Ty->getScalarSizeInBits();
1206   APInt Offset(BitWidth, 0);
1207   if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1208     return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset, ICI,
1209                                            UseBlockValue);
1210 
1211   CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1212   if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1213     return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset, ICI,
1214                                            UseBlockValue);
1215 
1216   if (match(LHS, m_Intrinsic<Intrinsic::ctpop>(m_Specific(Val))))
1217     return getValueFromICmpCtpop(EdgePred, RHS);
1218 
1219   const APInt *Mask, *C;
1220   if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1221       match(RHS, m_APInt(C))) {
1222     // If (Val & Mask) == C then all the masked bits are known and we can
1223     // compute a value range based on that.
1224     if (EdgePred == ICmpInst::ICMP_EQ) {
1225       KnownBits Known;
1226       Known.Zero = ~*C & *Mask;
1227       Known.One = *C & *Mask;
1228       return ValueLatticeElement::getRange(
1229           ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1230     }
1231 
1232     if (EdgePred == ICmpInst::ICMP_NE)
1233       return ValueLatticeElement::getRange(
1234           ConstantRange::makeMaskNotEqualRange(*Mask, *C));
1235   }
1236 
1237   // If (X urem Modulus) >= C, then X >= C.
1238   // If trunc X >= C, then X >= C.
1239   // TODO: An upper bound could be computed as well.
1240   if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
1241                              m_Trunc(m_Specific(Val)))) &&
1242       match(RHS, m_APInt(C))) {
1243     // Use the icmp region so we don't have to deal with different predicates.
1244     ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
1245     if (!CR.isEmptySet())
1246       return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
1247           CR.getUnsignedMin().zext(BitWidth), APInt(BitWidth, 0)));
1248   }
1249 
1250   // Recognize:
1251   // icmp slt (ashr X, ShAmtC), C --> icmp slt X, C << ShAmtC
1252   // Preconditions: (C << ShAmtC) >> ShAmtC == C
1253   const APInt *ShAmtC;
1254   if (CmpInst::isSigned(EdgePred) &&
1255       match(LHS, m_AShr(m_Specific(Val), m_APInt(ShAmtC))) &&
1256       match(RHS, m_APInt(C))) {
1257     auto CR = getRangeViaSLT(
1258         EdgePred, *C, [&](const APInt &RHS) -> std::optional<ConstantRange> {
1259           APInt New = RHS << *ShAmtC;
1260           if ((New.ashr(*ShAmtC)) != RHS)
1261             return std::nullopt;
1262           return ConstantRange::getNonEmpty(
1263               APInt::getSignedMinValue(New.getBitWidth()), New);
1264         });
1265     if (CR)
1266       return ValueLatticeElement::getRange(*CR);
1267   }
1268 
1269   // a - b or ptrtoint(a) - ptrtoint(b) ==/!= 0 if a ==/!= b
1270   Value *X, *Y;
1271   if (ICI->isEquality() && match(Val, m_Sub(m_Value(X), m_Value(Y)))) {
1272     // Peek through ptrtoints
1273     match(X, m_PtrToIntSameSize(DL, m_Value(X)));
1274     match(Y, m_PtrToIntSameSize(DL, m_Value(Y)));
1275     if ((X == LHS && Y == RHS) || (X == RHS && Y == LHS)) {
1276       Constant *NullVal = Constant::getNullValue(Val->getType());
1277       if (EdgePred == ICmpInst::ICMP_EQ)
1278         return ValueLatticeElement::get(NullVal);
1279       return ValueLatticeElement::getNot(NullVal);
1280     }
1281   }
1282 
1283   return ValueLatticeElement::getOverdefined();
1284 }
1285 
1286 // Handle conditions of the form
1287 // extractvalue(op.with.overflow(%x, C), 1).
1288 static ValueLatticeElement getValueFromOverflowCondition(
1289     Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1290   // TODO: This only works with a constant RHS for now. We could also compute
1291   // the range of the RHS, but this doesn't fit into the current structure of
1292   // the edge value calculation.
1293   const APInt *C;
1294   if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1295     return ValueLatticeElement::getOverdefined();
1296 
1297   // Calculate the possible values of %x for which no overflow occurs.
1298   ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
1299       WO->getBinaryOp(), *C, WO->getNoWrapKind());
1300 
1301   // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1302   // constrained to it's inverse (all values that might cause overflow).
1303   if (IsTrueDest)
1304     NWR = NWR.inverse();
1305   return ValueLatticeElement::getRange(NWR);
1306 }
1307 
1308 std::optional<ValueLatticeElement>
1309 LazyValueInfoImpl::getValueFromCondition(Value *Val, Value *Cond,
1310                                          bool IsTrueDest, bool UseBlockValue,
1311                                          unsigned Depth) {
1312   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1313     return getValueFromICmpCondition(Val, ICI, IsTrueDest, UseBlockValue);
1314 
1315   if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1316     if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1317       if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1318         return getValueFromOverflowCondition(Val, WO, IsTrueDest);
1319 
1320   if (++Depth == MaxAnalysisRecursionDepth)
1321     return ValueLatticeElement::getOverdefined();
1322 
1323   Value *N;
1324   if (match(Cond, m_Not(m_Value(N))))
1325     return getValueFromCondition(Val, N, !IsTrueDest, UseBlockValue, Depth);
1326 
1327   Value *L, *R;
1328   bool IsAnd;
1329   if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1330     IsAnd = true;
1331   else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1332     IsAnd = false;
1333   else
1334     return ValueLatticeElement::getOverdefined();
1335 
1336   std::optional<ValueLatticeElement> LV =
1337       getValueFromCondition(Val, L, IsTrueDest, UseBlockValue, Depth);
1338   if (!LV)
1339     return std::nullopt;
1340   std::optional<ValueLatticeElement> RV =
1341       getValueFromCondition(Val, R, IsTrueDest, UseBlockValue, Depth);
1342   if (!RV)
1343     return std::nullopt;
1344 
1345   // if (L && R) -> intersect L and R
1346   // if (!(L || R)) -> intersect !L and !R
1347   // if (L || R) -> union L and R
1348   // if (!(L && R)) -> union !L and !R
1349   if (IsTrueDest ^ IsAnd) {
1350     LV->mergeIn(*RV);
1351     return *LV;
1352   }
1353 
1354   return LV->intersect(*RV);
1355 }
1356 
1357 // Return true if Usr has Op as an operand, otherwise false.
1358 static bool usesOperand(User *Usr, Value *Op) {
1359   return is_contained(Usr->operands(), Op);
1360 }
1361 
1362 // Return true if the instruction type of Val is supported by
1363 // constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1364 // Call this before calling constantFoldUser() to find out if it's even worth
1365 // attempting to call it.
1366 static bool isOperationFoldable(User *Usr) {
1367   return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1368 }
1369 
1370 // Check if Usr can be simplified to an integer constant when the value of one
1371 // of its operands Op is an integer constant OpConstVal. If so, return it as an
1372 // lattice value range with a single element or otherwise return an overdefined
1373 // lattice value.
1374 static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
1375                                             const APInt &OpConstVal,
1376                                             const DataLayout &DL) {
1377   assert(isOperationFoldable(Usr) && "Precondition");
1378   Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1379   // Check if Usr can be simplified to a constant.
1380   if (auto *CI = dyn_cast<CastInst>(Usr)) {
1381     assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
1382     if (auto *C = dyn_cast_or_null<ConstantInt>(
1383             simplifyCastInst(CI->getOpcode(), OpConst,
1384                              CI->getDestTy(), DL))) {
1385       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1386     }
1387   } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1388     bool Op0Match = BO->getOperand(0) == Op;
1389     bool Op1Match = BO->getOperand(1) == Op;
1390     assert((Op0Match || Op1Match) &&
1391            "Operand 0 nor Operand 1 isn't a match");
1392     Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1393     Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1394     if (auto *C = dyn_cast_or_null<ConstantInt>(
1395             simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1396       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1397     }
1398   } else if (isa<FreezeInst>(Usr)) {
1399     assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1400     return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1401   }
1402   return ValueLatticeElement::getOverdefined();
1403 }
1404 
1405 /// Compute the value of Val on the edge BBFrom -> BBTo.
1406 std::optional<ValueLatticeElement>
1407 LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1408                                      BasicBlock *BBTo, bool UseBlockValue) {
1409   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1410   // know that v != 0.
1411   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1412     // If this is a conditional branch and only one successor goes to BBTo, then
1413     // we may be able to infer something from the condition.
1414     if (BI->isConditional() &&
1415         BI->getSuccessor(0) != BI->getSuccessor(1)) {
1416       bool isTrueDest = BI->getSuccessor(0) == BBTo;
1417       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
1418              "BBTo isn't a successor of BBFrom");
1419       Value *Condition = BI->getCondition();
1420 
1421       // If V is the condition of the branch itself, then we know exactly what
1422       // it is.
1423       // NB: The condition on a `br` can't be a vector type.
1424       if (Condition == Val)
1425         return ValueLatticeElement::get(ConstantInt::get(
1426                               Type::getInt1Ty(Val->getContext()), isTrueDest));
1427 
1428       // If the condition of the branch is an equality comparison, we may be
1429       // able to infer the value.
1430       std::optional<ValueLatticeElement> Result =
1431           getValueFromCondition(Val, Condition, isTrueDest, UseBlockValue);
1432       if (!Result)
1433         return std::nullopt;
1434 
1435       if (!Result->isOverdefined())
1436         return Result;
1437 
1438       if (User *Usr = dyn_cast<User>(Val)) {
1439         assert(Result->isOverdefined() && "Result isn't overdefined");
1440         // Check with isOperationFoldable() first to avoid linearly iterating
1441         // over the operands unnecessarily which can be expensive for
1442         // instructions with many operands.
1443         if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1444           const DataLayout &DL = BBTo->getDataLayout();
1445           if (usesOperand(Usr, Condition)) {
1446             // If Val has Condition as an operand and Val can be folded into a
1447             // constant with either Condition == true or Condition == false,
1448             // propagate the constant.
1449             // eg.
1450             //   ; %Val is true on the edge to %then.
1451             //   %Val = and i1 %Condition, true.
1452             //   br %Condition, label %then, label %else
1453             APInt ConditionVal(1, isTrueDest ? 1 : 0);
1454             Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1455           } else {
1456             // If one of Val's operand has an inferred value, we may be able to
1457             // infer the value of Val.
1458             // eg.
1459             //    ; %Val is 94 on the edge to %then.
1460             //    %Val = add i8 %Op, 1
1461             //    %Condition = icmp eq i8 %Op, 93
1462             //    br i1 %Condition, label %then, label %else
1463             for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1464               Value *Op = Usr->getOperand(i);
1465               ValueLatticeElement OpLatticeVal = *getValueFromCondition(
1466                   Op, Condition, isTrueDest, /*UseBlockValue*/ false);
1467               if (std::optional<APInt> OpConst =
1468                       OpLatticeVal.asConstantInteger()) {
1469                 Result = constantFoldUser(Usr, Op, *OpConst, DL);
1470                 break;
1471               }
1472             }
1473           }
1474         }
1475       }
1476       if (!Result->isOverdefined())
1477         return Result;
1478     }
1479   }
1480 
1481   // If the edge was formed by a switch on the value, then we may know exactly
1482   // what it is.
1483   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1484     Value *Condition = SI->getCondition();
1485     if (!isa<IntegerType>(Val->getType()))
1486       return ValueLatticeElement::getOverdefined();
1487     bool ValUsesConditionAndMayBeFoldable = false;
1488     if (Condition != Val) {
1489       // Check if Val has Condition as an operand.
1490       if (User *Usr = dyn_cast<User>(Val))
1491         ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1492             usesOperand(Usr, Condition);
1493       if (!ValUsesConditionAndMayBeFoldable)
1494         return ValueLatticeElement::getOverdefined();
1495     }
1496     assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
1497            "Condition != Val nor Val doesn't use Condition");
1498 
1499     bool DefaultCase = SI->getDefaultDest() == BBTo;
1500     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1501     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1502 
1503     for (auto Case : SI->cases()) {
1504       APInt CaseValue = Case.getCaseValue()->getValue();
1505       ConstantRange EdgeVal(CaseValue);
1506       if (ValUsesConditionAndMayBeFoldable) {
1507         User *Usr = cast<User>(Val);
1508         const DataLayout &DL = BBTo->getDataLayout();
1509         ValueLatticeElement EdgeLatticeVal =
1510             constantFoldUser(Usr, Condition, CaseValue, DL);
1511         if (EdgeLatticeVal.isOverdefined())
1512           return ValueLatticeElement::getOverdefined();
1513         EdgeVal = EdgeLatticeVal.getConstantRange();
1514       }
1515       if (DefaultCase) {
1516         // It is possible that the default destination is the destination of
1517         // some cases. We cannot perform difference for those cases.
1518         // We know Condition != CaseValue in BBTo.  In some cases we can use
1519         // this to infer Val == f(Condition) is != f(CaseValue).  For now, we
1520         // only do this when f is identity (i.e. Val == Condition), but we
1521         // should be able to do this for any injective f.
1522         if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1523           EdgesVals = EdgesVals.difference(EdgeVal);
1524       } else if (Case.getCaseSuccessor() == BBTo)
1525         EdgesVals = EdgesVals.unionWith(EdgeVal);
1526     }
1527     return ValueLatticeElement::getRange(std::move(EdgesVals));
1528   }
1529   return ValueLatticeElement::getOverdefined();
1530 }
1531 
1532 /// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1533 /// the basic block if the edge does not constrain Val.
1534 std::optional<ValueLatticeElement>
1535 LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1536                                 BasicBlock *BBTo, Instruction *CxtI) {
1537   // If already a constant, there is nothing to compute.
1538   if (Constant *VC = dyn_cast<Constant>(Val))
1539     return ValueLatticeElement::get(VC);
1540 
1541   std::optional<ValueLatticeElement> LocalResult =
1542       getEdgeValueLocal(Val, BBFrom, BBTo, /*UseBlockValue*/ true);
1543   if (!LocalResult)
1544     return std::nullopt;
1545 
1546   if (hasSingleValue(*LocalResult))
1547     // Can't get any more precise here
1548     return LocalResult;
1549 
1550   std::optional<ValueLatticeElement> OptInBlock =
1551       getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1552   if (!OptInBlock)
1553     return std::nullopt;
1554   ValueLatticeElement &InBlock = *OptInBlock;
1555 
1556   // We can use the context instruction (generically the ultimate instruction
1557   // the calling pass is trying to simplify) here, even though the result of
1558   // this function is generally cached when called from the solve* functions
1559   // (and that cached result might be used with queries using a different
1560   // context instruction), because when this function is called from the solve*
1561   // functions, the context instruction is not provided. When called from
1562   // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1563   // but then the result is not cached.
1564   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1565 
1566   return LocalResult->intersect(InBlock);
1567 }
1568 
1569 ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
1570                                                        Instruction *CxtI) {
1571   LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
1572                     << BB->getName() << "'\n");
1573 
1574   assert(BlockValueStack.empty() && BlockValueSet.empty());
1575   std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
1576   if (!OptResult) {
1577     solve();
1578     OptResult = getBlockValue(V, BB, CxtI);
1579     assert(OptResult && "Value not available after solving");
1580   }
1581 
1582   ValueLatticeElement Result = *OptResult;
1583   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1584   return Result;
1585 }
1586 
1587 ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
1588   LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
1589                     << "'\n");
1590 
1591   if (auto *C = dyn_cast<Constant>(V))
1592     return ValueLatticeElement::get(C);
1593 
1594   ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
1595   if (auto *I = dyn_cast<Instruction>(V))
1596     Result = getFromRangeMetadata(I);
1597   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1598 
1599   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
1600   return Result;
1601 }
1602 
1603 ValueLatticeElement LazyValueInfoImpl::
1604 getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1605                Instruction *CxtI) {
1606   LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
1607                     << FromBB->getName() << "' to '" << ToBB->getName()
1608                     << "'\n");
1609 
1610   std::optional<ValueLatticeElement> Result =
1611       getEdgeValue(V, FromBB, ToBB, CxtI);
1612   while (!Result) {
1613     // As the worklist only explicitly tracks block values (but not edge values)
1614     // we may have to call solve() multiple times, as the edge value calculation
1615     // may request additional block values.
1616     solve();
1617     Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1618   }
1619 
1620   LLVM_DEBUG(dbgs() << "  Result = " << *Result << "\n");
1621   return *Result;
1622 }
1623 
1624 ValueLatticeElement LazyValueInfoImpl::getValueAtUse(const Use &U) {
1625   Value *V = U.get();
1626   auto *CxtI = cast<Instruction>(U.getUser());
1627   ValueLatticeElement VL = getValueInBlock(V, CxtI->getParent(), CxtI);
1628 
1629   // Check whether the only (possibly transitive) use of the value is in a
1630   // position where V can be constrained by a select or branch condition.
1631   const Use *CurrU = &U;
1632   // TODO: Increase limit?
1633   const unsigned MaxUsesToInspect = 3;
1634   for (unsigned I = 0; I < MaxUsesToInspect; ++I) {
1635     std::optional<ValueLatticeElement> CondVal;
1636     auto *CurrI = cast<Instruction>(CurrU->getUser());
1637     if (auto *SI = dyn_cast<SelectInst>(CurrI)) {
1638       // If the value is undef, a different value may be chosen in
1639       // the select condition and at use.
1640       if (!isGuaranteedNotToBeUndef(SI->getCondition(), AC))
1641         break;
1642       if (CurrU->getOperandNo() == 1)
1643         CondVal =
1644             *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ true,
1645                                    /*UseBlockValue*/ false);
1646       else if (CurrU->getOperandNo() == 2)
1647         CondVal =
1648             *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ false,
1649                                    /*UseBlockValue*/ false);
1650     } else if (auto *PHI = dyn_cast<PHINode>(CurrI)) {
1651       // TODO: Use non-local query?
1652       CondVal = *getEdgeValueLocal(V, PHI->getIncomingBlock(*CurrU),
1653                                    PHI->getParent(), /*UseBlockValue*/ false);
1654     }
1655     if (CondVal)
1656       VL = VL.intersect(*CondVal);
1657 
1658     // Only follow one-use chain, to allow direct intersection of conditions.
1659     // If there are multiple uses, we would have to intersect with the union of
1660     // all conditions at different uses.
1661     // Stop walking if we hit a non-speculatable instruction. Even if the
1662     // result is only used under a specific condition, executing the
1663     // instruction itself may cause side effects or UB already.
1664     // This also disallows looking through phi nodes: If the phi node is part
1665     // of a cycle, we might end up reasoning about values from different cycle
1666     // iterations (PR60629).
1667     if (!CurrI->hasOneUse() ||
1668         !isSafeToSpeculativelyExecuteWithVariableReplaced(CurrI))
1669       break;
1670     CurrU = &*CurrI->use_begin();
1671   }
1672   return VL;
1673 }
1674 
1675 void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1676                                    BasicBlock *NewSucc) {
1677   TheCache.threadEdgeImpl(OldSucc, NewSucc);
1678 }
1679 
1680 //===----------------------------------------------------------------------===//
1681 //                            LazyValueInfo Impl
1682 //===----------------------------------------------------------------------===//
1683 
1684 bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1685   Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1686 
1687   if (auto *Impl = Info.getImpl())
1688     Impl->clear();
1689 
1690   // Fully lazy.
1691   return false;
1692 }
1693 
1694 void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1695   AU.setPreservesAll();
1696   AU.addRequired<AssumptionCacheTracker>();
1697   AU.addRequired<TargetLibraryInfoWrapperPass>();
1698 }
1699 
1700 LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1701 
1702 /// This lazily constructs the LazyValueInfoImpl.
1703 LazyValueInfoImpl &LazyValueInfo::getOrCreateImpl(const Module *M) {
1704   if (!PImpl) {
1705     assert(M && "getCache() called with a null Module");
1706     const DataLayout &DL = M->getDataLayout();
1707     Function *GuardDecl =
1708         Intrinsic::getDeclarationIfExists(M, Intrinsic::experimental_guard);
1709     PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
1710   }
1711   return *static_cast<LazyValueInfoImpl *>(PImpl);
1712 }
1713 
1714 LazyValueInfoImpl *LazyValueInfo::getImpl() {
1715   if (!PImpl)
1716     return nullptr;
1717   return static_cast<LazyValueInfoImpl *>(PImpl);
1718 }
1719 
1720 LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1721 
1722 void LazyValueInfo::releaseMemory() {
1723   // If the cache was allocated, free it.
1724   if (auto *Impl = getImpl()) {
1725     delete &*Impl;
1726     PImpl = nullptr;
1727   }
1728 }
1729 
1730 bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1731                                FunctionAnalysisManager::Invalidator &Inv) {
1732   // We need to invalidate if we have either failed to preserve this analyses
1733   // result directly or if any of its dependencies have been invalidated.
1734   auto PAC = PA.getChecker<LazyValueAnalysis>();
1735   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
1736     return true;
1737 
1738   return false;
1739 }
1740 
1741 void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1742 
1743 LazyValueInfo LazyValueAnalysis::run(Function &F,
1744                                      FunctionAnalysisManager &FAM) {
1745   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1746 
1747   return LazyValueInfo(&AC, &F.getDataLayout());
1748 }
1749 
1750 /// Returns true if we can statically tell that this value will never be a
1751 /// "useful" constant.  In practice, this means we've got something like an
1752 /// alloca or a malloc call for which a comparison against a constant can
1753 /// only be guarding dead code.  Note that we are potentially giving up some
1754 /// precision in dead code (a constant result) in favour of avoiding a
1755 /// expensive search for a easily answered common query.
1756 static bool isKnownNonConstant(Value *V) {
1757   V = V->stripPointerCasts();
1758   // The return val of alloc cannot be a Constant.
1759   if (isa<AllocaInst>(V))
1760     return true;
1761   return false;
1762 }
1763 
1764 Constant *LazyValueInfo::getConstant(Value *V, Instruction *CxtI) {
1765   // Bail out early if V is known not to be a Constant.
1766   if (isKnownNonConstant(V))
1767     return nullptr;
1768 
1769   BasicBlock *BB = CxtI->getParent();
1770   ValueLatticeElement Result =
1771       getOrCreateImpl(BB->getModule()).getValueInBlock(V, BB, CxtI);
1772 
1773   if (Result.isConstant())
1774     return Result.getConstant();
1775   if (Result.isConstantRange()) {
1776     const ConstantRange &CR = Result.getConstantRange();
1777     if (const APInt *SingleVal = CR.getSingleElement())
1778       return ConstantInt::get(V->getType(), *SingleVal);
1779   }
1780   return nullptr;
1781 }
1782 
1783 ConstantRange LazyValueInfo::getConstantRange(Value *V, Instruction *CxtI,
1784                                               bool UndefAllowed) {
1785   BasicBlock *BB = CxtI->getParent();
1786   ValueLatticeElement Result =
1787       getOrCreateImpl(BB->getModule()).getValueInBlock(V, BB, CxtI);
1788   return Result.asConstantRange(V->getType(), UndefAllowed);
1789 }
1790 
1791 ConstantRange LazyValueInfo::getConstantRangeAtUse(const Use &U,
1792                                                    bool UndefAllowed) {
1793   auto *Inst = cast<Instruction>(U.getUser());
1794   ValueLatticeElement Result =
1795       getOrCreateImpl(Inst->getModule()).getValueAtUse(U);
1796   return Result.asConstantRange(U->getType(), UndefAllowed);
1797 }
1798 
1799 /// Determine whether the specified value is known to be a
1800 /// constant on the specified edge. Return null if not.
1801 Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1802                                            BasicBlock *ToBB,
1803                                            Instruction *CxtI) {
1804   Module *M = FromBB->getModule();
1805   ValueLatticeElement Result =
1806       getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1807 
1808   if (Result.isConstant())
1809     return Result.getConstant();
1810   if (Result.isConstantRange()) {
1811     const ConstantRange &CR = Result.getConstantRange();
1812     if (const APInt *SingleVal = CR.getSingleElement())
1813       return ConstantInt::get(V->getType(), *SingleVal);
1814   }
1815   return nullptr;
1816 }
1817 
1818 ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
1819                                                     BasicBlock *FromBB,
1820                                                     BasicBlock *ToBB,
1821                                                     Instruction *CxtI) {
1822   Module *M = FromBB->getModule();
1823   ValueLatticeElement Result =
1824       getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1825   // TODO: Should undef be allowed here?
1826   return Result.asConstantRange(V->getType(), /*UndefAllowed*/ true);
1827 }
1828 
1829 static Constant *getPredicateResult(CmpInst::Predicate Pred, Constant *C,
1830                                     const ValueLatticeElement &Val,
1831                                     const DataLayout &DL) {
1832   // If we know the value is a constant, evaluate the conditional.
1833   if (Val.isConstant())
1834     return ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL);
1835 
1836   Type *ResTy = CmpInst::makeCmpResultType(C->getType());
1837   if (Val.isConstantRange()) {
1838     const ConstantRange &CR = Val.getConstantRange();
1839     ConstantRange RHS = C->toConstantRange();
1840     if (CR.icmp(Pred, RHS))
1841       return ConstantInt::getTrue(ResTy);
1842     if (CR.icmp(CmpInst::getInversePredicate(Pred), RHS))
1843       return ConstantInt::getFalse(ResTy);
1844     return nullptr;
1845   }
1846 
1847   if (Val.isNotConstant()) {
1848     // If this is an equality comparison, we can try to fold it knowing that
1849     // "V != C1".
1850     if (Pred == ICmpInst::ICMP_EQ) {
1851       // !C1 == C -> false iff C1 == C.
1852       Constant *Res = ConstantFoldCompareInstOperands(
1853           ICmpInst::ICMP_NE, Val.getNotConstant(), C, DL);
1854       if (Res && Res->isNullValue())
1855         return ConstantInt::getFalse(ResTy);
1856     } else if (Pred == ICmpInst::ICMP_NE) {
1857       // !C1 != C -> true iff C1 == C.
1858       Constant *Res = ConstantFoldCompareInstOperands(
1859           ICmpInst::ICMP_NE, Val.getNotConstant(), C, DL);
1860       if (Res && Res->isNullValue())
1861         return ConstantInt::getTrue(ResTy);
1862     }
1863     return nullptr;
1864   }
1865 
1866   return nullptr;
1867 }
1868 
1869 /// Determine whether the specified value comparison with a constant is known to
1870 /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1871 Constant *LazyValueInfo::getPredicateOnEdge(CmpInst::Predicate Pred, Value *V,
1872                                             Constant *C, BasicBlock *FromBB,
1873                                             BasicBlock *ToBB,
1874                                             Instruction *CxtI) {
1875   Module *M = FromBB->getModule();
1876   ValueLatticeElement Result =
1877       getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1878 
1879   return getPredicateResult(Pred, C, Result, M->getDataLayout());
1880 }
1881 
1882 Constant *LazyValueInfo::getPredicateAt(CmpInst::Predicate Pred, Value *V,
1883                                         Constant *C, Instruction *CxtI,
1884                                         bool UseBlockValue) {
1885   // Is or is not NonNull are common predicates being queried. If
1886   // isKnownNonZero can tell us the result of the predicate, we can
1887   // return it quickly. But this is only a fastpath, and falling
1888   // through would still be correct.
1889   Module *M = CxtI->getModule();
1890   const DataLayout &DL = M->getDataLayout();
1891   if (V->getType()->isPointerTy() && C->isNullValue() &&
1892       isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1893     Type *ResTy = CmpInst::makeCmpResultType(C->getType());
1894     if (Pred == ICmpInst::ICMP_EQ)
1895       return ConstantInt::getFalse(ResTy);
1896     else if (Pred == ICmpInst::ICMP_NE)
1897       return ConstantInt::getTrue(ResTy);
1898   }
1899 
1900   auto &Impl = getOrCreateImpl(M);
1901   ValueLatticeElement Result =
1902       UseBlockValue ? Impl.getValueInBlock(V, CxtI->getParent(), CxtI)
1903                     : Impl.getValueAt(V, CxtI);
1904   Constant *Ret = getPredicateResult(Pred, C, Result, DL);
1905   if (Ret)
1906     return Ret;
1907 
1908   // Note: The following bit of code is somewhat distinct from the rest of LVI;
1909   // LVI as a whole tries to compute a lattice value which is conservatively
1910   // correct at a given location.  In this case, we have a predicate which we
1911   // weren't able to prove about the merged result, and we're pushing that
1912   // predicate back along each incoming edge to see if we can prove it
1913   // separately for each input.  As a motivating example, consider:
1914   // bb1:
1915   //   %v1 = ... ; constantrange<1, 5>
1916   //   br label %merge
1917   // bb2:
1918   //   %v2 = ... ; constantrange<10, 20>
1919   //   br label %merge
1920   // merge:
1921   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
1922   //   %pred = icmp eq i32 %phi, 8
1923   // We can't tell from the lattice value for '%phi' that '%pred' is false
1924   // along each path, but by checking the predicate over each input separately,
1925   // we can.
1926   // We limit the search to one step backwards from the current BB and value.
1927   // We could consider extending this to search further backwards through the
1928   // CFG and/or value graph, but there are non-obvious compile time vs quality
1929   // tradeoffs.
1930   BasicBlock *BB = CxtI->getParent();
1931 
1932   // Function entry or an unreachable block.  Bail to avoid confusing
1933   // analysis below.
1934   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1935   if (PI == PE)
1936     return nullptr;
1937 
1938   // If V is a PHI node in the same block as the context, we need to ask
1939   // questions about the predicate as applied to the incoming value along
1940   // each edge. This is useful for eliminating cases where the predicate is
1941   // known along all incoming edges.
1942   if (auto *PHI = dyn_cast<PHINode>(V))
1943     if (PHI->getParent() == BB) {
1944       Constant *Baseline = nullptr;
1945       for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1946         Value *Incoming = PHI->getIncomingValue(i);
1947         BasicBlock *PredBB = PHI->getIncomingBlock(i);
1948         // Note that PredBB may be BB itself.
1949         Constant *Result =
1950             getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
1951 
1952         // Keep going as long as we've seen a consistent known result for
1953         // all inputs.
1954         Baseline = (i == 0) ? Result /* First iteration */
1955                             : (Baseline == Result ? Baseline
1956                                                   : nullptr); /* All others */
1957         if (!Baseline)
1958           break;
1959       }
1960       if (Baseline)
1961         return Baseline;
1962     }
1963 
1964   // For a comparison where the V is outside this block, it's possible
1965   // that we've branched on it before. Look to see if the value is known
1966   // on all incoming edges.
1967   if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
1968     // For predecessor edge, determine if the comparison is true or false
1969     // on that edge. If they're all true or all false, we can conclude
1970     // the value of the comparison in this block.
1971     Constant *Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1972     if (Baseline) {
1973       // Check that all remaining incoming values match the first one.
1974       while (++PI != PE) {
1975         Constant *Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1976         if (Ret != Baseline)
1977           break;
1978       }
1979       // If we terminated early, then one of the values didn't match.
1980       if (PI == PE) {
1981         return Baseline;
1982       }
1983     }
1984   }
1985 
1986   return nullptr;
1987 }
1988 
1989 Constant *LazyValueInfo::getPredicateAt(CmpInst::Predicate Pred, Value *LHS,
1990                                         Value *RHS, Instruction *CxtI,
1991                                         bool UseBlockValue) {
1992   if (auto *C = dyn_cast<Constant>(RHS))
1993     return getPredicateAt(Pred, LHS, C, CxtI, UseBlockValue);
1994   if (auto *C = dyn_cast<Constant>(LHS))
1995     return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
1996                           UseBlockValue);
1997 
1998   // Got two non-Constant values. Try to determine the comparison results based
1999   // on the block values of the two operands, e.g. because they have
2000   // non-overlapping ranges.
2001   if (UseBlockValue) {
2002     Module *M = CxtI->getModule();
2003     ValueLatticeElement L =
2004         getOrCreateImpl(M).getValueInBlock(LHS, CxtI->getParent(), CxtI);
2005     if (L.isOverdefined())
2006       return nullptr;
2007 
2008     ValueLatticeElement R =
2009         getOrCreateImpl(M).getValueInBlock(RHS, CxtI->getParent(), CxtI);
2010     Type *Ty = CmpInst::makeCmpResultType(LHS->getType());
2011     return L.getCompare(Pred, Ty, R, M->getDataLayout());
2012   }
2013   return nullptr;
2014 }
2015 
2016 void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
2017                                BasicBlock *NewSucc) {
2018   if (auto *Impl = getImpl())
2019     Impl->threadEdge(PredBB, OldSucc, NewSucc);
2020 }
2021 
2022 void LazyValueInfo::forgetValue(Value *V) {
2023   if (auto *Impl = getImpl())
2024     Impl->forgetValue(V);
2025 }
2026 
2027 void LazyValueInfo::eraseBlock(BasicBlock *BB) {
2028   if (auto *Impl = getImpl())
2029     Impl->eraseBlock(BB);
2030 }
2031 
2032 void LazyValueInfo::clear() {
2033   if (auto *Impl = getImpl())
2034     Impl->clear();
2035 }
2036 
2037 void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
2038   if (auto *Impl = getImpl())
2039     Impl->printLVI(F, DTree, OS);
2040 }
2041 
2042 // Print the LVI for the function arguments at the start of each basic block.
2043 void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
2044     const BasicBlock *BB, formatted_raw_ostream &OS) {
2045   // Find if there are latticevalues defined for arguments of the function.
2046   auto *F = BB->getParent();
2047   for (const auto &Arg : F->args()) {
2048     ValueLatticeElement Result = LVIImpl->getValueInBlock(
2049         const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2050     if (Result.isUnknown())
2051       continue;
2052     OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
2053   }
2054 }
2055 
2056 // This function prints the LVI analysis for the instruction I at the beginning
2057 // of various basic blocks. It relies on calculated values that are stored in
2058 // the LazyValueInfoCache, and in the absence of cached values, recalculate the
2059 // LazyValueInfo for `I`, and print that info.
2060 void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
2061     const Instruction *I, formatted_raw_ostream &OS) {
2062 
2063   auto *ParentBB = I->getParent();
2064   SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
2065   // We can generate (solve) LVI values only for blocks that are dominated by
2066   // the I's parent. However, to avoid generating LVI for all dominating blocks,
2067   // that contain redundant/uninteresting information, we print LVI for
2068   // blocks that may use this LVI information (such as immediate successor
2069   // blocks, and blocks that contain uses of `I`).
2070   auto printResult = [&](const BasicBlock *BB) {
2071     if (!BlocksContainingLVI.insert(BB).second)
2072       return;
2073     ValueLatticeElement Result = LVIImpl->getValueInBlock(
2074         const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
2075       OS << "; LatticeVal for: '" << *I << "' in BB: '";
2076       BB->printAsOperand(OS, false);
2077       OS << "' is: " << Result << "\n";
2078   };
2079 
2080   printResult(ParentBB);
2081   // Print the LVI analysis results for the immediate successor blocks, that
2082   // are dominated by `ParentBB`.
2083   for (const auto *BBSucc : successors(ParentBB))
2084     if (DT.dominates(ParentBB, BBSucc))
2085       printResult(BBSucc);
2086 
2087   // Print LVI in blocks where `I` is used.
2088   for (const auto *U : I->users())
2089     if (auto *UseI = dyn_cast<Instruction>(U))
2090       if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
2091         printResult(UseI->getParent());
2092 
2093 }
2094 
2095 PreservedAnalyses LazyValueInfoPrinterPass::run(Function &F,
2096                                                 FunctionAnalysisManager &AM) {
2097   OS << "LVI for function '" << F.getName() << "':\n";
2098   auto &LVI = AM.getResult<LazyValueAnalysis>(F);
2099   auto &DTree = AM.getResult<DominatorTreeAnalysis>(F);
2100   LVI.printLVI(F, DTree, OS);
2101   return PreservedAnalyses::all();
2102 }
2103