xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/LazyValueInfo.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines the interface for lazy computation of value constraint
100b57cec5SDimitry Andric // information.
110b57cec5SDimitry Andric //
120b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
130b57cec5SDimitry Andric 
140b57cec5SDimitry Andric #include "llvm/Analysis/LazyValueInfo.h"
150b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
160b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/ValueLattice.h"
22480093f4SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
230b57cec5SDimitry Andric #include "llvm/IR/AssemblyAnnotationWriter.h"
240b57cec5SDimitry Andric #include "llvm/IR/CFG.h"
250b57cec5SDimitry Andric #include "llvm/IR/ConstantRange.h"
260b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
270b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
280b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
295f757f3fSDimitry Andric #include "llvm/IR/InstrTypes.h"
300b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
310b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
320b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
330b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
34*0fca6ea1SDimitry Andric #include "llvm/IR/Module.h"
350b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
360b57cec5SDimitry Andric #include "llvm/IR/ValueHandle.h"
37480093f4SDimitry Andric #include "llvm/InitializePasses.h"
380b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
390b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h"
40e8d8bef9SDimitry Andric #include "llvm/Support/KnownBits.h"
410b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
42bdd1243dSDimitry Andric #include <optional>
430b57cec5SDimitry Andric using namespace llvm;
440b57cec5SDimitry Andric using namespace PatternMatch;
450b57cec5SDimitry Andric 
460b57cec5SDimitry Andric #define DEBUG_TYPE "lazy-value-info"
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric // This is the number of worklist items we will process to try to discover an
490b57cec5SDimitry Andric // answer for a given value.
500b57cec5SDimitry Andric static const unsigned MaxProcessedPerValue = 500;
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric char LazyValueInfoWrapperPass::ID = 0;
LazyValueInfoWrapperPass()53480093f4SDimitry Andric LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
54480093f4SDimitry Andric   initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
55480093f4SDimitry Andric }
560b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",
570b57cec5SDimitry Andric                 "Lazy Value Information Analysis", false, true)
580b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
590b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
600b57cec5SDimitry Andric INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",
610b57cec5SDimitry Andric                 "Lazy Value Information Analysis", false, true)
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric namespace llvm {
createLazyValueInfoPass()64*0fca6ea1SDimitry Andric FunctionPass *createLazyValueInfoPass() {
65*0fca6ea1SDimitry Andric   return new LazyValueInfoWrapperPass();
660b57cec5SDimitry Andric }
67*0fca6ea1SDimitry Andric } // namespace llvm
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric AnalysisKey LazyValueAnalysis::Key;
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric /// Returns true if this lattice value represents at most one possible value.
720b57cec5SDimitry Andric /// This is as precise as any lattice value can get while still representing
730b57cec5SDimitry Andric /// reachable code.
hasSingleValue(const ValueLatticeElement & Val)740b57cec5SDimitry Andric static bool hasSingleValue(const ValueLatticeElement &Val) {
750b57cec5SDimitry Andric   if (Val.isConstantRange() &&
760b57cec5SDimitry Andric       Val.getConstantRange().isSingleElement())
770b57cec5SDimitry Andric     // Integer constants are single element ranges
780b57cec5SDimitry Andric     return true;
790b57cec5SDimitry Andric   if (Val.isConstant())
800b57cec5SDimitry Andric     // Non integer constants
810b57cec5SDimitry Andric     return true;
820b57cec5SDimitry Andric   return false;
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric /// Combine two sets of facts about the same value into a single set of
860b57cec5SDimitry Andric /// facts.  Note that this method is not suitable for merging facts along
870b57cec5SDimitry Andric /// different paths in a CFG; that's what the mergeIn function is for.  This
880b57cec5SDimitry Andric /// is for merging facts gathered about the same value at the same location
890b57cec5SDimitry Andric /// through two independent means.
900b57cec5SDimitry Andric /// Notes:
910b57cec5SDimitry Andric /// * This method does not promise to return the most precise possible lattice
920b57cec5SDimitry Andric ///   value implied by A and B.  It is allowed to return any lattice element
930b57cec5SDimitry Andric ///   which is at least as strong as *either* A or B (unless our facts
940b57cec5SDimitry Andric ///   conflict, see below).
950b57cec5SDimitry Andric /// * Due to unreachable code, the intersection of two lattice values could be
960b57cec5SDimitry Andric ///   contradictory.  If this happens, we return some valid lattice value so as
970b57cec5SDimitry Andric ///   not confuse the rest of LVI.  Ideally, we'd always return Undefined, but
980b57cec5SDimitry Andric ///   we do not make this guarantee.  TODO: This would be a useful enhancement.
intersect(const ValueLatticeElement & A,const ValueLatticeElement & B)990b57cec5SDimitry Andric static ValueLatticeElement intersect(const ValueLatticeElement &A,
1000b57cec5SDimitry Andric                                      const ValueLatticeElement &B) {
1010b57cec5SDimitry Andric   // Undefined is the strongest state.  It means the value is known to be along
1020b57cec5SDimitry Andric   // an unreachable path.
103d65cd7a5SDimitry Andric   if (A.isUnknown())
1040b57cec5SDimitry Andric     return A;
105d65cd7a5SDimitry Andric   if (B.isUnknown())
1060b57cec5SDimitry Andric     return B;
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   // If we gave up for one, but got a useable fact from the other, use it.
1090b57cec5SDimitry Andric   if (A.isOverdefined())
1100b57cec5SDimitry Andric     return B;
1110b57cec5SDimitry Andric   if (B.isOverdefined())
1120b57cec5SDimitry Andric     return A;
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric   // Can't get any more precise than constants.
1150b57cec5SDimitry Andric   if (hasSingleValue(A))
1160b57cec5SDimitry Andric     return A;
1170b57cec5SDimitry Andric   if (hasSingleValue(B))
1180b57cec5SDimitry Andric     return B;
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric   // Could be either constant range or not constant here.
1210b57cec5SDimitry Andric   if (!A.isConstantRange() || !B.isConstantRange()) {
1220b57cec5SDimitry Andric     // TODO: Arbitrary choice, could be improved
1230b57cec5SDimitry Andric     return A;
1240b57cec5SDimitry Andric   }
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric   // Intersect two constant ranges
1270b57cec5SDimitry Andric   ConstantRange Range =
1280b57cec5SDimitry Andric       A.getConstantRange().intersectWith(B.getConstantRange());
1295ffd83dbSDimitry Andric   // Note: An empty range is implicitly converted to unknown or undef depending
1305ffd83dbSDimitry Andric   // on MayIncludeUndef internally.
1315ffd83dbSDimitry Andric   return ValueLatticeElement::getRange(
132349cc55cSDimitry Andric       std::move(Range), /*MayIncludeUndef=*/A.isConstantRangeIncludingUndef() ||
1335ffd83dbSDimitry Andric                             B.isConstantRangeIncludingUndef());
1340b57cec5SDimitry Andric }
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1370b57cec5SDimitry Andric //                          LazyValueInfoCache Decl
1380b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric namespace {
1410b57cec5SDimitry Andric   /// A callback value handle updates the cache when values are erased.
1420b57cec5SDimitry Andric   class LazyValueInfoCache;
1430b57cec5SDimitry Andric   struct LVIValueHandle final : public CallbackVH {
1440b57cec5SDimitry Andric     LazyValueInfoCache *Parent;
1450b57cec5SDimitry Andric 
LVIValueHandle__anon6556ff8c0111::LVIValueHandle1465ffd83dbSDimitry Andric     LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
1470b57cec5SDimitry Andric       : CallbackVH(V), Parent(P) { }
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric     void deleted() override;
allUsesReplacedWith__anon6556ff8c0111::LVIValueHandle1500b57cec5SDimitry Andric     void allUsesReplacedWith(Value *V) override {
1510b57cec5SDimitry Andric       deleted();
1520b57cec5SDimitry Andric     }
1530b57cec5SDimitry Andric   };
1540b57cec5SDimitry Andric } // end anonymous namespace
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric namespace {
157e8d8bef9SDimitry Andric using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
158e8d8bef9SDimitry Andric 
1590b57cec5SDimitry Andric /// This is the cache kept by LazyValueInfo which
1600b57cec5SDimitry Andric /// maintains information about queries across the clients' queries.
1610b57cec5SDimitry Andric class LazyValueInfoCache {
1625ffd83dbSDimitry Andric   /// This is all of the cached information for one basic block. It contains
1635ffd83dbSDimitry Andric   /// the per-value lattice elements, as well as a separate set for
164e8d8bef9SDimitry Andric   /// overdefined values to reduce memory usage. Additionally pointers
165e8d8bef9SDimitry Andric   /// dereferenced in the block are cached for nullability queries.
1665ffd83dbSDimitry Andric   struct BlockCacheEntry {
1675ffd83dbSDimitry Andric     SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
1685ffd83dbSDimitry Andric     SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
16906c3fb27SDimitry Andric     // std::nullopt indicates that the nonnull pointers for this basic block
170e8d8bef9SDimitry Andric     // block have not been computed yet.
171bdd1243dSDimitry Andric     std::optional<NonNullPointerSet> NonNullPointers;
1720b57cec5SDimitry Andric   };
1730b57cec5SDimitry Andric 
1745ffd83dbSDimitry Andric   /// Cached information per basic block.
1755ffd83dbSDimitry Andric   DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
1765ffd83dbSDimitry Andric       BlockCache;
1775ffd83dbSDimitry Andric   /// Set of value handles used to erase values from the cache on deletion.
1785ffd83dbSDimitry Andric   DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
1790b57cec5SDimitry Andric 
getBlockEntry(BasicBlock * BB) const1805ffd83dbSDimitry Andric   const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
1815ffd83dbSDimitry Andric     auto It = BlockCache.find_as(BB);
1825ffd83dbSDimitry Andric     if (It == BlockCache.end())
1835ffd83dbSDimitry Andric       return nullptr;
1845ffd83dbSDimitry Andric     return It->second.get();
1855ffd83dbSDimitry Andric   }
1860b57cec5SDimitry Andric 
getOrCreateBlockEntry(BasicBlock * BB)1875ffd83dbSDimitry Andric   BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
1885ffd83dbSDimitry Andric     auto It = BlockCache.find_as(BB);
1895ffd83dbSDimitry Andric     if (It == BlockCache.end())
190*0fca6ea1SDimitry Andric       It = BlockCache.insert({BB, std::make_unique<BlockCacheEntry>()}).first;
1915ffd83dbSDimitry Andric 
1925ffd83dbSDimitry Andric     return It->second.get();
1935ffd83dbSDimitry Andric   }
1945ffd83dbSDimitry Andric 
addValueHandle(Value * Val)1955ffd83dbSDimitry Andric   void addValueHandle(Value *Val) {
1965ffd83dbSDimitry Andric     auto HandleIt = ValueHandles.find_as(Val);
1975ffd83dbSDimitry Andric     if (HandleIt == ValueHandles.end())
1985ffd83dbSDimitry Andric       ValueHandles.insert({Val, this});
1995ffd83dbSDimitry Andric   }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric public:
insertResult(Value * Val,BasicBlock * BB,const ValueLatticeElement & Result)2020b57cec5SDimitry Andric   void insertResult(Value *Val, BasicBlock *BB,
2030b57cec5SDimitry Andric                     const ValueLatticeElement &Result) {
2045ffd83dbSDimitry Andric     BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric     // Insert over-defined values into their own cache to reduce memory
2070b57cec5SDimitry Andric     // overhead.
2080b57cec5SDimitry Andric     if (Result.isOverdefined())
2095ffd83dbSDimitry Andric       Entry->OverDefined.insert(Val);
2105ffd83dbSDimitry Andric     else
2115ffd83dbSDimitry Andric       Entry->LatticeElements.insert({Val, Result});
2125ffd83dbSDimitry Andric 
2135ffd83dbSDimitry Andric     addValueHandle(Val);
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric 
getCachedValueInfo(Value * V,BasicBlock * BB) const216*0fca6ea1SDimitry Andric   std::optional<ValueLatticeElement> getCachedValueInfo(Value *V,
217*0fca6ea1SDimitry Andric                                                         BasicBlock *BB) const {
2185ffd83dbSDimitry Andric     const BlockCacheEntry *Entry = getBlockEntry(BB);
2195ffd83dbSDimitry Andric     if (!Entry)
220bdd1243dSDimitry Andric       return std::nullopt;
2210b57cec5SDimitry Andric 
2225ffd83dbSDimitry Andric     if (Entry->OverDefined.count(V))
2230b57cec5SDimitry Andric       return ValueLatticeElement::getOverdefined();
2240b57cec5SDimitry Andric 
2255ffd83dbSDimitry Andric     auto LatticeIt = Entry->LatticeElements.find_as(V);
2265ffd83dbSDimitry Andric     if (LatticeIt == Entry->LatticeElements.end())
227bdd1243dSDimitry Andric       return std::nullopt;
2285ffd83dbSDimitry Andric 
2295ffd83dbSDimitry Andric     return LatticeIt->second;
2300b57cec5SDimitry Andric   }
2310b57cec5SDimitry Andric 
232*0fca6ea1SDimitry Andric   bool
isNonNullAtEndOfBlock(Value * V,BasicBlock * BB,function_ref<NonNullPointerSet (BasicBlock *)> InitFn)233*0fca6ea1SDimitry Andric   isNonNullAtEndOfBlock(Value *V, BasicBlock *BB,
234e8d8bef9SDimitry Andric                         function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
235e8d8bef9SDimitry Andric     BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
236e8d8bef9SDimitry Andric     if (!Entry->NonNullPointers) {
237e8d8bef9SDimitry Andric       Entry->NonNullPointers = InitFn(BB);
238e8d8bef9SDimitry Andric       for (Value *V : *Entry->NonNullPointers)
239e8d8bef9SDimitry Andric         addValueHandle(V);
240e8d8bef9SDimitry Andric     }
241e8d8bef9SDimitry Andric 
242e8d8bef9SDimitry Andric     return Entry->NonNullPointers->count(V);
243e8d8bef9SDimitry Andric   }
244e8d8bef9SDimitry Andric 
2450b57cec5SDimitry Andric   /// clear - Empty the cache.
clear()2460b57cec5SDimitry Andric   void clear() {
2475ffd83dbSDimitry Andric     BlockCache.clear();
2485ffd83dbSDimitry Andric     ValueHandles.clear();
2490b57cec5SDimitry Andric   }
2500b57cec5SDimitry Andric 
2510b57cec5SDimitry Andric   /// Inform the cache that a given value has been deleted.
2520b57cec5SDimitry Andric   void eraseValue(Value *V);
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   /// This is part of the update interface to inform the cache
2550b57cec5SDimitry Andric   /// that a block has been deleted.
2560b57cec5SDimitry Andric   void eraseBlock(BasicBlock *BB);
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   /// Updates the cache to remove any influence an overdefined value in
2590b57cec5SDimitry Andric   /// OldSucc might have (unless also overdefined in NewSucc).  This just
2600b57cec5SDimitry Andric   /// flushes elements from the cache and does not add any.
2610b57cec5SDimitry Andric   void threadEdgeImpl(BasicBlock *OldSucc, BasicBlock *NewSucc);
2620b57cec5SDimitry Andric };
263*0fca6ea1SDimitry Andric } // namespace
2640b57cec5SDimitry Andric 
eraseValue(Value * V)2650b57cec5SDimitry Andric void LazyValueInfoCache::eraseValue(Value *V) {
2665ffd83dbSDimitry Andric   for (auto &Pair : BlockCache) {
2675ffd83dbSDimitry Andric     Pair.second->LatticeElements.erase(V);
2685ffd83dbSDimitry Andric     Pair.second->OverDefined.erase(V);
269e8d8bef9SDimitry Andric     if (Pair.second->NonNullPointers)
270e8d8bef9SDimitry Andric       Pair.second->NonNullPointers->erase(V);
2710b57cec5SDimitry Andric   }
2720b57cec5SDimitry Andric 
2735ffd83dbSDimitry Andric   auto HandleIt = ValueHandles.find_as(V);
2745ffd83dbSDimitry Andric   if (HandleIt != ValueHandles.end())
2755ffd83dbSDimitry Andric     ValueHandles.erase(HandleIt);
2760b57cec5SDimitry Andric }
2770b57cec5SDimitry Andric 
deleted()2780b57cec5SDimitry Andric void LVIValueHandle::deleted() {
2790b57cec5SDimitry Andric   // This erasure deallocates *this, so it MUST happen after we're done
2800b57cec5SDimitry Andric   // using any and all members of *this.
2810b57cec5SDimitry Andric   Parent->eraseValue(*this);
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric 
eraseBlock(BasicBlock * BB)2840b57cec5SDimitry Andric void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
2855ffd83dbSDimitry Andric   BlockCache.erase(BB);
2860b57cec5SDimitry Andric }
2870b57cec5SDimitry Andric 
threadEdgeImpl(BasicBlock * OldSucc,BasicBlock * NewSucc)2880b57cec5SDimitry Andric void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
2890b57cec5SDimitry Andric                                         BasicBlock *NewSucc) {
2900b57cec5SDimitry Andric   // When an edge in the graph has been threaded, values that we could not
2910b57cec5SDimitry Andric   // determine a value for before (i.e. were marked overdefined) may be
2920b57cec5SDimitry Andric   // possible to solve now. We do NOT try to proactively update these values.
2930b57cec5SDimitry Andric   // Instead, we clear their entries from the cache, and allow lazy updating to
2940b57cec5SDimitry Andric   // recompute them when needed.
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric   // The updating process is fairly simple: we need to drop cached info
2970b57cec5SDimitry Andric   // for all values that were marked overdefined in OldSucc, and for those same
2980b57cec5SDimitry Andric   // values in any successor of OldSucc (except NewSucc) in which they were
2990b57cec5SDimitry Andric   // also marked overdefined.
3000b57cec5SDimitry Andric   std::vector<BasicBlock*> worklist;
3010b57cec5SDimitry Andric   worklist.push_back(OldSucc);
3020b57cec5SDimitry Andric 
3035ffd83dbSDimitry Andric   const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
3045ffd83dbSDimitry Andric   if (!Entry || Entry->OverDefined.empty())
3050b57cec5SDimitry Andric     return; // Nothing to process here.
3065ffd83dbSDimitry Andric   SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
3075ffd83dbSDimitry Andric                                       Entry->OverDefined.end());
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   // Use a worklist to perform a depth-first search of OldSucc's successors.
3100b57cec5SDimitry Andric   // NOTE: We do not need a visited list since any blocks we have already
3110b57cec5SDimitry Andric   // visited will have had their overdefined markers cleared already, and we
3120b57cec5SDimitry Andric   // thus won't loop to their successors.
3130b57cec5SDimitry Andric   while (!worklist.empty()) {
3140b57cec5SDimitry Andric     BasicBlock *ToUpdate = worklist.back();
3150b57cec5SDimitry Andric     worklist.pop_back();
3160b57cec5SDimitry Andric 
3170b57cec5SDimitry Andric     // Skip blocks only accessible through NewSucc.
3180b57cec5SDimitry Andric     if (ToUpdate == NewSucc) continue;
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric     // If a value was marked overdefined in OldSucc, and is here too...
3215ffd83dbSDimitry Andric     auto OI = BlockCache.find_as(ToUpdate);
3225ffd83dbSDimitry Andric     if (OI == BlockCache.end() || OI->second->OverDefined.empty())
3230b57cec5SDimitry Andric       continue;
3245ffd83dbSDimitry Andric     auto &ValueSet = OI->second->OverDefined;
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric     bool changed = false;
3270b57cec5SDimitry Andric     for (Value *V : ValsToClear) {
3280b57cec5SDimitry Andric       if (!ValueSet.erase(V))
3290b57cec5SDimitry Andric         continue;
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric       // If we removed anything, then we potentially need to update
3320b57cec5SDimitry Andric       // blocks successors too.
3330b57cec5SDimitry Andric       changed = true;
3340b57cec5SDimitry Andric     }
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric     if (!changed) continue;
3370b57cec5SDimitry Andric 
338e8d8bef9SDimitry Andric     llvm::append_range(worklist, successors(ToUpdate));
3390b57cec5SDimitry Andric   }
3400b57cec5SDimitry Andric }
3410b57cec5SDimitry Andric 
3425f757f3fSDimitry Andric namespace llvm {
3430b57cec5SDimitry Andric namespace {
3440b57cec5SDimitry Andric /// An assembly annotator class to print LazyValueCache information in
3450b57cec5SDimitry Andric /// comments.
3460b57cec5SDimitry Andric class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
3470b57cec5SDimitry Andric   LazyValueInfoImpl *LVIImpl;
3480b57cec5SDimitry Andric   // While analyzing which blocks we can solve values for, we need the dominator
3495ffd83dbSDimitry Andric   // information.
3500b57cec5SDimitry Andric   DominatorTree &DT;
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric public:
LazyValueInfoAnnotatedWriter(LazyValueInfoImpl * L,DominatorTree & DTree)3530b57cec5SDimitry Andric   LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
3540b57cec5SDimitry Andric       : LVIImpl(L), DT(DTree) {}
3550b57cec5SDimitry Andric 
3565ffd83dbSDimitry Andric   void emitBasicBlockStartAnnot(const BasicBlock *BB,
3575ffd83dbSDimitry Andric                                 formatted_raw_ostream &OS) override;
3580b57cec5SDimitry Andric 
3595ffd83dbSDimitry Andric   void emitInstructionAnnot(const Instruction *I,
3605ffd83dbSDimitry Andric                             formatted_raw_ostream &OS) override;
3610b57cec5SDimitry Andric };
3625f757f3fSDimitry Andric } // namespace
3630b57cec5SDimitry Andric // The actual implementation of the lazy analysis and update.  Note that the
3640b57cec5SDimitry Andric // inheritance from LazyValueInfoCache is intended to be temporary while
3650b57cec5SDimitry Andric // splitting the code and then transitioning to a has-a relationship.
3660b57cec5SDimitry Andric class LazyValueInfoImpl {
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric   /// Cached results from previous queries
3690b57cec5SDimitry Andric   LazyValueInfoCache TheCache;
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric   /// This stack holds the state of the value solver during a query.
3720b57cec5SDimitry Andric   /// It basically emulates the callstack of the naive
3730b57cec5SDimitry Andric   /// recursive value lookup process.
3740b57cec5SDimitry Andric   SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric   /// Keeps track of which block-value pairs are in BlockValueStack.
3770b57cec5SDimitry Andric   DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric   /// Push BV onto BlockValueStack unless it's already in there.
3800b57cec5SDimitry Andric   /// Returns true on success.
pushBlockValue(const std::pair<BasicBlock *,Value * > & BV)3810b57cec5SDimitry Andric   bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
3820b57cec5SDimitry Andric     if (!BlockValueSet.insert(BV).second)
3830b57cec5SDimitry Andric       return false;  // It's already in the stack.
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "
3860b57cec5SDimitry Andric                       << BV.first->getName() << "\n");
3870b57cec5SDimitry Andric     BlockValueStack.push_back(BV);
3880b57cec5SDimitry Andric     return true;
3890b57cec5SDimitry Andric   }
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric   AssumptionCache *AC;  ///< A pointer to the cache of @llvm.assume calls.
3920b57cec5SDimitry Andric   const DataLayout &DL; ///< A mandatory DataLayout
3930b57cec5SDimitry Andric 
3945ffd83dbSDimitry Andric   /// Declaration of the llvm.experimental.guard() intrinsic,
3955ffd83dbSDimitry Andric   /// if it exists in the module.
3965ffd83dbSDimitry Andric   Function *GuardDecl;
3975ffd83dbSDimitry Andric 
398bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
39904eeddc0SDimitry Andric                                                    Instruction *CxtI);
400bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
401bdd1243dSDimitry Andric                                                   BasicBlock *T,
402bdd1243dSDimitry Andric                                                   Instruction *CxtI = nullptr);
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   // These methods process one work item and may add more. A false value
4050b57cec5SDimitry Andric   // returned means that the work item was not completely processed and must
4060b57cec5SDimitry Andric   // be revisited after going through the new items.
4070b57cec5SDimitry Andric   bool solveBlockValue(Value *Val, BasicBlock *BB);
408bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueImpl(Value *Val,
4090b57cec5SDimitry Andric                                                          BasicBlock *BB);
410bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
4110b57cec5SDimitry Andric                                                              BasicBlock *BB);
412bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
4130b57cec5SDimitry Andric                                                             BasicBlock *BB);
414bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
4150b57cec5SDimitry Andric                                                            BasicBlock *BB);
416bdd1243dSDimitry Andric   std::optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
417bdd1243dSDimitry Andric                                            BasicBlock *BB);
418bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
4195ffd83dbSDimitry Andric       Instruction *I, BasicBlock *BB,
420bdd1243dSDimitry Andric       std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
421bdd1243dSDimitry Andric           OpFn);
422bdd1243dSDimitry Andric   std::optional<ValueLatticeElement>
423bdd1243dSDimitry Andric   solveBlockValueBinaryOp(BinaryOperator *BBI, BasicBlock *BB);
424bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
4250b57cec5SDimitry Andric                                                          BasicBlock *BB);
426bdd1243dSDimitry Andric   std::optional<ValueLatticeElement>
427bdd1243dSDimitry Andric   solveBlockValueOverflowIntrinsic(WithOverflowInst *WO, BasicBlock *BB);
428bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
4290b57cec5SDimitry Andric                                                               BasicBlock *BB);
430bdd1243dSDimitry Andric   std::optional<ValueLatticeElement>
431*0fca6ea1SDimitry Andric   solveBlockValueInsertElement(InsertElementInst *IEI, BasicBlock *BB);
432*0fca6ea1SDimitry Andric   std::optional<ValueLatticeElement>
433bdd1243dSDimitry Andric   solveBlockValueExtractValue(ExtractValueInst *EVI, BasicBlock *BB);
434e8d8bef9SDimitry Andric   bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
4350b57cec5SDimitry Andric   void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
4360b57cec5SDimitry Andric                                                      ValueLatticeElement &BBLV,
4370b57cec5SDimitry Andric                                                      Instruction *BBI);
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric   void solve();
4400b57cec5SDimitry Andric 
441647cbc5dSDimitry Andric   // For the following methods, if UseBlockValue is true, the function may
442647cbc5dSDimitry Andric   // push additional values to the worklist and return nullopt. If
443647cbc5dSDimitry Andric   // UseBlockValue is false, it will never return nullopt.
444647cbc5dSDimitry Andric 
445647cbc5dSDimitry Andric   std::optional<ValueLatticeElement>
446647cbc5dSDimitry Andric   getValueFromSimpleICmpCondition(CmpInst::Predicate Pred, Value *RHS,
447647cbc5dSDimitry Andric                                   const APInt &Offset, Instruction *CxtI,
448647cbc5dSDimitry Andric                                   bool UseBlockValue);
449647cbc5dSDimitry Andric 
450647cbc5dSDimitry Andric   std::optional<ValueLatticeElement>
451647cbc5dSDimitry Andric   getValueFromICmpCondition(Value *Val, ICmpInst *ICI, bool isTrueDest,
452647cbc5dSDimitry Andric                             bool UseBlockValue);
453647cbc5dSDimitry Andric 
454647cbc5dSDimitry Andric   std::optional<ValueLatticeElement>
455647cbc5dSDimitry Andric   getValueFromCondition(Value *Val, Value *Cond, bool IsTrueDest,
456647cbc5dSDimitry Andric                         bool UseBlockValue, unsigned Depth = 0);
457647cbc5dSDimitry Andric 
458647cbc5dSDimitry Andric   std::optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
459647cbc5dSDimitry Andric                                                        BasicBlock *BBFrom,
460647cbc5dSDimitry Andric                                                        BasicBlock *BBTo,
461647cbc5dSDimitry Andric                                                        bool UseBlockValue);
462647cbc5dSDimitry Andric 
4630b57cec5SDimitry Andric public:
464e8d8bef9SDimitry Andric   /// This is the query interface to determine the lattice value for the
465e8d8bef9SDimitry Andric   /// specified Value* at the context instruction (if specified) or at the
466e8d8bef9SDimitry Andric   /// start of the block.
4670b57cec5SDimitry Andric   ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
4680b57cec5SDimitry Andric                                       Instruction *CxtI = nullptr);
4690b57cec5SDimitry Andric 
470e8d8bef9SDimitry Andric   /// This is the query interface to determine the lattice value for the
471e8d8bef9SDimitry Andric   /// specified Value* at the specified instruction using only information
472e8d8bef9SDimitry Andric   /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
473e8d8bef9SDimitry Andric   /// recursive query is performed.
4740b57cec5SDimitry Andric   ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   /// This is the query interface to determine the lattice
4770b57cec5SDimitry Andric   /// value for the specified Value* that is true on the specified edge.
4780b57cec5SDimitry Andric   ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
4790b57cec5SDimitry Andric                                      BasicBlock *ToBB,
4800b57cec5SDimitry Andric                                      Instruction *CxtI = nullptr);
4810b57cec5SDimitry Andric 
4825f757f3fSDimitry Andric   ValueLatticeElement getValueAtUse(const Use &U);
4835f757f3fSDimitry Andric 
4840b57cec5SDimitry Andric   /// Complete flush all previously computed values
clear()4850b57cec5SDimitry Andric   void clear() {
4860b57cec5SDimitry Andric     TheCache.clear();
4870b57cec5SDimitry Andric   }
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric   /// Printing the LazyValueInfo Analysis.
printLVI(Function & F,DominatorTree & DTree,raw_ostream & OS)4900b57cec5SDimitry Andric   void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
4910b57cec5SDimitry Andric     LazyValueInfoAnnotatedWriter Writer(this, DTree);
4920b57cec5SDimitry Andric     F.print(OS, &Writer);
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric 
4958a4dda33SDimitry Andric   /// This is part of the update interface to remove information related to this
4968a4dda33SDimitry Andric   /// value from the cache.
forgetValue(Value * V)4978a4dda33SDimitry Andric   void forgetValue(Value *V) { TheCache.eraseValue(V); }
4988a4dda33SDimitry Andric 
4990b57cec5SDimitry Andric   /// This is part of the update interface to inform the cache
5000b57cec5SDimitry Andric   /// that a block has been deleted.
eraseBlock(BasicBlock * BB)5010b57cec5SDimitry Andric   void eraseBlock(BasicBlock *BB) {
5020b57cec5SDimitry Andric     TheCache.eraseBlock(BB);
5030b57cec5SDimitry Andric   }
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   /// This is the update interface to inform the cache that an edge from
5060b57cec5SDimitry Andric   /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
5070b57cec5SDimitry Andric   void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
5080b57cec5SDimitry Andric 
LazyValueInfoImpl(AssumptionCache * AC,const DataLayout & DL,Function * GuardDecl)5090b57cec5SDimitry Andric   LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
5105ffd83dbSDimitry Andric                     Function *GuardDecl)
5115ffd83dbSDimitry Andric       : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
5120b57cec5SDimitry Andric };
5135f757f3fSDimitry Andric } // namespace llvm
5140b57cec5SDimitry Andric 
solve()5150b57cec5SDimitry Andric void LazyValueInfoImpl::solve() {
5160b57cec5SDimitry Andric   SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
5170b57cec5SDimitry Andric       BlockValueStack.begin(), BlockValueStack.end());
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   unsigned processedCount = 0;
5200b57cec5SDimitry Andric   while (!BlockValueStack.empty()) {
5210b57cec5SDimitry Andric     processedCount++;
5220b57cec5SDimitry Andric     // Abort if we have to process too many values to get a result for this one.
5230b57cec5SDimitry Andric     // Because of the design of the overdefined cache currently being per-block
5240b57cec5SDimitry Andric     // to avoid naming-related issues (IE it wants to try to give different
5250b57cec5SDimitry Andric     // results for the same name in different blocks), overdefined results don't
5260b57cec5SDimitry Andric     // get cached globally, which in turn means we will often try to rediscover
5270b57cec5SDimitry Andric     // the same overdefined result again and again.  Once something like
5280b57cec5SDimitry Andric     // PredicateInfo is used in LVI or CVP, we should be able to make the
5290b57cec5SDimitry Andric     // overdefined cache global, and remove this throttle.
5300b57cec5SDimitry Andric     if (processedCount > MaxProcessedPerValue) {
5310b57cec5SDimitry Andric       LLVM_DEBUG(
5320b57cec5SDimitry Andric           dbgs() << "Giving up on stack because we are getting too deep\n");
5330b57cec5SDimitry Andric       // Fill in the original values
5340b57cec5SDimitry Andric       while (!StartingStack.empty()) {
5350b57cec5SDimitry Andric         std::pair<BasicBlock *, Value *> &e = StartingStack.back();
5360b57cec5SDimitry Andric         TheCache.insertResult(e.second, e.first,
5370b57cec5SDimitry Andric                               ValueLatticeElement::getOverdefined());
5380b57cec5SDimitry Andric         StartingStack.pop_back();
5390b57cec5SDimitry Andric       }
5400b57cec5SDimitry Andric       BlockValueSet.clear();
5410b57cec5SDimitry Andric       BlockValueStack.clear();
5420b57cec5SDimitry Andric       return;
5430b57cec5SDimitry Andric     }
5440b57cec5SDimitry Andric     std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
5450b57cec5SDimitry Andric     assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!");
546297eecfbSDimitry Andric     unsigned StackSize = BlockValueStack.size();
547297eecfbSDimitry Andric     (void) StackSize;
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric     if (solveBlockValue(e.second, e.first)) {
5500b57cec5SDimitry Andric       // The work item was completely processed.
551297eecfbSDimitry Andric       assert(BlockValueStack.size() == StackSize &&
552297eecfbSDimitry Andric              BlockValueStack.back() == e && "Nothing should have been pushed!");
5535ffd83dbSDimitry Andric #ifndef NDEBUG
554bdd1243dSDimitry Andric       std::optional<ValueLatticeElement> BBLV =
5555ffd83dbSDimitry Andric           TheCache.getCachedValueInfo(e.second, e.first);
5565ffd83dbSDimitry Andric       assert(BBLV && "Result should be in cache!");
5570b57cec5SDimitry Andric       LLVM_DEBUG(
5580b57cec5SDimitry Andric           dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "
5595ffd83dbSDimitry Andric                  << *BBLV << "\n");
5605ffd83dbSDimitry Andric #endif
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric       BlockValueStack.pop_back();
5630b57cec5SDimitry Andric       BlockValueSet.erase(e);
5640b57cec5SDimitry Andric     } else {
5650b57cec5SDimitry Andric       // More work needs to be done before revisiting.
566297eecfbSDimitry Andric       assert(BlockValueStack.size() == StackSize + 1 &&
567297eecfbSDimitry Andric              "Exactly one element should have been pushed!");
5680b57cec5SDimitry Andric     }
5690b57cec5SDimitry Andric   }
5700b57cec5SDimitry Andric }
5710b57cec5SDimitry Andric 
572bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
getBlockValue(Value * Val,BasicBlock * BB,Instruction * CxtI)573bdd1243dSDimitry Andric LazyValueInfoImpl::getBlockValue(Value *Val, BasicBlock *BB,
574bdd1243dSDimitry Andric                                  Instruction *CxtI) {
5750b57cec5SDimitry Andric   // If already a constant, there is nothing to compute.
5760b57cec5SDimitry Andric   if (Constant *VC = dyn_cast<Constant>(Val))
5770b57cec5SDimitry Andric     return ValueLatticeElement::get(VC);
5780b57cec5SDimitry Andric 
579bdd1243dSDimitry Andric   if (std::optional<ValueLatticeElement> OptLatticeVal =
58004eeddc0SDimitry Andric           TheCache.getCachedValueInfo(Val, BB)) {
58104eeddc0SDimitry Andric     intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
5825ffd83dbSDimitry Andric     return OptLatticeVal;
58304eeddc0SDimitry Andric   }
5845ffd83dbSDimitry Andric 
5855ffd83dbSDimitry Andric   // We have hit a cycle, assume overdefined.
5865ffd83dbSDimitry Andric   if (!pushBlockValue({ BB, Val }))
5875ffd83dbSDimitry Andric     return ValueLatticeElement::getOverdefined();
5885ffd83dbSDimitry Andric 
5895ffd83dbSDimitry Andric   // Yet to be resolved.
590bdd1243dSDimitry Andric   return std::nullopt;
5910b57cec5SDimitry Andric }
5920b57cec5SDimitry Andric 
getFromRangeMetadata(Instruction * BBI)5930b57cec5SDimitry Andric static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
5940b57cec5SDimitry Andric   switch (BBI->getOpcode()) {
595*0fca6ea1SDimitry Andric   default:
596*0fca6ea1SDimitry Andric     break;
5970b57cec5SDimitry Andric   case Instruction::Call:
5980b57cec5SDimitry Andric   case Instruction::Invoke:
599*0fca6ea1SDimitry Andric     if (std::optional<ConstantRange> Range = cast<CallBase>(BBI)->getRange())
600*0fca6ea1SDimitry Andric       return ValueLatticeElement::getRange(*Range);
601*0fca6ea1SDimitry Andric     [[fallthrough]];
602*0fca6ea1SDimitry Andric   case Instruction::Load:
6030b57cec5SDimitry Andric     if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
6040b57cec5SDimitry Andric       if (isa<IntegerType>(BBI->getType())) {
6050b57cec5SDimitry Andric         return ValueLatticeElement::getRange(
6060b57cec5SDimitry Andric             getConstantRangeFromMetadata(*Ranges));
6070b57cec5SDimitry Andric       }
6080b57cec5SDimitry Andric     break;
6090b57cec5SDimitry Andric   };
6100b57cec5SDimitry Andric   // Nothing known - will be intersected with other facts
6110b57cec5SDimitry Andric   return ValueLatticeElement::getOverdefined();
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric 
solveBlockValue(Value * Val,BasicBlock * BB)6140b57cec5SDimitry Andric bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
6155ffd83dbSDimitry Andric   assert(!isa<Constant>(Val) && "Value should not be constant");
6165ffd83dbSDimitry Andric   assert(!TheCache.getCachedValueInfo(Val, BB) &&
6175ffd83dbSDimitry Andric          "Value should not be in cache");
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   // Hold off inserting this value into the Cache in case we have to return
6200b57cec5SDimitry Andric   // false and come back later.
621bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
6225ffd83dbSDimitry Andric   if (!Res)
6230b57cec5SDimitry Andric     // Work pushed, will revisit
6240b57cec5SDimitry Andric     return false;
6250b57cec5SDimitry Andric 
6265ffd83dbSDimitry Andric   TheCache.insertResult(Val, BB, *Res);
6270b57cec5SDimitry Andric   return true;
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric 
630bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueImpl(Value * Val,BasicBlock * BB)631bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueImpl(Value *Val, BasicBlock *BB) {
6320b57cec5SDimitry Andric   Instruction *BBI = dyn_cast<Instruction>(Val);
6330b57cec5SDimitry Andric   if (!BBI || BBI->getParent() != BB)
6345ffd83dbSDimitry Andric     return solveBlockValueNonLocal(Val, BB);
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   if (PHINode *PN = dyn_cast<PHINode>(BBI))
6375ffd83dbSDimitry Andric     return solveBlockValuePHINode(PN, BB);
6380b57cec5SDimitry Andric 
6390b57cec5SDimitry Andric   if (auto *SI = dyn_cast<SelectInst>(BBI))
6405ffd83dbSDimitry Andric     return solveBlockValueSelect(SI, BB);
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   // If this value is a nonnull pointer, record it's range and bailout.  Note
6430b57cec5SDimitry Andric   // that for all other pointer typed values, we terminate the search at the
6440b57cec5SDimitry Andric   // definition.  We could easily extend this to look through geps, bitcasts,
6450b57cec5SDimitry Andric   // and the like to prove non-nullness, but it's not clear that's worth it
6460b57cec5SDimitry Andric   // compile time wise.  The context-insensitive value walk done inside
6470b57cec5SDimitry Andric   // isKnownNonZero gets most of the profitable cases at much less expense.
6480b57cec5SDimitry Andric   // This does mean that we have a sensitivity to where the defining
6490b57cec5SDimitry Andric   // instruction is placed, even if it could legally be hoisted much higher.
6500b57cec5SDimitry Andric   // That is unfortunate.
6510b57cec5SDimitry Andric   PointerType *PT = dyn_cast<PointerType>(BBI->getType());
6525ffd83dbSDimitry Andric   if (PT && isKnownNonZero(BBI, DL))
6535ffd83dbSDimitry Andric     return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
6545ffd83dbSDimitry Andric 
655*0fca6ea1SDimitry Andric   if (BBI->getType()->isIntOrIntVectorTy()) {
6560b57cec5SDimitry Andric     if (auto *CI = dyn_cast<CastInst>(BBI))
6575ffd83dbSDimitry Andric       return solveBlockValueCast(CI, BB);
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
6605ffd83dbSDimitry Andric       return solveBlockValueBinaryOp(BO, BB);
6610b57cec5SDimitry Andric 
662*0fca6ea1SDimitry Andric     if (auto *IEI = dyn_cast<InsertElementInst>(BBI))
663*0fca6ea1SDimitry Andric       return solveBlockValueInsertElement(IEI, BB);
664*0fca6ea1SDimitry Andric 
6650b57cec5SDimitry Andric     if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
6665ffd83dbSDimitry Andric       return solveBlockValueExtractValue(EVI, BB);
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric     if (auto *II = dyn_cast<IntrinsicInst>(BBI))
6695ffd83dbSDimitry Andric       return solveBlockValueIntrinsic(II, BB);
6700b57cec5SDimitry Andric   }
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
6730b57cec5SDimitry Andric                     << "' - unknown inst def found.\n");
6745ffd83dbSDimitry Andric   return getFromRangeMetadata(BBI);
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric 
AddNonNullPointer(Value * Ptr,NonNullPointerSet & PtrSet)677e8d8bef9SDimitry Andric static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
678e8d8bef9SDimitry Andric   // TODO: Use NullPointerIsDefined instead.
679e8d8bef9SDimitry Andric   if (Ptr->getType()->getPointerAddressSpace() == 0)
680e8d8bef9SDimitry Andric     PtrSet.insert(getUnderlyingObject(Ptr));
681e8d8bef9SDimitry Andric }
682e8d8bef9SDimitry Andric 
AddNonNullPointersByInstruction(Instruction * I,NonNullPointerSet & PtrSet)683e8d8bef9SDimitry Andric static void AddNonNullPointersByInstruction(
684e8d8bef9SDimitry Andric     Instruction *I, NonNullPointerSet &PtrSet) {
6850b57cec5SDimitry Andric   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
686e8d8bef9SDimitry Andric     AddNonNullPointer(L->getPointerOperand(), PtrSet);
687e8d8bef9SDimitry Andric   } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
688e8d8bef9SDimitry Andric     AddNonNullPointer(S->getPointerOperand(), PtrSet);
689e8d8bef9SDimitry Andric   } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
690e8d8bef9SDimitry Andric     if (MI->isVolatile()) return;
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric     // FIXME: check whether it has a valuerange that excludes zero?
6930b57cec5SDimitry Andric     ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
694e8d8bef9SDimitry Andric     if (!Len || Len->isZero()) return;
6950b57cec5SDimitry Andric 
696e8d8bef9SDimitry Andric     AddNonNullPointer(MI->getRawDest(), PtrSet);
6970b57cec5SDimitry Andric     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
698e8d8bef9SDimitry Andric       AddNonNullPointer(MTI->getRawSource(), PtrSet);
6990b57cec5SDimitry Andric   }
700e8d8bef9SDimitry Andric }
701e8d8bef9SDimitry Andric 
isNonNullAtEndOfBlock(Value * Val,BasicBlock * BB)702e8d8bef9SDimitry Andric bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
703e8d8bef9SDimitry Andric   if (NullPointerIsDefined(BB->getParent(),
704e8d8bef9SDimitry Andric                            Val->getType()->getPointerAddressSpace()))
7050b57cec5SDimitry Andric     return false;
7060b57cec5SDimitry Andric 
707fe6060f1SDimitry Andric   Val = Val->stripInBoundsOffsets();
708e8d8bef9SDimitry Andric   return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
709e8d8bef9SDimitry Andric     NonNullPointerSet NonNullPointers;
7100b57cec5SDimitry Andric     for (Instruction &I : *BB)
711e8d8bef9SDimitry Andric       AddNonNullPointersByInstruction(&I, NonNullPointers);
712e8d8bef9SDimitry Andric     return NonNullPointers;
713e8d8bef9SDimitry Andric   });
7140b57cec5SDimitry Andric }
7150b57cec5SDimitry Andric 
716bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueNonLocal(Value * Val,BasicBlock * BB)717bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueNonLocal(Value *Val, BasicBlock *BB) {
7180b57cec5SDimitry Andric   ValueLatticeElement Result;  // Start Undefined.
7190b57cec5SDimitry Andric 
720*0fca6ea1SDimitry Andric   // If this is the entry block, we must be asking about an argument.
721fe6060f1SDimitry Andric   if (BB->isEntryBlock()) {
7220b57cec5SDimitry Andric     assert(isa<Argument>(Val) && "Unknown live-in to the entry block");
723*0fca6ea1SDimitry Andric     if (std::optional<ConstantRange> Range = cast<Argument>(Val)->getRange())
724*0fca6ea1SDimitry Andric       return ValueLatticeElement::getRange(*Range);
7255ffd83dbSDimitry Andric     return ValueLatticeElement::getOverdefined();
7260b57cec5SDimitry Andric   }
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   // Loop over all of our predecessors, merging what we know from them into
7290b57cec5SDimitry Andric   // result.  If we encounter an unexplored predecessor, we eagerly explore it
7300b57cec5SDimitry Andric   // in a depth first manner.  In practice, this has the effect of discovering
7310b57cec5SDimitry Andric   // paths we can't analyze eagerly without spending compile times analyzing
7320b57cec5SDimitry Andric   // other paths.  This heuristic benefits from the fact that predecessors are
7330b57cec5SDimitry Andric   // frequently arranged such that dominating ones come first and we quickly
7340b57cec5SDimitry Andric   // find a path to function entry.  TODO: We should consider explicitly
7350b57cec5SDimitry Andric   // canonicalizing to make this true rather than relying on this happy
7360b57cec5SDimitry Andric   // accident.
737fe6060f1SDimitry Andric   for (BasicBlock *Pred : predecessors(BB)) {
738bdd1243dSDimitry Andric     std::optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
7395ffd83dbSDimitry Andric     if (!EdgeResult)
7400b57cec5SDimitry Andric       // Explore that input, then return here
741bdd1243dSDimitry Andric       return std::nullopt;
7420b57cec5SDimitry Andric 
7435ffd83dbSDimitry Andric     Result.mergeIn(*EdgeResult);
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric     // If we hit overdefined, exit early.  The BlockVals entry is already set
7460b57cec5SDimitry Andric     // to overdefined.
7470b57cec5SDimitry Andric     if (Result.isOverdefined()) {
7480b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
749bdd1243dSDimitry Andric                         << "' - overdefined because of pred '"
750bdd1243dSDimitry Andric                         << Pred->getName() << "' (non local).\n");
7515ffd83dbSDimitry Andric       return Result;
7520b57cec5SDimitry Andric     }
7530b57cec5SDimitry Andric   }
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   // Return the merged value, which is more precise than 'overdefined'.
7560b57cec5SDimitry Andric   assert(!Result.isOverdefined());
7575ffd83dbSDimitry Andric   return Result;
7580b57cec5SDimitry Andric }
7590b57cec5SDimitry Andric 
760bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValuePHINode(PHINode * PN,BasicBlock * BB)761bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValuePHINode(PHINode *PN, BasicBlock *BB) {
7620b57cec5SDimitry Andric   ValueLatticeElement Result;  // Start Undefined.
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric   // Loop over all of our predecessors, merging what we know from them into
7650b57cec5SDimitry Andric   // result.  See the comment about the chosen traversal order in
7660b57cec5SDimitry Andric   // solveBlockValueNonLocal; the same reasoning applies here.
7670b57cec5SDimitry Andric   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7680b57cec5SDimitry Andric     BasicBlock *PhiBB = PN->getIncomingBlock(i);
7690b57cec5SDimitry Andric     Value *PhiVal = PN->getIncomingValue(i);
7700b57cec5SDimitry Andric     // Note that we can provide PN as the context value to getEdgeValue, even
7710b57cec5SDimitry Andric     // though the results will be cached, because PN is the value being used as
7720b57cec5SDimitry Andric     // the cache key in the caller.
773bdd1243dSDimitry Andric     std::optional<ValueLatticeElement> EdgeResult =
7745ffd83dbSDimitry Andric         getEdgeValue(PhiVal, PhiBB, BB, PN);
7755ffd83dbSDimitry Andric     if (!EdgeResult)
7760b57cec5SDimitry Andric       // Explore that input, then return here
777bdd1243dSDimitry Andric       return std::nullopt;
7780b57cec5SDimitry Andric 
7795ffd83dbSDimitry Andric     Result.mergeIn(*EdgeResult);
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric     // If we hit overdefined, exit early.  The BlockVals entry is already set
7820b57cec5SDimitry Andric     // to overdefined.
7830b57cec5SDimitry Andric     if (Result.isOverdefined()) {
7840b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
7850b57cec5SDimitry Andric                         << "' - overdefined because of pred (local).\n");
7860b57cec5SDimitry Andric 
7875ffd83dbSDimitry Andric       return Result;
7880b57cec5SDimitry Andric     }
7890b57cec5SDimitry Andric   }
7900b57cec5SDimitry Andric 
7910b57cec5SDimitry Andric   // Return the merged value, which is more precise than 'overdefined'.
7920b57cec5SDimitry Andric   assert(!Result.isOverdefined() && "Possible PHI in entry block?");
7935ffd83dbSDimitry Andric   return Result;
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric // If we can determine a constraint on the value given conditions assumed by
7970b57cec5SDimitry Andric // the program, intersect those constraints with BBLV
intersectAssumeOrGuardBlockValueConstantRange(Value * Val,ValueLatticeElement & BBLV,Instruction * BBI)7980b57cec5SDimitry Andric void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
7990b57cec5SDimitry Andric     Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
8000b57cec5SDimitry Andric   BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
8010b57cec5SDimitry Andric   if (!BBI)
8020b57cec5SDimitry Andric     return;
8030b57cec5SDimitry Andric 
8045ffd83dbSDimitry Andric   BasicBlock *BB = BBI->getParent();
8050b57cec5SDimitry Andric   for (auto &AssumeVH : AC->assumptionsFor(Val)) {
8060b57cec5SDimitry Andric     if (!AssumeVH)
8070b57cec5SDimitry Andric       continue;
8085ffd83dbSDimitry Andric 
8095ffd83dbSDimitry Andric     // Only check assumes in the block of the context instruction. Other
8105ffd83dbSDimitry Andric     // assumes will have already been taken into account when the value was
8115ffd83dbSDimitry Andric     // propagated from predecessor blocks.
8120b57cec5SDimitry Andric     auto *I = cast<CallInst>(AssumeVH);
8135ffd83dbSDimitry Andric     if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
8140b57cec5SDimitry Andric       continue;
8150b57cec5SDimitry Andric 
816647cbc5dSDimitry Andric     BBLV = intersect(BBLV, *getValueFromCondition(Val, I->getArgOperand(0),
817647cbc5dSDimitry Andric                                                   /*IsTrueDest*/ true,
818647cbc5dSDimitry Andric                                                   /*UseBlockValue*/ false));
8190b57cec5SDimitry Andric   }
8200b57cec5SDimitry Andric 
8210b57cec5SDimitry Andric   // If guards are not used in the module, don't spend time looking for them
822e8d8bef9SDimitry Andric   if (GuardDecl && !GuardDecl->use_empty() &&
823e8d8bef9SDimitry Andric       BBI->getIterator() != BB->begin()) {
824647cbc5dSDimitry Andric     for (Instruction &I :
825647cbc5dSDimitry Andric          make_range(std::next(BBI->getIterator().getReverse()), BB->rend())) {
8260b57cec5SDimitry Andric       Value *Cond = nullptr;
8270b57cec5SDimitry Andric       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
828647cbc5dSDimitry Andric         BBLV = intersect(BBLV,
829647cbc5dSDimitry Andric                          *getValueFromCondition(Val, Cond, /*IsTrueDest*/ true,
830647cbc5dSDimitry Andric                                                 /*UseBlockValue*/ false));
8310b57cec5SDimitry Andric     }
8320b57cec5SDimitry Andric   }
8330b57cec5SDimitry Andric 
834e8d8bef9SDimitry Andric   if (BBLV.isOverdefined()) {
835e8d8bef9SDimitry Andric     // Check whether we're checking at the terminator, and the pointer has
836e8d8bef9SDimitry Andric     // been dereferenced in this block.
837e8d8bef9SDimitry Andric     PointerType *PTy = dyn_cast<PointerType>(Val->getType());
838e8d8bef9SDimitry Andric     if (PTy && BB->getTerminator() == BBI &&
839e8d8bef9SDimitry Andric         isNonNullAtEndOfBlock(Val, BB))
840e8d8bef9SDimitry Andric       BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
841e8d8bef9SDimitry Andric   }
842e8d8bef9SDimitry Andric }
843e8d8bef9SDimitry Andric 
844bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueSelect(SelectInst * SI,BasicBlock * BB)845bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueSelect(SelectInst *SI, BasicBlock *BB) {
8460b57cec5SDimitry Andric   // Recurse on our inputs if needed
847bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptTrueVal =
84804eeddc0SDimitry Andric       getBlockValue(SI->getTrueValue(), BB, SI);
8495ffd83dbSDimitry Andric   if (!OptTrueVal)
850bdd1243dSDimitry Andric     return std::nullopt;
8515ffd83dbSDimitry Andric   ValueLatticeElement &TrueVal = *OptTrueVal;
8520b57cec5SDimitry Andric 
853bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptFalseVal =
85404eeddc0SDimitry Andric       getBlockValue(SI->getFalseValue(), BB, SI);
8555ffd83dbSDimitry Andric   if (!OptFalseVal)
856bdd1243dSDimitry Andric     return std::nullopt;
8575ffd83dbSDimitry Andric   ValueLatticeElement &FalseVal = *OptFalseVal;
8585ffd83dbSDimitry Andric 
85904eeddc0SDimitry Andric   if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
860*0fca6ea1SDimitry Andric     const ConstantRange &TrueCR = TrueVal.asConstantRange(SI->getType());
861*0fca6ea1SDimitry Andric     const ConstantRange &FalseCR = FalseVal.asConstantRange(SI->getType());
8620b57cec5SDimitry Andric     Value *LHS = nullptr;
8630b57cec5SDimitry Andric     Value *RHS = nullptr;
8640b57cec5SDimitry Andric     SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
8650b57cec5SDimitry Andric     // Is this a min specifically of our two inputs?  (Avoid the risk of
8660b57cec5SDimitry Andric     // ValueTracking getting smarter looking back past our immediate inputs.)
8670b57cec5SDimitry Andric     if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
86804eeddc0SDimitry Andric         ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
86904eeddc0SDimitry Andric          (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
8700b57cec5SDimitry Andric       ConstantRange ResultCR = [&]() {
8710b57cec5SDimitry Andric         switch (SPR.Flavor) {
8720b57cec5SDimitry Andric         default:
8730b57cec5SDimitry Andric           llvm_unreachable("unexpected minmax type!");
8740b57cec5SDimitry Andric         case SPF_SMIN:                   /// Signed minimum
8750b57cec5SDimitry Andric           return TrueCR.smin(FalseCR);
8760b57cec5SDimitry Andric         case SPF_UMIN:                   /// Unsigned minimum
8770b57cec5SDimitry Andric           return TrueCR.umin(FalseCR);
8780b57cec5SDimitry Andric         case SPF_SMAX:                   /// Signed maximum
8790b57cec5SDimitry Andric           return TrueCR.smax(FalseCR);
8800b57cec5SDimitry Andric         case SPF_UMAX:                   /// Unsigned maximum
8810b57cec5SDimitry Andric           return TrueCR.umax(FalseCR);
8820b57cec5SDimitry Andric         };
8830b57cec5SDimitry Andric       }();
8845ffd83dbSDimitry Andric       return ValueLatticeElement::getRange(
885349cc55cSDimitry Andric           ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
8865ffd83dbSDimitry Andric                         FalseVal.isConstantRangeIncludingUndef());
8870b57cec5SDimitry Andric     }
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric     if (SPR.Flavor == SPF_ABS) {
8905ffd83dbSDimitry Andric       if (LHS == SI->getTrueValue())
8915ffd83dbSDimitry Andric         return ValueLatticeElement::getRange(
8925ffd83dbSDimitry Andric             TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
8935ffd83dbSDimitry Andric       if (LHS == SI->getFalseValue())
8945ffd83dbSDimitry Andric         return ValueLatticeElement::getRange(
8955ffd83dbSDimitry Andric             FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
8960b57cec5SDimitry Andric     }
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric     if (SPR.Flavor == SPF_NABS) {
899349cc55cSDimitry Andric       ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
9005ffd83dbSDimitry Andric       if (LHS == SI->getTrueValue())
9015ffd83dbSDimitry Andric         return ValueLatticeElement::getRange(
9025ffd83dbSDimitry Andric             Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
9035ffd83dbSDimitry Andric       if (LHS == SI->getFalseValue())
9045ffd83dbSDimitry Andric         return ValueLatticeElement::getRange(
9055ffd83dbSDimitry Andric             Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
9060b57cec5SDimitry Andric     }
9070b57cec5SDimitry Andric   }
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric   // Can we constrain the facts about the true and false values by using the
9100b57cec5SDimitry Andric   // condition itself?  This shows up with idioms like e.g. select(a > 5, a, 5).
9110b57cec5SDimitry Andric   // TODO: We could potentially refine an overdefined true value above.
9120b57cec5SDimitry Andric   Value *Cond = SI->getCondition();
91306c3fb27SDimitry Andric   // If the value is undef, a different value may be chosen in
91406c3fb27SDimitry Andric   // the select condition.
9155f757f3fSDimitry Andric   if (isGuaranteedNotToBeUndef(Cond, AC)) {
916647cbc5dSDimitry Andric     TrueVal =
917647cbc5dSDimitry Andric         intersect(TrueVal, *getValueFromCondition(SI->getTrueValue(), Cond,
918647cbc5dSDimitry Andric                                                   /*IsTrueDest*/ true,
919647cbc5dSDimitry Andric                                                   /*UseBlockValue*/ false));
920647cbc5dSDimitry Andric     FalseVal =
921647cbc5dSDimitry Andric         intersect(FalseVal, *getValueFromCondition(SI->getFalseValue(), Cond,
922647cbc5dSDimitry Andric                                                    /*IsTrueDest*/ false,
923647cbc5dSDimitry Andric                                                    /*UseBlockValue*/ false));
92406c3fb27SDimitry Andric   }
9250b57cec5SDimitry Andric 
9265ffd83dbSDimitry Andric   ValueLatticeElement Result = TrueVal;
9275ffd83dbSDimitry Andric   Result.mergeIn(FalseVal);
9285ffd83dbSDimitry Andric   return Result;
9290b57cec5SDimitry Andric }
9300b57cec5SDimitry Andric 
931bdd1243dSDimitry Andric std::optional<ConstantRange>
getRangeFor(Value * V,Instruction * CxtI,BasicBlock * BB)932bdd1243dSDimitry Andric LazyValueInfoImpl::getRangeFor(Value *V, Instruction *CxtI, BasicBlock *BB) {
933bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
9345ffd83dbSDimitry Andric   if (!OptVal)
935bdd1243dSDimitry Andric     return std::nullopt;
936*0fca6ea1SDimitry Andric   return OptVal->asConstantRange(V->getType());
9370b57cec5SDimitry Andric }
9380b57cec5SDimitry Andric 
939bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueCast(CastInst * CI,BasicBlock * BB)940bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueCast(CastInst *CI, BasicBlock *BB) {
9410b57cec5SDimitry Andric   // Filter out casts we don't know how to reason about before attempting to
9420b57cec5SDimitry Andric   // recurse on our operand.  This can cut a long search short if we know we're
9430b57cec5SDimitry Andric   // not going to be able to get any useful information anways.
9440b57cec5SDimitry Andric   switch (CI->getOpcode()) {
9450b57cec5SDimitry Andric   case Instruction::Trunc:
9460b57cec5SDimitry Andric   case Instruction::SExt:
9470b57cec5SDimitry Andric   case Instruction::ZExt:
9480b57cec5SDimitry Andric     break;
9490b57cec5SDimitry Andric   default:
9500b57cec5SDimitry Andric     // Unhandled instructions are overdefined.
9510b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
9520b57cec5SDimitry Andric                       << "' - overdefined (unknown cast).\n");
9535ffd83dbSDimitry Andric     return ValueLatticeElement::getOverdefined();
9540b57cec5SDimitry Andric   }
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric   // Figure out the range of the LHS.  If that fails, we still apply the
9570b57cec5SDimitry Andric   // transfer rule on the full set since we may be able to locally infer
9580b57cec5SDimitry Andric   // interesting facts.
959bdd1243dSDimitry Andric   std::optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
96081ad6265SDimitry Andric   if (!LHSRes)
9610b57cec5SDimitry Andric     // More work to do before applying this transfer rule.
962bdd1243dSDimitry Andric     return std::nullopt;
963bdd1243dSDimitry Andric   const ConstantRange &LHSRange = *LHSRes;
9640b57cec5SDimitry Andric 
965*0fca6ea1SDimitry Andric   const unsigned ResultBitWidth = CI->getType()->getScalarSizeInBits();
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric   // NOTE: We're currently limited by the set of operations that ConstantRange
9680b57cec5SDimitry Andric   // can evaluate symbolically.  Enhancing that set will allows us to analyze
9690b57cec5SDimitry Andric   // more definitions.
9705ffd83dbSDimitry Andric   return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
9710b57cec5SDimitry Andric                                                        ResultBitWidth));
9720b57cec5SDimitry Andric }
9730b57cec5SDimitry Andric 
974bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueBinaryOpImpl(Instruction * I,BasicBlock * BB,std::function<ConstantRange (const ConstantRange &,const ConstantRange &)> OpFn)975bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
9765ffd83dbSDimitry Andric     Instruction *I, BasicBlock *BB,
977bdd1243dSDimitry Andric     std::function<ConstantRange(const ConstantRange &, const ConstantRange &)>
978bdd1243dSDimitry Andric         OpFn) {
9790b57cec5SDimitry Andric   // Figure out the ranges of the operands.  If that fails, use a
9800b57cec5SDimitry Andric   // conservative range, but apply the transfer rule anyways.  This
9810b57cec5SDimitry Andric   // lets us pick up facts from expressions like "and i32 (call i32
9820b57cec5SDimitry Andric   // @foo()), 32"
983bdd1243dSDimitry Andric   std::optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
984647cbc5dSDimitry Andric   if (!LHSRes)
985647cbc5dSDimitry Andric     return std::nullopt;
986647cbc5dSDimitry Andric 
987bdd1243dSDimitry Andric   std::optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
988647cbc5dSDimitry Andric   if (!RHSRes)
989bdd1243dSDimitry Andric     return std::nullopt;
9900b57cec5SDimitry Andric 
991bdd1243dSDimitry Andric   const ConstantRange &LHSRange = *LHSRes;
992bdd1243dSDimitry Andric   const ConstantRange &RHSRange = *RHSRes;
9935ffd83dbSDimitry Andric   return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
9940b57cec5SDimitry Andric }
9950b57cec5SDimitry Andric 
996bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueBinaryOp(BinaryOperator * BO,BasicBlock * BB)997bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueBinaryOp(BinaryOperator *BO, BasicBlock *BB) {
9980b57cec5SDimitry Andric   assert(BO->getOperand(0)->getType()->isSized() &&
9990b57cec5SDimitry Andric          "all operands to binary operators are sized");
1000480093f4SDimitry Andric   if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
1001*0fca6ea1SDimitry Andric     unsigned NoWrapKind = OBO->getNoWrapKind();
1002480093f4SDimitry Andric     return solveBlockValueBinaryOpImpl(
10035ffd83dbSDimitry Andric         BO, BB,
1004480093f4SDimitry Andric         [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
1005480093f4SDimitry Andric           return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
1006480093f4SDimitry Andric         });
1007480093f4SDimitry Andric   }
1008480093f4SDimitry Andric 
1009480093f4SDimitry Andric   return solveBlockValueBinaryOpImpl(
10105ffd83dbSDimitry Andric       BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
10110b57cec5SDimitry Andric         return CR1.binaryOp(BO->getOpcode(), CR2);
10120b57cec5SDimitry Andric       });
10130b57cec5SDimitry Andric }
10140b57cec5SDimitry Andric 
1015bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueOverflowIntrinsic(WithOverflowInst * WO,BasicBlock * BB)10165ffd83dbSDimitry Andric LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
10175ffd83dbSDimitry Andric                                                     BasicBlock *BB) {
10185ffd83dbSDimitry Andric   return solveBlockValueBinaryOpImpl(
10195ffd83dbSDimitry Andric       WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
10200b57cec5SDimitry Andric         return CR1.binaryOp(WO->getBinaryOp(), CR2);
10210b57cec5SDimitry Andric       });
10220b57cec5SDimitry Andric }
10230b57cec5SDimitry Andric 
1024bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueIntrinsic(IntrinsicInst * II,BasicBlock * BB)1025bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueIntrinsic(IntrinsicInst *II, BasicBlock *BB) {
102606c3fb27SDimitry Andric   ValueLatticeElement MetadataVal = getFromRangeMetadata(II);
1027e8d8bef9SDimitry Andric   if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
10280b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
1029fe6060f1SDimitry Andric                       << "' - unknown intrinsic.\n");
103006c3fb27SDimitry Andric     return MetadataVal;
10310b57cec5SDimitry Andric   }
10320b57cec5SDimitry Andric 
1033e8d8bef9SDimitry Andric   SmallVector<ConstantRange, 2> OpRanges;
1034e8d8bef9SDimitry Andric   for (Value *Op : II->args()) {
1035bdd1243dSDimitry Andric     std::optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1036e8d8bef9SDimitry Andric     if (!Range)
1037bdd1243dSDimitry Andric       return std::nullopt;
1038e8d8bef9SDimitry Andric     OpRanges.push_back(*Range);
1039e8d8bef9SDimitry Andric   }
1040e8d8bef9SDimitry Andric 
104106c3fb27SDimitry Andric   return intersect(ValueLatticeElement::getRange(ConstantRange::intrinsic(
104206c3fb27SDimitry Andric                        II->getIntrinsicID(), OpRanges)),
104306c3fb27SDimitry Andric                    MetadataVal);
1044e8d8bef9SDimitry Andric }
1045e8d8bef9SDimitry Andric 
1046bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueInsertElement(InsertElementInst * IEI,BasicBlock * BB)1047*0fca6ea1SDimitry Andric LazyValueInfoImpl::solveBlockValueInsertElement(InsertElementInst *IEI,
1048*0fca6ea1SDimitry Andric                                                 BasicBlock *BB) {
1049*0fca6ea1SDimitry Andric   std::optional<ValueLatticeElement> OptEltVal =
1050*0fca6ea1SDimitry Andric       getBlockValue(IEI->getOperand(1), BB, IEI);
1051*0fca6ea1SDimitry Andric   if (!OptEltVal)
1052*0fca6ea1SDimitry Andric     return std::nullopt;
1053*0fca6ea1SDimitry Andric   ValueLatticeElement &Res = *OptEltVal;
1054*0fca6ea1SDimitry Andric 
1055*0fca6ea1SDimitry Andric   std::optional<ValueLatticeElement> OptVecVal =
1056*0fca6ea1SDimitry Andric       getBlockValue(IEI->getOperand(0), BB, IEI);
1057*0fca6ea1SDimitry Andric   if (!OptVecVal)
1058*0fca6ea1SDimitry Andric     return std::nullopt;
1059*0fca6ea1SDimitry Andric 
1060*0fca6ea1SDimitry Andric   Res.mergeIn(*OptVecVal);
1061*0fca6ea1SDimitry Andric   return Res;
1062*0fca6ea1SDimitry Andric }
1063*0fca6ea1SDimitry Andric 
1064*0fca6ea1SDimitry Andric std::optional<ValueLatticeElement>
solveBlockValueExtractValue(ExtractValueInst * EVI,BasicBlock * BB)1065bdd1243dSDimitry Andric LazyValueInfoImpl::solveBlockValueExtractValue(ExtractValueInst *EVI,
1066bdd1243dSDimitry Andric                                                BasicBlock *BB) {
10678bcb0991SDimitry Andric   if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
10688bcb0991SDimitry Andric     if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
10695ffd83dbSDimitry Andric       return solveBlockValueOverflowIntrinsic(WO, BB);
10708bcb0991SDimitry Andric 
10718bcb0991SDimitry Andric   // Handle extractvalue of insertvalue to allow further simplification
10728bcb0991SDimitry Andric   // based on replaced with.overflow intrinsics.
107381ad6265SDimitry Andric   if (Value *V = simplifyExtractValueInst(
10748bcb0991SDimitry Andric           EVI->getAggregateOperand(), EVI->getIndices(),
1075*0fca6ea1SDimitry Andric           EVI->getDataLayout()))
107604eeddc0SDimitry Andric     return getBlockValue(V, BB, EVI);
10778bcb0991SDimitry Andric 
10788bcb0991SDimitry Andric   LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()
10798bcb0991SDimitry Andric                     << "' - overdefined (unknown extractvalue).\n");
10805ffd83dbSDimitry Andric   return ValueLatticeElement::getOverdefined();
10815ffd83dbSDimitry Andric }
10825ffd83dbSDimitry Andric 
matchICmpOperand(APInt & Offset,Value * LHS,Value * Val,ICmpInst::Predicate Pred)1083fe6060f1SDimitry Andric static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val,
10845ffd83dbSDimitry Andric                              ICmpInst::Predicate Pred) {
10855ffd83dbSDimitry Andric   if (LHS == Val)
10868bcb0991SDimitry Andric     return true;
10875ffd83dbSDimitry Andric 
10885ffd83dbSDimitry Andric   // Handle range checking idiom produced by InstCombine. We will subtract the
10895ffd83dbSDimitry Andric   // offset from the allowed range for RHS in this case.
1090fe6060f1SDimitry Andric   const APInt *C;
1091*0fca6ea1SDimitry Andric   if (match(LHS, m_AddLike(m_Specific(Val), m_APInt(C)))) {
1092fe6060f1SDimitry Andric     Offset = *C;
10935ffd83dbSDimitry Andric     return true;
1094fe6060f1SDimitry Andric   }
1095fe6060f1SDimitry Andric 
1096fe6060f1SDimitry Andric   // Handle the symmetric case. This appears in saturation patterns like
1097fe6060f1SDimitry Andric   // (x == 16) ? 16 : (x + 1).
1098*0fca6ea1SDimitry Andric   if (match(Val, m_AddLike(m_Specific(LHS), m_APInt(C)))) {
1099fe6060f1SDimitry Andric     Offset = -*C;
1100fe6060f1SDimitry Andric     return true;
1101fe6060f1SDimitry Andric   }
11025ffd83dbSDimitry Andric 
11035ffd83dbSDimitry Andric   // If (x | y) < C, then (x < C) && (y < C).
11045ffd83dbSDimitry Andric   if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
11055ffd83dbSDimitry Andric       (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
11065ffd83dbSDimitry Andric     return true;
11075ffd83dbSDimitry Andric 
11085ffd83dbSDimitry Andric   // If (x & y) > C, then (x > C) && (y > C).
11095ffd83dbSDimitry Andric   if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
11105ffd83dbSDimitry Andric       (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
11115ffd83dbSDimitry Andric     return true;
11125ffd83dbSDimitry Andric 
11135ffd83dbSDimitry Andric   return false;
11148bcb0991SDimitry Andric }
11158bcb0991SDimitry Andric 
1116e8d8bef9SDimitry Andric /// Get value range for a "(Val + Offset) Pred RHS" condition.
1117647cbc5dSDimitry Andric std::optional<ValueLatticeElement>
getValueFromSimpleICmpCondition(CmpInst::Predicate Pred,Value * RHS,const APInt & Offset,Instruction * CxtI,bool UseBlockValue)1118647cbc5dSDimitry Andric LazyValueInfoImpl::getValueFromSimpleICmpCondition(CmpInst::Predicate Pred,
1119647cbc5dSDimitry Andric                                                    Value *RHS,
1120647cbc5dSDimitry Andric                                                    const APInt &Offset,
1121647cbc5dSDimitry Andric                                                    Instruction *CxtI,
1122647cbc5dSDimitry Andric                                                    bool UseBlockValue) {
1123*0fca6ea1SDimitry Andric   ConstantRange RHSRange(RHS->getType()->getScalarSizeInBits(),
1124e8d8bef9SDimitry Andric                          /*isFullSet=*/true);
1125647cbc5dSDimitry Andric   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1126e8d8bef9SDimitry Andric     RHSRange = ConstantRange(CI->getValue());
1127647cbc5dSDimitry Andric   } else if (UseBlockValue) {
1128647cbc5dSDimitry Andric     std::optional<ValueLatticeElement> R =
1129647cbc5dSDimitry Andric         getBlockValue(RHS, CxtI->getParent(), CxtI);
1130647cbc5dSDimitry Andric     if (!R)
1131647cbc5dSDimitry Andric       return std::nullopt;
1132*0fca6ea1SDimitry Andric     RHSRange = R->asConstantRange(RHS->getType());
1133647cbc5dSDimitry Andric   }
1134e8d8bef9SDimitry Andric 
1135e8d8bef9SDimitry Andric   ConstantRange TrueValues =
1136e8d8bef9SDimitry Andric       ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1137fe6060f1SDimitry Andric   return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1138e8d8bef9SDimitry Andric }
1139e8d8bef9SDimitry Andric 
11405f757f3fSDimitry Andric static std::optional<ConstantRange>
getRangeViaSLT(CmpInst::Predicate Pred,APInt RHS,function_ref<std::optional<ConstantRange> (const APInt &)> Fn)11415f757f3fSDimitry Andric getRangeViaSLT(CmpInst::Predicate Pred, APInt RHS,
11425f757f3fSDimitry Andric                function_ref<std::optional<ConstantRange>(const APInt &)> Fn) {
11435f757f3fSDimitry Andric   bool Invert = false;
11445f757f3fSDimitry Andric   if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
11455f757f3fSDimitry Andric     Pred = ICmpInst::getInversePredicate(Pred);
11465f757f3fSDimitry Andric     Invert = true;
11475f757f3fSDimitry Andric   }
11485f757f3fSDimitry Andric   if (Pred == ICmpInst::ICMP_SLE) {
11495f757f3fSDimitry Andric     Pred = ICmpInst::ICMP_SLT;
11505f757f3fSDimitry Andric     if (RHS.isMaxSignedValue())
11515f757f3fSDimitry Andric       return std::nullopt; // Could also return full/empty here, if we wanted.
11525f757f3fSDimitry Andric     ++RHS;
11535f757f3fSDimitry Andric   }
11545f757f3fSDimitry Andric   assert(Pred == ICmpInst::ICMP_SLT && "Must be signed predicate");
11555f757f3fSDimitry Andric   if (auto CR = Fn(RHS))
11565f757f3fSDimitry Andric     return Invert ? CR->inverse() : CR;
11575f757f3fSDimitry Andric   return std::nullopt;
11585f757f3fSDimitry Andric }
11595f757f3fSDimitry Andric 
getValueFromICmpCondition(Value * Val,ICmpInst * ICI,bool isTrueDest,bool UseBlockValue)1160647cbc5dSDimitry Andric std::optional<ValueLatticeElement> LazyValueInfoImpl::getValueFromICmpCondition(
1161647cbc5dSDimitry Andric     Value *Val, ICmpInst *ICI, bool isTrueDest, bool UseBlockValue) {
11620b57cec5SDimitry Andric   Value *LHS = ICI->getOperand(0);
11630b57cec5SDimitry Andric   Value *RHS = ICI->getOperand(1);
11645ffd83dbSDimitry Andric 
11655ffd83dbSDimitry Andric   // Get the predicate that must hold along the considered edge.
11665ffd83dbSDimitry Andric   CmpInst::Predicate EdgePred =
11675ffd83dbSDimitry Andric       isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric   if (isa<Constant>(RHS)) {
11700b57cec5SDimitry Andric     if (ICI->isEquality() && LHS == Val) {
11715ffd83dbSDimitry Andric       if (EdgePred == ICmpInst::ICMP_EQ)
11720b57cec5SDimitry Andric         return ValueLatticeElement::get(cast<Constant>(RHS));
1173d65cd7a5SDimitry Andric       else if (!isa<UndefValue>(RHS))
11740b57cec5SDimitry Andric         return ValueLatticeElement::getNot(cast<Constant>(RHS));
11750b57cec5SDimitry Andric     }
11760b57cec5SDimitry Andric   }
11770b57cec5SDimitry Andric 
1178fe6060f1SDimitry Andric   Type *Ty = Val->getType();
1179fe6060f1SDimitry Andric   if (!Ty->isIntegerTy())
11800b57cec5SDimitry Andric     return ValueLatticeElement::getOverdefined();
11810b57cec5SDimitry Andric 
11824824e7fdSDimitry Andric   unsigned BitWidth = Ty->getScalarSizeInBits();
11834824e7fdSDimitry Andric   APInt Offset(BitWidth, 0);
1184e8d8bef9SDimitry Andric   if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1185647cbc5dSDimitry Andric     return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset, ICI,
1186647cbc5dSDimitry Andric                                            UseBlockValue);
1187e8d8bef9SDimitry Andric 
1188e8d8bef9SDimitry Andric   CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1189e8d8bef9SDimitry Andric   if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1190647cbc5dSDimitry Andric     return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset, ICI,
1191647cbc5dSDimitry Andric                                            UseBlockValue);
1192e8d8bef9SDimitry Andric 
1193e8d8bef9SDimitry Andric   const APInt *Mask, *C;
1194fe6060f1SDimitry Andric   if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1195e8d8bef9SDimitry Andric       match(RHS, m_APInt(C))) {
1196fe6060f1SDimitry Andric     // If (Val & Mask) == C then all the masked bits are known and we can
1197fe6060f1SDimitry Andric     // compute a value range based on that.
1198fe6060f1SDimitry Andric     if (EdgePred == ICmpInst::ICMP_EQ) {
1199e8d8bef9SDimitry Andric       KnownBits Known;
1200e8d8bef9SDimitry Andric       Known.Zero = ~*C & *Mask;
1201e8d8bef9SDimitry Andric       Known.One = *C & *Mask;
1202e8d8bef9SDimitry Andric       return ValueLatticeElement::getRange(
1203e8d8bef9SDimitry Andric           ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
12040b57cec5SDimitry Andric     }
1205*0fca6ea1SDimitry Andric 
1206*0fca6ea1SDimitry Andric     if (EdgePred == ICmpInst::ICMP_NE)
1207*0fca6ea1SDimitry Andric       return ValueLatticeElement::getRange(
1208*0fca6ea1SDimitry Andric           ConstantRange::makeMaskNotEqualRange(*Mask, *C));
1209fe6060f1SDimitry Andric   }
12100b57cec5SDimitry Andric 
12114824e7fdSDimitry Andric   // If (X urem Modulus) >= C, then X >= C.
121204eeddc0SDimitry Andric   // If trunc X >= C, then X >= C.
12134824e7fdSDimitry Andric   // TODO: An upper bound could be computed as well.
121404eeddc0SDimitry Andric   if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
121504eeddc0SDimitry Andric                              m_Trunc(m_Specific(Val)))) &&
12164824e7fdSDimitry Andric       match(RHS, m_APInt(C))) {
12174824e7fdSDimitry Andric     // Use the icmp region so we don't have to deal with different predicates.
12184824e7fdSDimitry Andric     ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
12194824e7fdSDimitry Andric     if (!CR.isEmptySet())
12204824e7fdSDimitry Andric       return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
122181ad6265SDimitry Andric           CR.getUnsignedMin().zext(BitWidth), APInt(BitWidth, 0)));
12224824e7fdSDimitry Andric   }
12234824e7fdSDimitry Andric 
12245f757f3fSDimitry Andric   // Recognize:
12255f757f3fSDimitry Andric   // icmp slt (ashr X, ShAmtC), C --> icmp slt X, C << ShAmtC
12265f757f3fSDimitry Andric   // Preconditions: (C << ShAmtC) >> ShAmtC == C
12275f757f3fSDimitry Andric   const APInt *ShAmtC;
12285f757f3fSDimitry Andric   if (CmpInst::isSigned(EdgePred) &&
12295f757f3fSDimitry Andric       match(LHS, m_AShr(m_Specific(Val), m_APInt(ShAmtC))) &&
12305f757f3fSDimitry Andric       match(RHS, m_APInt(C))) {
12315f757f3fSDimitry Andric     auto CR = getRangeViaSLT(
12325f757f3fSDimitry Andric         EdgePred, *C, [&](const APInt &RHS) -> std::optional<ConstantRange> {
12335f757f3fSDimitry Andric           APInt New = RHS << *ShAmtC;
12345f757f3fSDimitry Andric           if ((New.ashr(*ShAmtC)) != RHS)
12355f757f3fSDimitry Andric             return std::nullopt;
12365f757f3fSDimitry Andric           return ConstantRange::getNonEmpty(
12375f757f3fSDimitry Andric               APInt::getSignedMinValue(New.getBitWidth()), New);
12385f757f3fSDimitry Andric         });
12395f757f3fSDimitry Andric     if (CR)
12405f757f3fSDimitry Andric       return ValueLatticeElement::getRange(*CR);
12415f757f3fSDimitry Andric   }
12425f757f3fSDimitry Andric 
1243e8d8bef9SDimitry Andric   return ValueLatticeElement::getOverdefined();
12440b57cec5SDimitry Andric }
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric // Handle conditions of the form
12470b57cec5SDimitry Andric // extractvalue(op.with.overflow(%x, C), 1).
getValueFromOverflowCondition(Value * Val,WithOverflowInst * WO,bool IsTrueDest)12480b57cec5SDimitry Andric static ValueLatticeElement getValueFromOverflowCondition(
12490b57cec5SDimitry Andric     Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
12500b57cec5SDimitry Andric   // TODO: This only works with a constant RHS for now. We could also compute
12510b57cec5SDimitry Andric   // the range of the RHS, but this doesn't fit into the current structure of
12520b57cec5SDimitry Andric   // the edge value calculation.
12530b57cec5SDimitry Andric   const APInt *C;
12540b57cec5SDimitry Andric   if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
12550b57cec5SDimitry Andric     return ValueLatticeElement::getOverdefined();
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric   // Calculate the possible values of %x for which no overflow occurs.
12580b57cec5SDimitry Andric   ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
12590b57cec5SDimitry Andric       WO->getBinaryOp(), *C, WO->getNoWrapKind());
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric   // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
12620b57cec5SDimitry Andric   // constrained to it's inverse (all values that might cause overflow).
12630b57cec5SDimitry Andric   if (IsTrueDest)
12640b57cec5SDimitry Andric     NWR = NWR.inverse();
12650b57cec5SDimitry Andric   return ValueLatticeElement::getRange(NWR);
12660b57cec5SDimitry Andric }
12670b57cec5SDimitry Andric 
1268647cbc5dSDimitry Andric std::optional<ValueLatticeElement>
getValueFromCondition(Value * Val,Value * Cond,bool IsTrueDest,bool UseBlockValue,unsigned Depth)1269647cbc5dSDimitry Andric LazyValueInfoImpl::getValueFromCondition(Value *Val, Value *Cond,
1270647cbc5dSDimitry Andric                                          bool IsTrueDest, bool UseBlockValue,
1271647cbc5dSDimitry Andric                                          unsigned Depth) {
12720b57cec5SDimitry Andric   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1273647cbc5dSDimitry Andric     return getValueFromICmpCondition(Val, ICI, IsTrueDest, UseBlockValue);
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric   if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
12760b57cec5SDimitry Andric     if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
12770b57cec5SDimitry Andric       if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
12785f757f3fSDimitry Andric         return getValueFromOverflowCondition(Val, WO, IsTrueDest);
12795f757f3fSDimitry Andric 
12805f757f3fSDimitry Andric   if (++Depth == MaxAnalysisRecursionDepth)
12815f757f3fSDimitry Andric     return ValueLatticeElement::getOverdefined();
12820b57cec5SDimitry Andric 
1283bdd1243dSDimitry Andric   Value *N;
12845f757f3fSDimitry Andric   if (match(Cond, m_Not(m_Value(N))))
1285647cbc5dSDimitry Andric     return getValueFromCondition(Val, N, !IsTrueDest, UseBlockValue, Depth);
1286bdd1243dSDimitry Andric 
1287e8d8bef9SDimitry Andric   Value *L, *R;
1288e8d8bef9SDimitry Andric   bool IsAnd;
1289e8d8bef9SDimitry Andric   if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1290e8d8bef9SDimitry Andric     IsAnd = true;
1291e8d8bef9SDimitry Andric   else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1292e8d8bef9SDimitry Andric     IsAnd = false;
1293e8d8bef9SDimitry Andric   else
12940b57cec5SDimitry Andric     return ValueLatticeElement::getOverdefined();
12950b57cec5SDimitry Andric 
1296647cbc5dSDimitry Andric   std::optional<ValueLatticeElement> LV =
1297647cbc5dSDimitry Andric       getValueFromCondition(Val, L, IsTrueDest, UseBlockValue, Depth);
1298647cbc5dSDimitry Andric   if (!LV)
1299647cbc5dSDimitry Andric     return std::nullopt;
1300647cbc5dSDimitry Andric   std::optional<ValueLatticeElement> RV =
1301647cbc5dSDimitry Andric       getValueFromCondition(Val, R, IsTrueDest, UseBlockValue, Depth);
1302647cbc5dSDimitry Andric   if (!RV)
1303647cbc5dSDimitry Andric     return std::nullopt;
13040b57cec5SDimitry Andric 
1305e8d8bef9SDimitry Andric   // if (L && R) -> intersect L and R
1306bdd1243dSDimitry Andric   // if (!(L || R)) -> intersect !L and !R
1307e8d8bef9SDimitry Andric   // if (L || R) -> union L and R
1308bdd1243dSDimitry Andric   // if (!(L && R)) -> union !L and !R
13095f757f3fSDimitry Andric   if (IsTrueDest ^ IsAnd) {
1310647cbc5dSDimitry Andric     LV->mergeIn(*RV);
1311647cbc5dSDimitry Andric     return *LV;
13120b57cec5SDimitry Andric   }
13130b57cec5SDimitry Andric 
1314647cbc5dSDimitry Andric   return intersect(*LV, *RV);
13150b57cec5SDimitry Andric }
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric // Return true if Usr has Op as an operand, otherwise false.
usesOperand(User * Usr,Value * Op)13180b57cec5SDimitry Andric static bool usesOperand(User *Usr, Value *Op) {
1319e8d8bef9SDimitry Andric   return is_contained(Usr->operands(), Op);
13200b57cec5SDimitry Andric }
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric // Return true if the instruction type of Val is supported by
1323e8d8bef9SDimitry Andric // constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1324e8d8bef9SDimitry Andric // Call this before calling constantFoldUser() to find out if it's even worth
1325e8d8bef9SDimitry Andric // attempting to call it.
isOperationFoldable(User * Usr)13260b57cec5SDimitry Andric static bool isOperationFoldable(User *Usr) {
1327e8d8bef9SDimitry Andric   return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
13280b57cec5SDimitry Andric }
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric // Check if Usr can be simplified to an integer constant when the value of one
13310b57cec5SDimitry Andric // of its operands Op is an integer constant OpConstVal. If so, return it as an
13320b57cec5SDimitry Andric // lattice value range with a single element or otherwise return an overdefined
13330b57cec5SDimitry Andric // lattice value.
constantFoldUser(User * Usr,Value * Op,const APInt & OpConstVal,const DataLayout & DL)13340b57cec5SDimitry Andric static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
13350b57cec5SDimitry Andric                                             const APInt &OpConstVal,
13360b57cec5SDimitry Andric                                             const DataLayout &DL) {
13370b57cec5SDimitry Andric   assert(isOperationFoldable(Usr) && "Precondition");
13380b57cec5SDimitry Andric   Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
13390b57cec5SDimitry Andric   // Check if Usr can be simplified to a constant.
13400b57cec5SDimitry Andric   if (auto *CI = dyn_cast<CastInst>(Usr)) {
13410b57cec5SDimitry Andric     assert(CI->getOperand(0) == Op && "Operand 0 isn't Op");
13420b57cec5SDimitry Andric     if (auto *C = dyn_cast_or_null<ConstantInt>(
134381ad6265SDimitry Andric             simplifyCastInst(CI->getOpcode(), OpConst,
13440b57cec5SDimitry Andric                              CI->getDestTy(), DL))) {
13450b57cec5SDimitry Andric       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
13460b57cec5SDimitry Andric     }
13470b57cec5SDimitry Andric   } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
13480b57cec5SDimitry Andric     bool Op0Match = BO->getOperand(0) == Op;
13490b57cec5SDimitry Andric     bool Op1Match = BO->getOperand(1) == Op;
13500b57cec5SDimitry Andric     assert((Op0Match || Op1Match) &&
13510b57cec5SDimitry Andric            "Operand 0 nor Operand 1 isn't a match");
13520b57cec5SDimitry Andric     Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
13530b57cec5SDimitry Andric     Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
13540b57cec5SDimitry Andric     if (auto *C = dyn_cast_or_null<ConstantInt>(
135581ad6265SDimitry Andric             simplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
13560b57cec5SDimitry Andric       return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
13570b57cec5SDimitry Andric     }
1358e8d8bef9SDimitry Andric   } else if (isa<FreezeInst>(Usr)) {
1359e8d8bef9SDimitry Andric     assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op");
1360e8d8bef9SDimitry Andric     return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
13610b57cec5SDimitry Andric   }
13620b57cec5SDimitry Andric   return ValueLatticeElement::getOverdefined();
13630b57cec5SDimitry Andric }
13640b57cec5SDimitry Andric 
13655f757f3fSDimitry Andric /// Compute the value of Val on the edge BBFrom -> BBTo.
1366647cbc5dSDimitry Andric std::optional<ValueLatticeElement>
getEdgeValueLocal(Value * Val,BasicBlock * BBFrom,BasicBlock * BBTo,bool UseBlockValue)1367647cbc5dSDimitry Andric LazyValueInfoImpl::getEdgeValueLocal(Value *Val, BasicBlock *BBFrom,
1368647cbc5dSDimitry Andric                                      BasicBlock *BBTo, bool UseBlockValue) {
13690b57cec5SDimitry Andric   // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
13700b57cec5SDimitry Andric   // know that v != 0.
13710b57cec5SDimitry Andric   if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
13720b57cec5SDimitry Andric     // If this is a conditional branch and only one successor goes to BBTo, then
13730b57cec5SDimitry Andric     // we may be able to infer something from the condition.
13740b57cec5SDimitry Andric     if (BI->isConditional() &&
13750b57cec5SDimitry Andric         BI->getSuccessor(0) != BI->getSuccessor(1)) {
13760b57cec5SDimitry Andric       bool isTrueDest = BI->getSuccessor(0) == BBTo;
13770b57cec5SDimitry Andric       assert(BI->getSuccessor(!isTrueDest) == BBTo &&
13780b57cec5SDimitry Andric              "BBTo isn't a successor of BBFrom");
13790b57cec5SDimitry Andric       Value *Condition = BI->getCondition();
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric       // If V is the condition of the branch itself, then we know exactly what
13820b57cec5SDimitry Andric       // it is.
1383*0fca6ea1SDimitry Andric       // NB: The condition on a `br` can't be a vector type.
13845ffd83dbSDimitry Andric       if (Condition == Val)
13855ffd83dbSDimitry Andric         return ValueLatticeElement::get(ConstantInt::get(
13860b57cec5SDimitry Andric                               Type::getInt1Ty(Val->getContext()), isTrueDest));
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric       // If the condition of the branch is an equality comparison, we may be
13890b57cec5SDimitry Andric       // able to infer the value.
1390647cbc5dSDimitry Andric       std::optional<ValueLatticeElement> Result =
1391647cbc5dSDimitry Andric           getValueFromCondition(Val, Condition, isTrueDest, UseBlockValue);
1392647cbc5dSDimitry Andric       if (!Result)
1393647cbc5dSDimitry Andric         return std::nullopt;
1394647cbc5dSDimitry Andric 
1395647cbc5dSDimitry Andric       if (!Result->isOverdefined())
13965ffd83dbSDimitry Andric         return Result;
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric       if (User *Usr = dyn_cast<User>(Val)) {
1399647cbc5dSDimitry Andric         assert(Result->isOverdefined() && "Result isn't overdefined");
14000b57cec5SDimitry Andric         // Check with isOperationFoldable() first to avoid linearly iterating
14010b57cec5SDimitry Andric         // over the operands unnecessarily which can be expensive for
14020b57cec5SDimitry Andric         // instructions with many operands.
14030b57cec5SDimitry Andric         if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1404*0fca6ea1SDimitry Andric           const DataLayout &DL = BBTo->getDataLayout();
14050b57cec5SDimitry Andric           if (usesOperand(Usr, Condition)) {
14060b57cec5SDimitry Andric             // If Val has Condition as an operand and Val can be folded into a
14070b57cec5SDimitry Andric             // constant with either Condition == true or Condition == false,
14080b57cec5SDimitry Andric             // propagate the constant.
14090b57cec5SDimitry Andric             // eg.
14100b57cec5SDimitry Andric             //   ; %Val is true on the edge to %then.
14110b57cec5SDimitry Andric             //   %Val = and i1 %Condition, true.
14120b57cec5SDimitry Andric             //   br %Condition, label %then, label %else
14130b57cec5SDimitry Andric             APInt ConditionVal(1, isTrueDest ? 1 : 0);
14140b57cec5SDimitry Andric             Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
14150b57cec5SDimitry Andric           } else {
14160b57cec5SDimitry Andric             // If one of Val's operand has an inferred value, we may be able to
14170b57cec5SDimitry Andric             // infer the value of Val.
14180b57cec5SDimitry Andric             // eg.
14190b57cec5SDimitry Andric             //    ; %Val is 94 on the edge to %then.
14200b57cec5SDimitry Andric             //    %Val = add i8 %Op, 1
14210b57cec5SDimitry Andric             //    %Condition = icmp eq i8 %Op, 93
14220b57cec5SDimitry Andric             //    br i1 %Condition, label %then, label %else
14230b57cec5SDimitry Andric             for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
14240b57cec5SDimitry Andric               Value *Op = Usr->getOperand(i);
1425647cbc5dSDimitry Andric               ValueLatticeElement OpLatticeVal = *getValueFromCondition(
1426647cbc5dSDimitry Andric                   Op, Condition, isTrueDest, /*UseBlockValue*/ false);
1427bdd1243dSDimitry Andric               if (std::optional<APInt> OpConst =
1428bdd1243dSDimitry Andric                       OpLatticeVal.asConstantInteger()) {
142981ad6265SDimitry Andric                 Result = constantFoldUser(Usr, Op, *OpConst, DL);
14300b57cec5SDimitry Andric                 break;
14310b57cec5SDimitry Andric               }
14320b57cec5SDimitry Andric             }
14330b57cec5SDimitry Andric           }
14340b57cec5SDimitry Andric         }
14350b57cec5SDimitry Andric       }
1436647cbc5dSDimitry Andric       if (!Result->isOverdefined())
14375ffd83dbSDimitry Andric         return Result;
14380b57cec5SDimitry Andric     }
14390b57cec5SDimitry Andric   }
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   // If the edge was formed by a switch on the value, then we may know exactly
14420b57cec5SDimitry Andric   // what it is.
14430b57cec5SDimitry Andric   if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
14440b57cec5SDimitry Andric     Value *Condition = SI->getCondition();
14450b57cec5SDimitry Andric     if (!isa<IntegerType>(Val->getType()))
14465f757f3fSDimitry Andric       return ValueLatticeElement::getOverdefined();
14470b57cec5SDimitry Andric     bool ValUsesConditionAndMayBeFoldable = false;
14480b57cec5SDimitry Andric     if (Condition != Val) {
14490b57cec5SDimitry Andric       // Check if Val has Condition as an operand.
14500b57cec5SDimitry Andric       if (User *Usr = dyn_cast<User>(Val))
14510b57cec5SDimitry Andric         ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
14520b57cec5SDimitry Andric             usesOperand(Usr, Condition);
14530b57cec5SDimitry Andric       if (!ValUsesConditionAndMayBeFoldable)
14545f757f3fSDimitry Andric         return ValueLatticeElement::getOverdefined();
14550b57cec5SDimitry Andric     }
14560b57cec5SDimitry Andric     assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&
14570b57cec5SDimitry Andric            "Condition != Val nor Val doesn't use Condition");
14580b57cec5SDimitry Andric 
14590b57cec5SDimitry Andric     bool DefaultCase = SI->getDefaultDest() == BBTo;
14600b57cec5SDimitry Andric     unsigned BitWidth = Val->getType()->getIntegerBitWidth();
14610b57cec5SDimitry Andric     ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric     for (auto Case : SI->cases()) {
14640b57cec5SDimitry Andric       APInt CaseValue = Case.getCaseValue()->getValue();
14650b57cec5SDimitry Andric       ConstantRange EdgeVal(CaseValue);
14660b57cec5SDimitry Andric       if (ValUsesConditionAndMayBeFoldable) {
14670b57cec5SDimitry Andric         User *Usr = cast<User>(Val);
1468*0fca6ea1SDimitry Andric         const DataLayout &DL = BBTo->getDataLayout();
14690b57cec5SDimitry Andric         ValueLatticeElement EdgeLatticeVal =
14700b57cec5SDimitry Andric             constantFoldUser(Usr, Condition, CaseValue, DL);
14710b57cec5SDimitry Andric         if (EdgeLatticeVal.isOverdefined())
14725f757f3fSDimitry Andric           return ValueLatticeElement::getOverdefined();
14730b57cec5SDimitry Andric         EdgeVal = EdgeLatticeVal.getConstantRange();
14740b57cec5SDimitry Andric       }
14750b57cec5SDimitry Andric       if (DefaultCase) {
14760b57cec5SDimitry Andric         // It is possible that the default destination is the destination of
14770b57cec5SDimitry Andric         // some cases. We cannot perform difference for those cases.
14780b57cec5SDimitry Andric         // We know Condition != CaseValue in BBTo.  In some cases we can use
14790b57cec5SDimitry Andric         // this to infer Val == f(Condition) is != f(CaseValue).  For now, we
14800b57cec5SDimitry Andric         // only do this when f is identity (i.e. Val == Condition), but we
14810b57cec5SDimitry Andric         // should be able to do this for any injective f.
14820b57cec5SDimitry Andric         if (Case.getCaseSuccessor() != BBTo && Condition == Val)
14830b57cec5SDimitry Andric           EdgesVals = EdgesVals.difference(EdgeVal);
14840b57cec5SDimitry Andric       } else if (Case.getCaseSuccessor() == BBTo)
14850b57cec5SDimitry Andric         EdgesVals = EdgesVals.unionWith(EdgeVal);
14860b57cec5SDimitry Andric     }
14875ffd83dbSDimitry Andric     return ValueLatticeElement::getRange(std::move(EdgesVals));
14880b57cec5SDimitry Andric   }
14895f757f3fSDimitry Andric   return ValueLatticeElement::getOverdefined();
14900b57cec5SDimitry Andric }
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric /// Compute the value of Val on the edge BBFrom -> BBTo or the value at
14930b57cec5SDimitry Andric /// the basic block if the edge does not constrain Val.
1494bdd1243dSDimitry Andric std::optional<ValueLatticeElement>
getEdgeValue(Value * Val,BasicBlock * BBFrom,BasicBlock * BBTo,Instruction * CxtI)1495bdd1243dSDimitry Andric LazyValueInfoImpl::getEdgeValue(Value *Val, BasicBlock *BBFrom,
1496bdd1243dSDimitry Andric                                 BasicBlock *BBTo, Instruction *CxtI) {
14970b57cec5SDimitry Andric   // If already a constant, there is nothing to compute.
14985ffd83dbSDimitry Andric   if (Constant *VC = dyn_cast<Constant>(Val))
14995ffd83dbSDimitry Andric     return ValueLatticeElement::get(VC);
15000b57cec5SDimitry Andric 
1501647cbc5dSDimitry Andric   std::optional<ValueLatticeElement> LocalResult =
1502647cbc5dSDimitry Andric       getEdgeValueLocal(Val, BBFrom, BBTo, /*UseBlockValue*/ true);
1503647cbc5dSDimitry Andric   if (!LocalResult)
1504647cbc5dSDimitry Andric     return std::nullopt;
1505647cbc5dSDimitry Andric 
1506647cbc5dSDimitry Andric   if (hasSingleValue(*LocalResult))
15070b57cec5SDimitry Andric     // Can't get any more precise here
15085ffd83dbSDimitry Andric     return LocalResult;
15090b57cec5SDimitry Andric 
1510bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptInBlock =
151104eeddc0SDimitry Andric       getBlockValue(Val, BBFrom, BBFrom->getTerminator());
15125ffd83dbSDimitry Andric   if (!OptInBlock)
1513bdd1243dSDimitry Andric     return std::nullopt;
15145ffd83dbSDimitry Andric   ValueLatticeElement &InBlock = *OptInBlock;
15150b57cec5SDimitry Andric 
15160b57cec5SDimitry Andric   // We can use the context instruction (generically the ultimate instruction
15170b57cec5SDimitry Andric   // the calling pass is trying to simplify) here, even though the result of
15180b57cec5SDimitry Andric   // this function is generally cached when called from the solve* functions
15190b57cec5SDimitry Andric   // (and that cached result might be used with queries using a different
15200b57cec5SDimitry Andric   // context instruction), because when this function is called from the solve*
15210b57cec5SDimitry Andric   // functions, the context instruction is not provided. When called from
15220b57cec5SDimitry Andric   // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
15230b57cec5SDimitry Andric   // but then the result is not cached.
15240b57cec5SDimitry Andric   intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
15250b57cec5SDimitry Andric 
1526647cbc5dSDimitry Andric   return intersect(*LocalResult, InBlock);
15270b57cec5SDimitry Andric }
15280b57cec5SDimitry Andric 
getValueInBlock(Value * V,BasicBlock * BB,Instruction * CxtI)15290b57cec5SDimitry Andric ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
15300b57cec5SDimitry Andric                                                        Instruction *CxtI) {
15310b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"
15320b57cec5SDimitry Andric                     << BB->getName() << "'\n");
15330b57cec5SDimitry Andric 
15340b57cec5SDimitry Andric   assert(BlockValueStack.empty() && BlockValueSet.empty());
1535bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
15365ffd83dbSDimitry Andric   if (!OptResult) {
15370b57cec5SDimitry Andric     solve();
153804eeddc0SDimitry Andric     OptResult = getBlockValue(V, BB, CxtI);
15395ffd83dbSDimitry Andric     assert(OptResult && "Value not available after solving");
15400b57cec5SDimitry Andric   }
15410b57cec5SDimitry Andric 
154204eeddc0SDimitry Andric   ValueLatticeElement Result = *OptResult;
15430b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
15440b57cec5SDimitry Andric   return Result;
15450b57cec5SDimitry Andric }
15460b57cec5SDimitry Andric 
getValueAt(Value * V,Instruction * CxtI)15470b57cec5SDimitry Andric ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
15480b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()
15490b57cec5SDimitry Andric                     << "'\n");
15500b57cec5SDimitry Andric 
15510b57cec5SDimitry Andric   if (auto *C = dyn_cast<Constant>(V))
15520b57cec5SDimitry Andric     return ValueLatticeElement::get(C);
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric   ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
15550b57cec5SDimitry Andric   if (auto *I = dyn_cast<Instruction>(V))
15560b57cec5SDimitry Andric     Result = getFromRangeMetadata(I);
15570b57cec5SDimitry Andric   intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
15580b57cec5SDimitry Andric 
15590b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "  Result = " << Result << "\n");
15600b57cec5SDimitry Andric   return Result;
15610b57cec5SDimitry Andric }
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric ValueLatticeElement LazyValueInfoImpl::
getValueOnEdge(Value * V,BasicBlock * FromBB,BasicBlock * ToBB,Instruction * CxtI)15640b57cec5SDimitry Andric getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
15650b57cec5SDimitry Andric                Instruction *CxtI) {
15660b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"
15670b57cec5SDimitry Andric                     << FromBB->getName() << "' to '" << ToBB->getName()
15680b57cec5SDimitry Andric                     << "'\n");
15690b57cec5SDimitry Andric 
1570bdd1243dSDimitry Andric   std::optional<ValueLatticeElement> Result =
1571bdd1243dSDimitry Andric       getEdgeValue(V, FromBB, ToBB, CxtI);
1572647cbc5dSDimitry Andric   while (!Result) {
1573647cbc5dSDimitry Andric     // As the worklist only explicitly tracks block values (but not edge values)
1574647cbc5dSDimitry Andric     // we may have to call solve() multiple times, as the edge value calculation
1575647cbc5dSDimitry Andric     // may request additional block values.
15760b57cec5SDimitry Andric     solve();
15775ffd83dbSDimitry Andric     Result = getEdgeValue(V, FromBB, ToBB, CxtI);
15780b57cec5SDimitry Andric   }
15790b57cec5SDimitry Andric 
15805ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "  Result = " << *Result << "\n");
15815ffd83dbSDimitry Andric   return *Result;
15820b57cec5SDimitry Andric }
15830b57cec5SDimitry Andric 
getValueAtUse(const Use & U)15845f757f3fSDimitry Andric ValueLatticeElement LazyValueInfoImpl::getValueAtUse(const Use &U) {
15855f757f3fSDimitry Andric   Value *V = U.get();
15865f757f3fSDimitry Andric   auto *CxtI = cast<Instruction>(U.getUser());
15875f757f3fSDimitry Andric   ValueLatticeElement VL = getValueInBlock(V, CxtI->getParent(), CxtI);
15885f757f3fSDimitry Andric 
15895f757f3fSDimitry Andric   // Check whether the only (possibly transitive) use of the value is in a
15905f757f3fSDimitry Andric   // position where V can be constrained by a select or branch condition.
15915f757f3fSDimitry Andric   const Use *CurrU = &U;
15925f757f3fSDimitry Andric   // TODO: Increase limit?
15935f757f3fSDimitry Andric   const unsigned MaxUsesToInspect = 3;
15945f757f3fSDimitry Andric   for (unsigned I = 0; I < MaxUsesToInspect; ++I) {
15955f757f3fSDimitry Andric     std::optional<ValueLatticeElement> CondVal;
15965f757f3fSDimitry Andric     auto *CurrI = cast<Instruction>(CurrU->getUser());
15975f757f3fSDimitry Andric     if (auto *SI = dyn_cast<SelectInst>(CurrI)) {
15985f757f3fSDimitry Andric       // If the value is undef, a different value may be chosen in
15995f757f3fSDimitry Andric       // the select condition and at use.
16005f757f3fSDimitry Andric       if (!isGuaranteedNotToBeUndef(SI->getCondition(), AC))
16015f757f3fSDimitry Andric         break;
16025f757f3fSDimitry Andric       if (CurrU->getOperandNo() == 1)
1603647cbc5dSDimitry Andric         CondVal =
1604647cbc5dSDimitry Andric             *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ true,
1605647cbc5dSDimitry Andric                                    /*UseBlockValue*/ false);
16065f757f3fSDimitry Andric       else if (CurrU->getOperandNo() == 2)
1607647cbc5dSDimitry Andric         CondVal =
1608647cbc5dSDimitry Andric             *getValueFromCondition(V, SI->getCondition(), /*IsTrueDest*/ false,
1609647cbc5dSDimitry Andric                                    /*UseBlockValue*/ false);
16105f757f3fSDimitry Andric     } else if (auto *PHI = dyn_cast<PHINode>(CurrI)) {
16115f757f3fSDimitry Andric       // TODO: Use non-local query?
1612647cbc5dSDimitry Andric       CondVal = *getEdgeValueLocal(V, PHI->getIncomingBlock(*CurrU),
1613647cbc5dSDimitry Andric                                    PHI->getParent(), /*UseBlockValue*/ false);
16145f757f3fSDimitry Andric     }
16155f757f3fSDimitry Andric     if (CondVal)
16165f757f3fSDimitry Andric       VL = intersect(VL, *CondVal);
16175f757f3fSDimitry Andric 
16185f757f3fSDimitry Andric     // Only follow one-use chain, to allow direct intersection of conditions.
16195f757f3fSDimitry Andric     // If there are multiple uses, we would have to intersect with the union of
16205f757f3fSDimitry Andric     // all conditions at different uses.
16215f757f3fSDimitry Andric     // Stop walking if we hit a non-speculatable instruction. Even if the
16225f757f3fSDimitry Andric     // result is only used under a specific condition, executing the
16235f757f3fSDimitry Andric     // instruction itself may cause side effects or UB already.
16245f757f3fSDimitry Andric     // This also disallows looking through phi nodes: If the phi node is part
16255f757f3fSDimitry Andric     // of a cycle, we might end up reasoning about values from different cycle
16265f757f3fSDimitry Andric     // iterations (PR60629).
16275f757f3fSDimitry Andric     if (!CurrI->hasOneUse() || !isSafeToSpeculativelyExecute(CurrI))
16285f757f3fSDimitry Andric       break;
16295f757f3fSDimitry Andric     CurrU = &*CurrI->use_begin();
16305f757f3fSDimitry Andric   }
16315f757f3fSDimitry Andric   return VL;
16325f757f3fSDimitry Andric }
16335f757f3fSDimitry Andric 
threadEdge(BasicBlock * PredBB,BasicBlock * OldSucc,BasicBlock * NewSucc)16340b57cec5SDimitry Andric void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
16350b57cec5SDimitry Andric                                    BasicBlock *NewSucc) {
16360b57cec5SDimitry Andric   TheCache.threadEdgeImpl(OldSucc, NewSucc);
16370b57cec5SDimitry Andric }
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
16400b57cec5SDimitry Andric //                            LazyValueInfo Impl
16410b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
16420b57cec5SDimitry Andric 
runOnFunction(Function & F)16430b57cec5SDimitry Andric bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
16440b57cec5SDimitry Andric   Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
16450b57cec5SDimitry Andric 
16465f757f3fSDimitry Andric   if (auto *Impl = Info.getImpl())
16475f757f3fSDimitry Andric     Impl->clear();
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric   // Fully lazy.
16500b57cec5SDimitry Andric   return false;
16510b57cec5SDimitry Andric }
16520b57cec5SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const16530b57cec5SDimitry Andric void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
16540b57cec5SDimitry Andric   AU.setPreservesAll();
16550b57cec5SDimitry Andric   AU.addRequired<AssumptionCacheTracker>();
16560b57cec5SDimitry Andric   AU.addRequired<TargetLibraryInfoWrapperPass>();
16570b57cec5SDimitry Andric }
16580b57cec5SDimitry Andric 
getLVI()16590b57cec5SDimitry Andric LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
16600b57cec5SDimitry Andric 
16615f757f3fSDimitry Andric /// This lazily constructs the LazyValueInfoImpl.
getOrCreateImpl(const Module * M)16625f757f3fSDimitry Andric LazyValueInfoImpl &LazyValueInfo::getOrCreateImpl(const Module *M) {
16635f757f3fSDimitry Andric   if (!PImpl) {
16645f757f3fSDimitry Andric     assert(M && "getCache() called with a null Module");
16655f757f3fSDimitry Andric     const DataLayout &DL = M->getDataLayout();
16665f757f3fSDimitry Andric     Function *GuardDecl =
16675f757f3fSDimitry Andric         M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
16685f757f3fSDimitry Andric     PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
16695f757f3fSDimitry Andric   }
16705f757f3fSDimitry Andric   return *static_cast<LazyValueInfoImpl *>(PImpl);
16715f757f3fSDimitry Andric }
16725f757f3fSDimitry Andric 
getImpl()16735f757f3fSDimitry Andric LazyValueInfoImpl *LazyValueInfo::getImpl() {
16745f757f3fSDimitry Andric   if (!PImpl)
16755f757f3fSDimitry Andric     return nullptr;
16765f757f3fSDimitry Andric   return static_cast<LazyValueInfoImpl *>(PImpl);
16775f757f3fSDimitry Andric }
16785f757f3fSDimitry Andric 
~LazyValueInfo()16790b57cec5SDimitry Andric LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
16800b57cec5SDimitry Andric 
releaseMemory()16810b57cec5SDimitry Andric void LazyValueInfo::releaseMemory() {
16820b57cec5SDimitry Andric   // If the cache was allocated, free it.
16835f757f3fSDimitry Andric   if (auto *Impl = getImpl()) {
16845f757f3fSDimitry Andric     delete &*Impl;
16850b57cec5SDimitry Andric     PImpl = nullptr;
16860b57cec5SDimitry Andric   }
16870b57cec5SDimitry Andric }
16880b57cec5SDimitry Andric 
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)16890b57cec5SDimitry Andric bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
16900b57cec5SDimitry Andric                                FunctionAnalysisManager::Invalidator &Inv) {
16910b57cec5SDimitry Andric   // We need to invalidate if we have either failed to preserve this analyses
16920b57cec5SDimitry Andric   // result directly or if any of its dependencies have been invalidated.
16930b57cec5SDimitry Andric   auto PAC = PA.getChecker<LazyValueAnalysis>();
16945ffd83dbSDimitry Andric   if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
16950b57cec5SDimitry Andric     return true;
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   return false;
16980b57cec5SDimitry Andric }
16990b57cec5SDimitry Andric 
releaseMemory()17000b57cec5SDimitry Andric void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
17010b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)17020b57cec5SDimitry Andric LazyValueInfo LazyValueAnalysis::run(Function &F,
17030b57cec5SDimitry Andric                                      FunctionAnalysisManager &FAM) {
17040b57cec5SDimitry Andric   auto &AC = FAM.getResult<AssumptionAnalysis>(F);
17050b57cec5SDimitry Andric 
1706*0fca6ea1SDimitry Andric   return LazyValueInfo(&AC, &F.getDataLayout());
17070b57cec5SDimitry Andric }
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric /// Returns true if we can statically tell that this value will never be a
17100b57cec5SDimitry Andric /// "useful" constant.  In practice, this means we've got something like an
17110b57cec5SDimitry Andric /// alloca or a malloc call for which a comparison against a constant can
17120b57cec5SDimitry Andric /// only be guarding dead code.  Note that we are potentially giving up some
17130b57cec5SDimitry Andric /// precision in dead code (a constant result) in favour of avoiding a
17140b57cec5SDimitry Andric /// expensive search for a easily answered common query.
isKnownNonConstant(Value * V)17150b57cec5SDimitry Andric static bool isKnownNonConstant(Value *V) {
17160b57cec5SDimitry Andric   V = V->stripPointerCasts();
17170b57cec5SDimitry Andric   // The return val of alloc cannot be a Constant.
17180b57cec5SDimitry Andric   if (isa<AllocaInst>(V))
17190b57cec5SDimitry Andric     return true;
17200b57cec5SDimitry Andric   return false;
17210b57cec5SDimitry Andric }
17220b57cec5SDimitry Andric 
getConstant(Value * V,Instruction * CxtI)1723e8d8bef9SDimitry Andric Constant *LazyValueInfo::getConstant(Value *V, Instruction *CxtI) {
17240b57cec5SDimitry Andric   // Bail out early if V is known not to be a Constant.
17250b57cec5SDimitry Andric   if (isKnownNonConstant(V))
17260b57cec5SDimitry Andric     return nullptr;
17270b57cec5SDimitry Andric 
1728e8d8bef9SDimitry Andric   BasicBlock *BB = CxtI->getParent();
17290b57cec5SDimitry Andric   ValueLatticeElement Result =
17305f757f3fSDimitry Andric       getOrCreateImpl(BB->getModule()).getValueInBlock(V, BB, CxtI);
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   if (Result.isConstant())
17330b57cec5SDimitry Andric     return Result.getConstant();
17340b57cec5SDimitry Andric   if (Result.isConstantRange()) {
17350b57cec5SDimitry Andric     const ConstantRange &CR = Result.getConstantRange();
17360b57cec5SDimitry Andric     if (const APInt *SingleVal = CR.getSingleElement())
1737*0fca6ea1SDimitry Andric       return ConstantInt::get(V->getType(), *SingleVal);
17380b57cec5SDimitry Andric   }
17390b57cec5SDimitry Andric   return nullptr;
17400b57cec5SDimitry Andric }
17410b57cec5SDimitry Andric 
getConstantRange(Value * V,Instruction * CxtI,bool UndefAllowed)1742e8d8bef9SDimitry Andric ConstantRange LazyValueInfo::getConstantRange(Value *V, Instruction *CxtI,
17435ffd83dbSDimitry Andric                                               bool UndefAllowed) {
1744e8d8bef9SDimitry Andric   BasicBlock *BB = CxtI->getParent();
17450b57cec5SDimitry Andric   ValueLatticeElement Result =
17465f757f3fSDimitry Andric       getOrCreateImpl(BB->getModule()).getValueInBlock(V, BB, CxtI);
1747*0fca6ea1SDimitry Andric   return Result.asConstantRange(V->getType(), UndefAllowed);
17480b57cec5SDimitry Andric }
17490b57cec5SDimitry Andric 
getConstantRangeAtUse(const Use & U,bool UndefAllowed)1750bdd1243dSDimitry Andric ConstantRange LazyValueInfo::getConstantRangeAtUse(const Use &U,
1751bdd1243dSDimitry Andric                                                    bool UndefAllowed) {
17525f757f3fSDimitry Andric   auto *Inst = cast<Instruction>(U.getUser());
17535f757f3fSDimitry Andric   ValueLatticeElement Result =
17545f757f3fSDimitry Andric       getOrCreateImpl(Inst->getModule()).getValueAtUse(U);
1755*0fca6ea1SDimitry Andric   return Result.asConstantRange(U->getType(), UndefAllowed);
1756bdd1243dSDimitry Andric }
1757bdd1243dSDimitry Andric 
17580b57cec5SDimitry Andric /// Determine whether the specified value is known to be a
17590b57cec5SDimitry Andric /// constant on the specified edge. Return null if not.
getConstantOnEdge(Value * V,BasicBlock * FromBB,BasicBlock * ToBB,Instruction * CxtI)17600b57cec5SDimitry Andric Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
17610b57cec5SDimitry Andric                                            BasicBlock *ToBB,
17620b57cec5SDimitry Andric                                            Instruction *CxtI) {
17635ffd83dbSDimitry Andric   Module *M = FromBB->getModule();
17640b57cec5SDimitry Andric   ValueLatticeElement Result =
17655f757f3fSDimitry Andric       getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric   if (Result.isConstant())
17680b57cec5SDimitry Andric     return Result.getConstant();
17690b57cec5SDimitry Andric   if (Result.isConstantRange()) {
17700b57cec5SDimitry Andric     const ConstantRange &CR = Result.getConstantRange();
17710b57cec5SDimitry Andric     if (const APInt *SingleVal = CR.getSingleElement())
1772*0fca6ea1SDimitry Andric       return ConstantInt::get(V->getType(), *SingleVal);
17730b57cec5SDimitry Andric   }
17740b57cec5SDimitry Andric   return nullptr;
17750b57cec5SDimitry Andric }
17760b57cec5SDimitry Andric 
getConstantRangeOnEdge(Value * V,BasicBlock * FromBB,BasicBlock * ToBB,Instruction * CxtI)17770b57cec5SDimitry Andric ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
17780b57cec5SDimitry Andric                                                     BasicBlock *FromBB,
17790b57cec5SDimitry Andric                                                     BasicBlock *ToBB,
17800b57cec5SDimitry Andric                                                     Instruction *CxtI) {
17815ffd83dbSDimitry Andric   Module *M = FromBB->getModule();
17820b57cec5SDimitry Andric   ValueLatticeElement Result =
17835f757f3fSDimitry Andric       getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
17845f757f3fSDimitry Andric   // TODO: Should undef be allowed here?
1785*0fca6ea1SDimitry Andric   return Result.asConstantRange(V->getType(), /*UndefAllowed*/ true);
17860b57cec5SDimitry Andric }
17870b57cec5SDimitry Andric 
getPredicateResult(CmpInst::Predicate Pred,Constant * C,const ValueLatticeElement & Val,const DataLayout & DL)1788*0fca6ea1SDimitry Andric static Constant *getPredicateResult(CmpInst::Predicate Pred, Constant *C,
1789*0fca6ea1SDimitry Andric                                     const ValueLatticeElement &Val,
1790cb14a3feSDimitry Andric                                     const DataLayout &DL) {
17910b57cec5SDimitry Andric   // If we know the value is a constant, evaluate the conditional.
1792*0fca6ea1SDimitry Andric   if (Val.isConstant())
1793*0fca6ea1SDimitry Andric     return ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL);
17940b57cec5SDimitry Andric 
1795*0fca6ea1SDimitry Andric   Type *ResTy = CmpInst::makeCmpResultType(C->getType());
17960b57cec5SDimitry Andric   if (Val.isConstantRange()) {
17970b57cec5SDimitry Andric     const ConstantRange &CR = Val.getConstantRange();
1798*0fca6ea1SDimitry Andric     ConstantRange RHS = C->toConstantRange();
1799*0fca6ea1SDimitry Andric     if (CR.icmp(Pred, RHS))
1800*0fca6ea1SDimitry Andric       return ConstantInt::getTrue(ResTy);
1801*0fca6ea1SDimitry Andric     if (CR.icmp(CmpInst::getInversePredicate(Pred), RHS))
1802*0fca6ea1SDimitry Andric       return ConstantInt::getFalse(ResTy);
1803*0fca6ea1SDimitry Andric     return nullptr;
18040b57cec5SDimitry Andric   }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric   if (Val.isNotConstant()) {
18070b57cec5SDimitry Andric     // If this is an equality comparison, we can try to fold it knowing that
18080b57cec5SDimitry Andric     // "V != C1".
18090b57cec5SDimitry Andric     if (Pred == ICmpInst::ICMP_EQ) {
18100b57cec5SDimitry Andric       // !C1 == C -> false iff C1 == C.
1811*0fca6ea1SDimitry Andric       Constant *Res = ConstantFoldCompareInstOperands(
1812*0fca6ea1SDimitry Andric           ICmpInst::ICMP_NE, Val.getNotConstant(), C, DL);
181306c3fb27SDimitry Andric       if (Res && Res->isNullValue())
1814*0fca6ea1SDimitry Andric         return ConstantInt::getFalse(ResTy);
18150b57cec5SDimitry Andric     } else if (Pred == ICmpInst::ICMP_NE) {
18160b57cec5SDimitry Andric       // !C1 != C -> true iff C1 == C.
1817*0fca6ea1SDimitry Andric       Constant *Res = ConstantFoldCompareInstOperands(
1818*0fca6ea1SDimitry Andric           ICmpInst::ICMP_NE, Val.getNotConstant(), C, DL);
181906c3fb27SDimitry Andric       if (Res && Res->isNullValue())
1820*0fca6ea1SDimitry Andric         return ConstantInt::getTrue(ResTy);
18210b57cec5SDimitry Andric     }
1822*0fca6ea1SDimitry Andric     return nullptr;
18230b57cec5SDimitry Andric   }
18240b57cec5SDimitry Andric 
1825*0fca6ea1SDimitry Andric   return nullptr;
18260b57cec5SDimitry Andric }
18270b57cec5SDimitry Andric 
18280b57cec5SDimitry Andric /// Determine whether the specified value comparison with a constant is known to
18290b57cec5SDimitry Andric /// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
getPredicateOnEdge(CmpInst::Predicate Pred,Value * V,Constant * C,BasicBlock * FromBB,BasicBlock * ToBB,Instruction * CxtI)1830*0fca6ea1SDimitry Andric Constant *LazyValueInfo::getPredicateOnEdge(CmpInst::Predicate Pred, Value *V,
1831*0fca6ea1SDimitry Andric                                             Constant *C, BasicBlock *FromBB,
1832*0fca6ea1SDimitry Andric                                             BasicBlock *ToBB,
18330b57cec5SDimitry Andric                                             Instruction *CxtI) {
18345ffd83dbSDimitry Andric   Module *M = FromBB->getModule();
18350b57cec5SDimitry Andric   ValueLatticeElement Result =
18365f757f3fSDimitry Andric       getOrCreateImpl(M).getValueOnEdge(V, FromBB, ToBB, CxtI);
18370b57cec5SDimitry Andric 
1838cb14a3feSDimitry Andric   return getPredicateResult(Pred, C, Result, M->getDataLayout());
18390b57cec5SDimitry Andric }
18400b57cec5SDimitry Andric 
getPredicateAt(CmpInst::Predicate Pred,Value * V,Constant * C,Instruction * CxtI,bool UseBlockValue)1841*0fca6ea1SDimitry Andric Constant *LazyValueInfo::getPredicateAt(CmpInst::Predicate Pred, Value *V,
1842*0fca6ea1SDimitry Andric                                         Constant *C, Instruction *CxtI,
1843*0fca6ea1SDimitry Andric                                         bool UseBlockValue) {
18440b57cec5SDimitry Andric   // Is or is not NonNull are common predicates being queried. If
18450b57cec5SDimitry Andric   // isKnownNonZero can tell us the result of the predicate, we can
18460b57cec5SDimitry Andric   // return it quickly. But this is only a fastpath, and falling
18470b57cec5SDimitry Andric   // through would still be correct.
18485ffd83dbSDimitry Andric   Module *M = CxtI->getModule();
18495ffd83dbSDimitry Andric   const DataLayout &DL = M->getDataLayout();
18500b57cec5SDimitry Andric   if (V->getType()->isPointerTy() && C->isNullValue() &&
18510b57cec5SDimitry Andric       isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1852*0fca6ea1SDimitry Andric     Type *ResTy = CmpInst::makeCmpResultType(C->getType());
18530b57cec5SDimitry Andric     if (Pred == ICmpInst::ICMP_EQ)
1854*0fca6ea1SDimitry Andric       return ConstantInt::getFalse(ResTy);
18550b57cec5SDimitry Andric     else if (Pred == ICmpInst::ICMP_NE)
1856*0fca6ea1SDimitry Andric       return ConstantInt::getTrue(ResTy);
18570b57cec5SDimitry Andric   }
1858e8d8bef9SDimitry Andric 
18595f757f3fSDimitry Andric   auto &Impl = getOrCreateImpl(M);
18605f757f3fSDimitry Andric   ValueLatticeElement Result =
18615f757f3fSDimitry Andric       UseBlockValue ? Impl.getValueInBlock(V, CxtI->getParent(), CxtI)
18625f757f3fSDimitry Andric                     : Impl.getValueAt(V, CxtI);
1863*0fca6ea1SDimitry Andric   Constant *Ret = getPredicateResult(Pred, C, Result, DL);
1864*0fca6ea1SDimitry Andric   if (Ret)
18650b57cec5SDimitry Andric     return Ret;
18660b57cec5SDimitry Andric 
18670b57cec5SDimitry Andric   // Note: The following bit of code is somewhat distinct from the rest of LVI;
18680b57cec5SDimitry Andric   // LVI as a whole tries to compute a lattice value which is conservatively
18690b57cec5SDimitry Andric   // correct at a given location.  In this case, we have a predicate which we
18700b57cec5SDimitry Andric   // weren't able to prove about the merged result, and we're pushing that
18710b57cec5SDimitry Andric   // predicate back along each incoming edge to see if we can prove it
18720b57cec5SDimitry Andric   // separately for each input.  As a motivating example, consider:
18730b57cec5SDimitry Andric   // bb1:
18740b57cec5SDimitry Andric   //   %v1 = ... ; constantrange<1, 5>
18750b57cec5SDimitry Andric   //   br label %merge
18760b57cec5SDimitry Andric   // bb2:
18770b57cec5SDimitry Andric   //   %v2 = ... ; constantrange<10, 20>
18780b57cec5SDimitry Andric   //   br label %merge
18790b57cec5SDimitry Andric   // merge:
18800b57cec5SDimitry Andric   //   %phi = phi [%v1, %v2] ; constantrange<1,20>
18810b57cec5SDimitry Andric   //   %pred = icmp eq i32 %phi, 8
18820b57cec5SDimitry Andric   // We can't tell from the lattice value for '%phi' that '%pred' is false
18830b57cec5SDimitry Andric   // along each path, but by checking the predicate over each input separately,
18840b57cec5SDimitry Andric   // we can.
18850b57cec5SDimitry Andric   // We limit the search to one step backwards from the current BB and value.
18860b57cec5SDimitry Andric   // We could consider extending this to search further backwards through the
18870b57cec5SDimitry Andric   // CFG and/or value graph, but there are non-obvious compile time vs quality
18880b57cec5SDimitry Andric   // tradeoffs.
18890b57cec5SDimitry Andric   BasicBlock *BB = CxtI->getParent();
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric   // Function entry or an unreachable block.  Bail to avoid confusing
18920b57cec5SDimitry Andric   // analysis below.
18930b57cec5SDimitry Andric   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
18940b57cec5SDimitry Andric   if (PI == PE)
1895*0fca6ea1SDimitry Andric     return nullptr;
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric   // If V is a PHI node in the same block as the context, we need to ask
18980b57cec5SDimitry Andric   // questions about the predicate as applied to the incoming value along
18990b57cec5SDimitry Andric   // each edge. This is useful for eliminating cases where the predicate is
19000b57cec5SDimitry Andric   // known along all incoming edges.
19010b57cec5SDimitry Andric   if (auto *PHI = dyn_cast<PHINode>(V))
19020b57cec5SDimitry Andric     if (PHI->getParent() == BB) {
1903*0fca6ea1SDimitry Andric       Constant *Baseline = nullptr;
19040b57cec5SDimitry Andric       for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
19050b57cec5SDimitry Andric         Value *Incoming = PHI->getIncomingValue(i);
19060b57cec5SDimitry Andric         BasicBlock *PredBB = PHI->getIncomingBlock(i);
19070b57cec5SDimitry Andric         // Note that PredBB may be BB itself.
1908*0fca6ea1SDimitry Andric         Constant *Result =
1909349cc55cSDimitry Andric             getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric         // Keep going as long as we've seen a consistent known result for
19120b57cec5SDimitry Andric         // all inputs.
19130b57cec5SDimitry Andric         Baseline = (i == 0) ? Result /* First iteration */
1914349cc55cSDimitry Andric                             : (Baseline == Result ? Baseline
1915*0fca6ea1SDimitry Andric                                                   : nullptr); /* All others */
1916*0fca6ea1SDimitry Andric         if (!Baseline)
19170b57cec5SDimitry Andric           break;
19180b57cec5SDimitry Andric       }
1919*0fca6ea1SDimitry Andric       if (Baseline)
19200b57cec5SDimitry Andric         return Baseline;
19210b57cec5SDimitry Andric     }
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric   // For a comparison where the V is outside this block, it's possible
19240b57cec5SDimitry Andric   // that we've branched on it before. Look to see if the value is known
19250b57cec5SDimitry Andric   // on all incoming edges.
1926349cc55cSDimitry Andric   if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
19270b57cec5SDimitry Andric     // For predecessor edge, determine if the comparison is true or false
19280b57cec5SDimitry Andric     // on that edge. If they're all true or all false, we can conclude
19290b57cec5SDimitry Andric     // the value of the comparison in this block.
1930*0fca6ea1SDimitry Andric     Constant *Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1931*0fca6ea1SDimitry Andric     if (Baseline) {
19320b57cec5SDimitry Andric       // Check that all remaining incoming values match the first one.
19330b57cec5SDimitry Andric       while (++PI != PE) {
1934*0fca6ea1SDimitry Andric         Constant *Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1935349cc55cSDimitry Andric         if (Ret != Baseline)
1936349cc55cSDimitry Andric           break;
19370b57cec5SDimitry Andric       }
19380b57cec5SDimitry Andric       // If we terminated early, then one of the values didn't match.
19390b57cec5SDimitry Andric       if (PI == PE) {
19400b57cec5SDimitry Andric         return Baseline;
19410b57cec5SDimitry Andric       }
19420b57cec5SDimitry Andric     }
19430b57cec5SDimitry Andric   }
1944349cc55cSDimitry Andric 
1945*0fca6ea1SDimitry Andric   return nullptr;
19460b57cec5SDimitry Andric }
19470b57cec5SDimitry Andric 
getPredicateAt(CmpInst::Predicate Pred,Value * LHS,Value * RHS,Instruction * CxtI,bool UseBlockValue)1948*0fca6ea1SDimitry Andric Constant *LazyValueInfo::getPredicateAt(CmpInst::Predicate Pred, Value *LHS,
1949*0fca6ea1SDimitry Andric                                         Value *RHS, Instruction *CxtI,
1950fe6060f1SDimitry Andric                                         bool UseBlockValue) {
1951fe6060f1SDimitry Andric   if (auto *C = dyn_cast<Constant>(RHS))
1952*0fca6ea1SDimitry Andric     return getPredicateAt(Pred, LHS, C, CxtI, UseBlockValue);
1953fe6060f1SDimitry Andric   if (auto *C = dyn_cast<Constant>(LHS))
1954fe6060f1SDimitry Andric     return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
1955fe6060f1SDimitry Andric                           UseBlockValue);
1956fe6060f1SDimitry Andric 
1957bdd1243dSDimitry Andric   // Got two non-Constant values. Try to determine the comparison results based
1958bdd1243dSDimitry Andric   // on the block values of the two operands, e.g. because they have
1959bdd1243dSDimitry Andric   // non-overlapping ranges.
1960bdd1243dSDimitry Andric   if (UseBlockValue) {
1961bdd1243dSDimitry Andric     Module *M = CxtI->getModule();
1962bdd1243dSDimitry Andric     ValueLatticeElement L =
19635f757f3fSDimitry Andric         getOrCreateImpl(M).getValueInBlock(LHS, CxtI->getParent(), CxtI);
1964bdd1243dSDimitry Andric     if (L.isOverdefined())
1965*0fca6ea1SDimitry Andric       return nullptr;
1966bdd1243dSDimitry Andric 
1967bdd1243dSDimitry Andric     ValueLatticeElement R =
19685f757f3fSDimitry Andric         getOrCreateImpl(M).getValueInBlock(RHS, CxtI->getParent(), CxtI);
1969bdd1243dSDimitry Andric     Type *Ty = CmpInst::makeCmpResultType(LHS->getType());
1970*0fca6ea1SDimitry Andric     return L.getCompare(Pred, Ty, R, M->getDataLayout());
1971bdd1243dSDimitry Andric   }
1972*0fca6ea1SDimitry Andric   return nullptr;
1973fe6060f1SDimitry Andric }
1974fe6060f1SDimitry Andric 
threadEdge(BasicBlock * PredBB,BasicBlock * OldSucc,BasicBlock * NewSucc)19750b57cec5SDimitry Andric void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
19760b57cec5SDimitry Andric                                BasicBlock *NewSucc) {
19775f757f3fSDimitry Andric   if (auto *Impl = getImpl())
19785f757f3fSDimitry Andric     Impl->threadEdge(PredBB, OldSucc, NewSucc);
19790b57cec5SDimitry Andric }
19800b57cec5SDimitry Andric 
forgetValue(Value * V)19818a4dda33SDimitry Andric void LazyValueInfo::forgetValue(Value *V) {
19825f757f3fSDimitry Andric   if (auto *Impl = getImpl())
19835f757f3fSDimitry Andric     Impl->forgetValue(V);
19848a4dda33SDimitry Andric }
19858a4dda33SDimitry Andric 
eraseBlock(BasicBlock * BB)19860b57cec5SDimitry Andric void LazyValueInfo::eraseBlock(BasicBlock *BB) {
19875f757f3fSDimitry Andric   if (auto *Impl = getImpl())
19885f757f3fSDimitry Andric     Impl->eraseBlock(BB);
19890b57cec5SDimitry Andric }
19900b57cec5SDimitry Andric 
clear()19915f757f3fSDimitry Andric void LazyValueInfo::clear() {
19925f757f3fSDimitry Andric   if (auto *Impl = getImpl())
19935f757f3fSDimitry Andric     Impl->clear();
199481ad6265SDimitry Andric }
19950b57cec5SDimitry Andric 
printLVI(Function & F,DominatorTree & DTree,raw_ostream & OS)19960b57cec5SDimitry Andric void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
19975f757f3fSDimitry Andric   if (auto *Impl = getImpl())
19985f757f3fSDimitry Andric     Impl->printLVI(F, DTree, OS);
19990b57cec5SDimitry Andric }
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric // Print the LVI for the function arguments at the start of each basic block.
emitBasicBlockStartAnnot(const BasicBlock * BB,formatted_raw_ostream & OS)20020b57cec5SDimitry Andric void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
20030b57cec5SDimitry Andric     const BasicBlock *BB, formatted_raw_ostream &OS) {
20040b57cec5SDimitry Andric   // Find if there are latticevalues defined for arguments of the function.
20050b57cec5SDimitry Andric   auto *F = BB->getParent();
2006fcaf7f86SDimitry Andric   for (const auto &Arg : F->args()) {
20070b57cec5SDimitry Andric     ValueLatticeElement Result = LVIImpl->getValueInBlock(
20080b57cec5SDimitry Andric         const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
2009d65cd7a5SDimitry Andric     if (Result.isUnknown())
20100b57cec5SDimitry Andric       continue;
20110b57cec5SDimitry Andric     OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
20120b57cec5SDimitry Andric   }
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric // This function prints the LVI analysis for the instruction I at the beginning
20160b57cec5SDimitry Andric // of various basic blocks. It relies on calculated values that are stored in
20170b57cec5SDimitry Andric // the LazyValueInfoCache, and in the absence of cached values, recalculate the
20180b57cec5SDimitry Andric // LazyValueInfo for `I`, and print that info.
emitInstructionAnnot(const Instruction * I,formatted_raw_ostream & OS)20190b57cec5SDimitry Andric void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
20200b57cec5SDimitry Andric     const Instruction *I, formatted_raw_ostream &OS) {
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric   auto *ParentBB = I->getParent();
20230b57cec5SDimitry Andric   SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
20240b57cec5SDimitry Andric   // We can generate (solve) LVI values only for blocks that are dominated by
20250b57cec5SDimitry Andric   // the I's parent. However, to avoid generating LVI for all dominating blocks,
20260b57cec5SDimitry Andric   // that contain redundant/uninteresting information, we print LVI for
20270b57cec5SDimitry Andric   // blocks that may use this LVI information (such as immediate successor
20280b57cec5SDimitry Andric   // blocks, and blocks that contain uses of `I`).
20290b57cec5SDimitry Andric   auto printResult = [&](const BasicBlock *BB) {
20300b57cec5SDimitry Andric     if (!BlocksContainingLVI.insert(BB).second)
20310b57cec5SDimitry Andric       return;
20320b57cec5SDimitry Andric     ValueLatticeElement Result = LVIImpl->getValueInBlock(
20330b57cec5SDimitry Andric         const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
20340b57cec5SDimitry Andric       OS << "; LatticeVal for: '" << *I << "' in BB: '";
20350b57cec5SDimitry Andric       BB->printAsOperand(OS, false);
20360b57cec5SDimitry Andric       OS << "' is: " << Result << "\n";
20370b57cec5SDimitry Andric   };
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric   printResult(ParentBB);
20400b57cec5SDimitry Andric   // Print the LVI analysis results for the immediate successor blocks, that
20410b57cec5SDimitry Andric   // are dominated by `ParentBB`.
2042fcaf7f86SDimitry Andric   for (const auto *BBSucc : successors(ParentBB))
20430b57cec5SDimitry Andric     if (DT.dominates(ParentBB, BBSucc))
20440b57cec5SDimitry Andric       printResult(BBSucc);
20450b57cec5SDimitry Andric 
20460b57cec5SDimitry Andric   // Print LVI in blocks where `I` is used.
2047fcaf7f86SDimitry Andric   for (const auto *U : I->users())
20480b57cec5SDimitry Andric     if (auto *UseI = dyn_cast<Instruction>(U))
20490b57cec5SDimitry Andric       if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
20500b57cec5SDimitry Andric         printResult(UseI->getParent());
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric }
20530b57cec5SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)20545f757f3fSDimitry Andric PreservedAnalyses LazyValueInfoPrinterPass::run(Function &F,
20555f757f3fSDimitry Andric                                                 FunctionAnalysisManager &AM) {
20565f757f3fSDimitry Andric   OS << "LVI for function '" << F.getName() << "':\n";
20575f757f3fSDimitry Andric   auto &LVI = AM.getResult<LazyValueAnalysis>(F);
20585f757f3fSDimitry Andric   auto &DTree = AM.getResult<DominatorTreeAnalysis>(F);
20595f757f3fSDimitry Andric   LVI.printLVI(F, DTree, OS);
20605f757f3fSDimitry Andric   return PreservedAnalyses::all();
20610b57cec5SDimitry Andric }
2062