xref: /src/contrib/llvm-project/llvm/lib/Analysis/AssumptionCache.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
167c32a98SDimitry Andric //===- AssumptionCache.cpp - Cache finding @llvm.assume calls -------------===//
267c32a98SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
667c32a98SDimitry Andric //
767c32a98SDimitry Andric //===----------------------------------------------------------------------===//
867c32a98SDimitry Andric //
97fa27ce4SDimitry Andric // This file contains a pass that keeps track of @llvm.assume intrinsics in
107fa27ce4SDimitry Andric // the functions of a module.
1167c32a98SDimitry Andric //
1267c32a98SDimitry Andric //===----------------------------------------------------------------------===//
1367c32a98SDimitry Andric 
1467c32a98SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
15044eb2f6SDimitry Andric #include "llvm/ADT/STLExtras.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
18145449b1SDimitry Andric #include "llvm/Analysis/AssumeBundleQueries.h"
19c0981da4SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
20aca2e42cSDimitry Andric #include "llvm/Analysis/ValueTracking.h"
21044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
2267c32a98SDimitry Andric #include "llvm/IR/Function.h"
23044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
24044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
2567c32a98SDimitry Andric #include "llvm/IR/Instructions.h"
265a5ac124SDimitry Andric #include "llvm/IR/PassManager.h"
2767c32a98SDimitry Andric #include "llvm/IR/PatternMatch.h"
28706b4fc4SDimitry Andric #include "llvm/InitializePasses.h"
29044eb2f6SDimitry Andric #include "llvm/Pass.h"
30044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
31044eb2f6SDimitry Andric #include "llvm/Support/CommandLine.h"
32044eb2f6SDimitry Andric #include "llvm/Support/ErrorHandling.h"
33044eb2f6SDimitry Andric #include "llvm/Support/raw_ostream.h"
34044eb2f6SDimitry Andric #include <cassert>
35044eb2f6SDimitry Andric #include <utility>
36044eb2f6SDimitry Andric 
3767c32a98SDimitry Andric using namespace llvm;
3867c32a98SDimitry Andric using namespace llvm::PatternMatch;
3967c32a98SDimitry Andric 
4071d5a254SDimitry Andric static cl::opt<bool>
4171d5a254SDimitry Andric     VerifyAssumptionCache("verify-assumption-cache", cl::Hidden,
4271d5a254SDimitry Andric                           cl::desc("Enable verification of assumption cache"),
4371d5a254SDimitry Andric                           cl::init(false));
4471d5a254SDimitry Andric 
45cfca06d7SDimitry Andric SmallVector<AssumptionCache::ResultElem, 1> &
getOrInsertAffectedValues(Value * V)46a303c417SDimitry Andric AssumptionCache::getOrInsertAffectedValues(Value *V) {
47581a6d85SDimitry Andric   // Try using find_as first to avoid creating extra value handles just for the
48581a6d85SDimitry Andric   // purpose of doing the lookup.
49581a6d85SDimitry Andric   auto AVI = AffectedValues.find_as(V);
50581a6d85SDimitry Andric   if (AVI != AffectedValues.end())
51581a6d85SDimitry Andric     return AVI->second;
52581a6d85SDimitry Andric 
53a303c417SDimitry Andric   auto AVIP = AffectedValues.insert(
54cfca06d7SDimitry Andric       {AffectedValueCallbackVH(V, this), SmallVector<ResultElem, 1>()});
55581a6d85SDimitry Andric   return AVIP.first->second;
56581a6d85SDimitry Andric }
57581a6d85SDimitry Andric 
58cfca06d7SDimitry Andric static void
findAffectedValues(CallBase * CI,TargetTransformInfo * TTI,SmallVectorImpl<AssumptionCache::ResultElem> & Affected)59c0981da4SDimitry Andric findAffectedValues(CallBase *CI, TargetTransformInfo *TTI,
60cfca06d7SDimitry Andric                    SmallVectorImpl<AssumptionCache::ResultElem> &Affected) {
61581a6d85SDimitry Andric   // Note: This code must be kept in-sync with the code in
62581a6d85SDimitry Andric   // computeKnownBitsFromAssume in ValueTracking.
63581a6d85SDimitry Andric 
64ac9a064cSDimitry Andric   auto InsertAffected = [&Affected](Value *V) {
65ac9a064cSDimitry Andric     Affected.push_back({V, AssumptionCache::ExprResultIdx});
66ac9a064cSDimitry Andric   };
67581a6d85SDimitry Andric 
68ac9a064cSDimitry Andric   auto AddAffectedVal = [&Affected](Value *V, unsigned Idx) {
69ac9a064cSDimitry Andric     if (isa<Argument>(V) || isa<GlobalValue>(V) || isa<Instruction>(V)) {
70ac9a064cSDimitry Andric       Affected.push_back({V, Idx});
71581a6d85SDimitry Andric     }
72581a6d85SDimitry Andric   };
73581a6d85SDimitry Andric 
74cfca06d7SDimitry Andric   for (unsigned Idx = 0; Idx != CI->getNumOperandBundles(); Idx++) {
75aca2e42cSDimitry Andric     OperandBundleUse Bundle = CI->getOperandBundleAt(Idx);
76aca2e42cSDimitry Andric     if (Bundle.getTagName() == "separate_storage") {
77aca2e42cSDimitry Andric       assert(Bundle.Inputs.size() == 2 &&
78aca2e42cSDimitry Andric              "separate_storage must have two args");
79ac9a064cSDimitry Andric       AddAffectedVal(getUnderlyingObject(Bundle.Inputs[0]), Idx);
80ac9a064cSDimitry Andric       AddAffectedVal(getUnderlyingObject(Bundle.Inputs[1]), Idx);
81aca2e42cSDimitry Andric     } else if (Bundle.Inputs.size() > ABA_WasOn &&
82aca2e42cSDimitry Andric                Bundle.getTagName() != IgnoreBundleTag)
83ac9a064cSDimitry Andric       AddAffectedVal(Bundle.Inputs[ABA_WasOn], Idx);
84cfca06d7SDimitry Andric   }
85cfca06d7SDimitry Andric 
86ac9a064cSDimitry Andric   Value *Cond = CI->getArgOperand(0);
87ac9a064cSDimitry Andric   findValuesAffectedByCondition(Cond, /*IsAssume=*/true, InsertAffected);
88c0981da4SDimitry Andric 
89c0981da4SDimitry Andric   if (TTI) {
90c0981da4SDimitry Andric     const Value *Ptr;
91c0981da4SDimitry Andric     unsigned AS;
92c0981da4SDimitry Andric     std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(Cond);
93c0981da4SDimitry Andric     if (Ptr)
94ac9a064cSDimitry Andric       AddAffectedVal(const_cast<Value *>(Ptr->stripInBoundsOffsets()),
95ac9a064cSDimitry Andric                      AssumptionCache::ExprResultIdx);
96c0981da4SDimitry Andric   }
97e6d15924SDimitry Andric }
98e6d15924SDimitry Andric 
updateAffectedValues(AssumeInst * CI)997fa27ce4SDimitry Andric void AssumptionCache::updateAffectedValues(AssumeInst *CI) {
100cfca06d7SDimitry Andric   SmallVector<AssumptionCache::ResultElem, 16> Affected;
101c0981da4SDimitry Andric   findAffectedValues(CI, TTI, Affected);
102581a6d85SDimitry Andric 
103581a6d85SDimitry Andric   for (auto &AV : Affected) {
104cfca06d7SDimitry Andric     auto &AVV = getOrInsertAffectedValues(AV.Assume);
105c0981da4SDimitry Andric     if (llvm::none_of(AVV, [&](ResultElem &Elem) {
106cfca06d7SDimitry Andric           return Elem.Assume == CI && Elem.Index == AV.Index;
107c0981da4SDimitry Andric         }))
108cfca06d7SDimitry Andric       AVV.push_back({CI, AV.Index});
109581a6d85SDimitry Andric   }
110581a6d85SDimitry Andric }
111581a6d85SDimitry Andric 
unregisterAssumption(AssumeInst * CI)1127fa27ce4SDimitry Andric void AssumptionCache::unregisterAssumption(AssumeInst *CI) {
113cfca06d7SDimitry Andric   SmallVector<AssumptionCache::ResultElem, 16> Affected;
114c0981da4SDimitry Andric   findAffectedValues(CI, TTI, Affected);
115e6d15924SDimitry Andric 
116e6d15924SDimitry Andric   for (auto &AV : Affected) {
117cfca06d7SDimitry Andric     auto AVI = AffectedValues.find_as(AV.Assume);
118cfca06d7SDimitry Andric     if (AVI == AffectedValues.end())
119cfca06d7SDimitry Andric       continue;
120cfca06d7SDimitry Andric     bool Found = false;
121cfca06d7SDimitry Andric     bool HasNonnull = false;
122cfca06d7SDimitry Andric     for (ResultElem &Elem : AVI->second) {
123cfca06d7SDimitry Andric       if (Elem.Assume == CI) {
124cfca06d7SDimitry Andric         Found = true;
125cfca06d7SDimitry Andric         Elem.Assume = nullptr;
126cfca06d7SDimitry Andric       }
127cfca06d7SDimitry Andric       HasNonnull |= !!Elem.Assume;
128cfca06d7SDimitry Andric       if (HasNonnull && Found)
129cfca06d7SDimitry Andric         break;
130cfca06d7SDimitry Andric     }
131cfca06d7SDimitry Andric     assert(Found && "already unregistered or incorrect cache state");
132cfca06d7SDimitry Andric     if (!HasNonnull)
133e6d15924SDimitry Andric       AffectedValues.erase(AVI);
134e6d15924SDimitry Andric   }
1351d5ae102SDimitry Andric 
136b1c73532SDimitry Andric   llvm::erase(AssumeHandles, CI);
137e6d15924SDimitry Andric }
138e6d15924SDimitry Andric 
deleted()139581a6d85SDimitry Andric void AssumptionCache::AffectedValueCallbackVH::deleted() {
140b60736ecSDimitry Andric   AC->AffectedValues.erase(getValPtr());
141581a6d85SDimitry Andric   // 'this' now dangles!
142581a6d85SDimitry Andric }
143581a6d85SDimitry Andric 
transferAffectedValuesInCache(Value * OV,Value * NV)1441d5ae102SDimitry Andric void AssumptionCache::transferAffectedValuesInCache(Value *OV, Value *NV) {
1457c71d32aSDimitry Andric   auto &NAVV = getOrInsertAffectedValues(NV);
1467c71d32aSDimitry Andric   auto AVI = AffectedValues.find(OV);
1477c71d32aSDimitry Andric   if (AVI == AffectedValues.end())
1487c71d32aSDimitry Andric     return;
1497c71d32aSDimitry Andric 
1507c71d32aSDimitry Andric   for (auto &A : AVI->second)
151b60736ecSDimitry Andric     if (!llvm::is_contained(NAVV, A))
1527c71d32aSDimitry Andric       NAVV.push_back(A);
1531d5ae102SDimitry Andric   AffectedValues.erase(OV);
1547c71d32aSDimitry Andric }
1557c71d32aSDimitry Andric 
allUsesReplacedWith(Value * NV)156581a6d85SDimitry Andric void AssumptionCache::AffectedValueCallbackVH::allUsesReplacedWith(Value *NV) {
157581a6d85SDimitry Andric   if (!isa<Instruction>(NV) && !isa<Argument>(NV))
158581a6d85SDimitry Andric     return;
159581a6d85SDimitry Andric 
160581a6d85SDimitry Andric   // Any assumptions that affected this value now affect the new value.
161581a6d85SDimitry Andric 
1621d5ae102SDimitry Andric   AC->transferAffectedValuesInCache(getValPtr(), NV);
1637c71d32aSDimitry Andric   // 'this' now might dangle! If the AffectedValues map was resized to add an
1647c71d32aSDimitry Andric   // entry for NV then this object might have been destroyed in favor of some
1657c71d32aSDimitry Andric   // copy in the grown map.
166581a6d85SDimitry Andric }
167581a6d85SDimitry Andric 
scanFunction()16867c32a98SDimitry Andric void AssumptionCache::scanFunction() {
16967c32a98SDimitry Andric   assert(!Scanned && "Tried to scan the function twice!");
17067c32a98SDimitry Andric   assert(AssumeHandles.empty() && "Already have assumes when scanning!");
17167c32a98SDimitry Andric 
17267c32a98SDimitry Andric   // Go through all instructions in all blocks, add all calls to @llvm.assume
17367c32a98SDimitry Andric   // to this cache.
17467c32a98SDimitry Andric   for (BasicBlock &B : F)
175344a3780SDimitry Andric     for (Instruction &I : B)
1767fa27ce4SDimitry Andric       if (isa<AssumeInst>(&I))
177344a3780SDimitry Andric         AssumeHandles.push_back({&I, ExprResultIdx});
17867c32a98SDimitry Andric 
17967c32a98SDimitry Andric   // Mark the scan as complete.
18067c32a98SDimitry Andric   Scanned = true;
181581a6d85SDimitry Andric 
182581a6d85SDimitry Andric   // Update affected values.
183581a6d85SDimitry Andric   for (auto &A : AssumeHandles)
1847fa27ce4SDimitry Andric     updateAffectedValues(cast<AssumeInst>(A));
18567c32a98SDimitry Andric }
18667c32a98SDimitry Andric 
registerAssumption(AssumeInst * CI)1877fa27ce4SDimitry Andric void AssumptionCache::registerAssumption(AssumeInst *CI) {
18867c32a98SDimitry Andric   // If we haven't scanned the function yet, just drop this assumption. It will
18967c32a98SDimitry Andric   // be found when we scan later.
19067c32a98SDimitry Andric   if (!Scanned)
19167c32a98SDimitry Andric     return;
19267c32a98SDimitry Andric 
193cfca06d7SDimitry Andric   AssumeHandles.push_back({CI, ExprResultIdx});
19467c32a98SDimitry Andric 
19567c32a98SDimitry Andric #ifndef NDEBUG
19667c32a98SDimitry Andric   assert(CI->getParent() &&
1977fa27ce4SDimitry Andric          "Cannot register @llvm.assume call not in a basic block");
19867c32a98SDimitry Andric   assert(&F == CI->getParent()->getParent() &&
1997fa27ce4SDimitry Andric          "Cannot register @llvm.assume call not in this function");
20067c32a98SDimitry Andric 
20167c32a98SDimitry Andric   // We expect the number of assumptions to be small, so in an asserts build
20267c32a98SDimitry Andric   // check that we don't accumulate duplicates and that all assumptions point
20367c32a98SDimitry Andric   // to the same function.
20467c32a98SDimitry Andric   SmallPtrSet<Value *, 16> AssumptionSet;
20567c32a98SDimitry Andric   for (auto &VH : AssumeHandles) {
20667c32a98SDimitry Andric     if (!VH)
20767c32a98SDimitry Andric       continue;
20867c32a98SDimitry Andric 
20967c32a98SDimitry Andric     assert(&F == cast<Instruction>(VH)->getParent()->getParent() &&
21067c32a98SDimitry Andric            "Cached assumption not inside this function!");
2117fa27ce4SDimitry Andric     assert(match(cast<CallInst>(VH), m_Intrinsic<Intrinsic::assume>()) &&
2127fa27ce4SDimitry Andric            "Cached something other than a call to @llvm.assume!");
21367c32a98SDimitry Andric     assert(AssumptionSet.insert(VH).second &&
21467c32a98SDimitry Andric            "Cache contains multiple copies of a call!");
21567c32a98SDimitry Andric   }
21667c32a98SDimitry Andric #endif
217581a6d85SDimitry Andric 
218581a6d85SDimitry Andric   updateAffectedValues(CI);
21967c32a98SDimitry Andric }
22067c32a98SDimitry Andric 
run(Function & F,FunctionAnalysisManager & FAM)221c0981da4SDimitry Andric AssumptionCache AssumptionAnalysis::run(Function &F,
222c0981da4SDimitry Andric                                         FunctionAnalysisManager &FAM) {
223c0981da4SDimitry Andric   auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
224c0981da4SDimitry Andric   return AssumptionCache(F, &TTI);
225c0981da4SDimitry Andric }
226c0981da4SDimitry Andric 
227b915e9e0SDimitry Andric AnalysisKey AssumptionAnalysis::Key;
2285a5ac124SDimitry Andric 
run(Function & F,FunctionAnalysisManager & AM)2295a5ac124SDimitry Andric PreservedAnalyses AssumptionPrinterPass::run(Function &F,
230b915e9e0SDimitry Andric                                              FunctionAnalysisManager &AM) {
23101095a5dSDimitry Andric   AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
2325a5ac124SDimitry Andric 
2335a5ac124SDimitry Andric   OS << "Cached assumptions for function: " << F.getName() << "\n";
2345a5ac124SDimitry Andric   for (auto &VH : AC.assumptions())
2355a5ac124SDimitry Andric     if (VH)
2365a5ac124SDimitry Andric       OS << "  " << *cast<CallInst>(VH)->getArgOperand(0) << "\n";
2375a5ac124SDimitry Andric 
2385a5ac124SDimitry Andric   return PreservedAnalyses::all();
2395a5ac124SDimitry Andric }
2405a5ac124SDimitry Andric 
deleted()24167c32a98SDimitry Andric void AssumptionCacheTracker::FunctionCallbackVH::deleted() {
24267c32a98SDimitry Andric   auto I = ACT->AssumptionCaches.find_as(cast<Function>(getValPtr()));
24367c32a98SDimitry Andric   if (I != ACT->AssumptionCaches.end())
24467c32a98SDimitry Andric     ACT->AssumptionCaches.erase(I);
24567c32a98SDimitry Andric   // 'this' now dangles!
24667c32a98SDimitry Andric }
24767c32a98SDimitry Andric 
getAssumptionCache(Function & F)24867c32a98SDimitry Andric AssumptionCache &AssumptionCacheTracker::getAssumptionCache(Function &F) {
24967c32a98SDimitry Andric   // We probe the function map twice to try and avoid creating a value handle
25067c32a98SDimitry Andric   // around the function in common cases. This makes insertion a bit slower,
25167c32a98SDimitry Andric   // but if we have to insert we're going to scan the whole function so that
25267c32a98SDimitry Andric   // shouldn't matter.
25367c32a98SDimitry Andric   auto I = AssumptionCaches.find_as(&F);
25467c32a98SDimitry Andric   if (I != AssumptionCaches.end())
25567c32a98SDimitry Andric     return *I->second;
25667c32a98SDimitry Andric 
257c0981da4SDimitry Andric   auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
258c0981da4SDimitry Andric   auto *TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
259c0981da4SDimitry Andric 
26067c32a98SDimitry Andric   // Ok, build a new cache by scanning the function, insert it and the value
26167c32a98SDimitry Andric   // handle into our map, and return the newly populated cache.
26267c32a98SDimitry Andric   auto IP = AssumptionCaches.insert(std::make_pair(
263c0981da4SDimitry Andric       FunctionCallbackVH(&F, this), std::make_unique<AssumptionCache>(F, TTI)));
26467c32a98SDimitry Andric   assert(IP.second && "Scanning function already in the map?");
26567c32a98SDimitry Andric   return *IP.first->second;
26667c32a98SDimitry Andric }
26767c32a98SDimitry Andric 
lookupAssumptionCache(Function & F)268e6d15924SDimitry Andric AssumptionCache *AssumptionCacheTracker::lookupAssumptionCache(Function &F) {
269e6d15924SDimitry Andric   auto I = AssumptionCaches.find_as(&F);
270e6d15924SDimitry Andric   if (I != AssumptionCaches.end())
271e6d15924SDimitry Andric     return I->second.get();
272e6d15924SDimitry Andric   return nullptr;
273e6d15924SDimitry Andric }
274e6d15924SDimitry Andric 
verifyAnalysis() const27567c32a98SDimitry Andric void AssumptionCacheTracker::verifyAnalysis() const {
27671d5a254SDimitry Andric   // FIXME: In the long term the verifier should not be controllable with a
27771d5a254SDimitry Andric   // flag. We should either fix all passes to correctly update the assumption
27871d5a254SDimitry Andric   // cache and enable the verifier unconditionally or somehow arrange for the
27971d5a254SDimitry Andric   // assumption list to be updated automatically by passes.
28071d5a254SDimitry Andric   if (!VerifyAssumptionCache)
28171d5a254SDimitry Andric     return;
28271d5a254SDimitry Andric 
28367c32a98SDimitry Andric   SmallPtrSet<const CallInst *, 4> AssumptionSet;
28467c32a98SDimitry Andric   for (const auto &I : AssumptionCaches) {
28567c32a98SDimitry Andric     for (auto &VH : I.second->assumptions())
28667c32a98SDimitry Andric       if (VH)
28767c32a98SDimitry Andric         AssumptionSet.insert(cast<CallInst>(VH));
28867c32a98SDimitry Andric 
28967c32a98SDimitry Andric     for (const BasicBlock &B : cast<Function>(*I.first))
29067c32a98SDimitry Andric       for (const Instruction &II : B)
29171d5a254SDimitry Andric         if (match(&II, m_Intrinsic<Intrinsic::assume>()) &&
29271d5a254SDimitry Andric             !AssumptionSet.count(cast<CallInst>(&II)))
29371d5a254SDimitry Andric           report_fatal_error("Assumption in scanned function not in cache");
29467c32a98SDimitry Andric   }
29567c32a98SDimitry Andric }
29667c32a98SDimitry Andric 
AssumptionCacheTracker()29767c32a98SDimitry Andric AssumptionCacheTracker::AssumptionCacheTracker() : ImmutablePass(ID) {
29867c32a98SDimitry Andric   initializeAssumptionCacheTrackerPass(*PassRegistry::getPassRegistry());
29967c32a98SDimitry Andric }
30067c32a98SDimitry Andric 
301044eb2f6SDimitry Andric AssumptionCacheTracker::~AssumptionCacheTracker() = default;
302044eb2f6SDimitry Andric 
303044eb2f6SDimitry Andric char AssumptionCacheTracker::ID = 0;
30467c32a98SDimitry Andric 
30567c32a98SDimitry Andric INITIALIZE_PASS(AssumptionCacheTracker, "assumption-cache-tracker",
30667c32a98SDimitry Andric                 "Assumption Cache Tracker", false, true)
307