xref: /freebsd/contrib/llvm-project/llvm/lib/Analysis/AssumptionCache.cpp (revision 81ad626541db97eb356e2c1d4a20eb2a26a766ab)
1 //===- AssumptionCache.cpp - Cache finding @llvm.assume calls -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a pass that keeps track of @llvm.assume intrinsics in
10 // the functions of a module.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/AssumptionCache.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Analysis/AssumeBundleQueries.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/InstrTypes.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <cassert>
34 #include <utility>
35 
36 using namespace llvm;
37 using namespace llvm::PatternMatch;
38 
39 static cl::opt<bool>
40     VerifyAssumptionCache("verify-assumption-cache", cl::Hidden,
41                           cl::desc("Enable verification of assumption cache"),
42                           cl::init(false));
43 
44 SmallVector<AssumptionCache::ResultElem, 1> &
45 AssumptionCache::getOrInsertAffectedValues(Value *V) {
46   // Try using find_as first to avoid creating extra value handles just for the
47   // purpose of doing the lookup.
48   auto AVI = AffectedValues.find_as(V);
49   if (AVI != AffectedValues.end())
50     return AVI->second;
51 
52   auto AVIP = AffectedValues.insert(
53       {AffectedValueCallbackVH(V, this), SmallVector<ResultElem, 1>()});
54   return AVIP.first->second;
55 }
56 
57 static void
58 findAffectedValues(CallBase *CI, TargetTransformInfo *TTI,
59                    SmallVectorImpl<AssumptionCache::ResultElem> &Affected) {
60   // Note: This code must be kept in-sync with the code in
61   // computeKnownBitsFromAssume in ValueTracking.
62 
63   auto AddAffected = [&Affected](Value *V, unsigned Idx =
64                                                AssumptionCache::ExprResultIdx) {
65     if (isa<Argument>(V)) {
66       Affected.push_back({V, Idx});
67     } else if (auto *I = dyn_cast<Instruction>(V)) {
68       Affected.push_back({I, Idx});
69 
70       // Peek through unary operators to find the source of the condition.
71       Value *Op;
72       if (match(I, m_BitCast(m_Value(Op))) ||
73           match(I, m_PtrToInt(m_Value(Op))) || match(I, m_Not(m_Value(Op)))) {
74         if (isa<Instruction>(Op) || isa<Argument>(Op))
75           Affected.push_back({Op, Idx});
76       }
77     }
78   };
79 
80   for (unsigned Idx = 0; Idx != CI->getNumOperandBundles(); Idx++) {
81     if (CI->getOperandBundleAt(Idx).Inputs.size() > ABA_WasOn &&
82         CI->getOperandBundleAt(Idx).getTagName() != IgnoreBundleTag)
83       AddAffected(CI->getOperandBundleAt(Idx).Inputs[ABA_WasOn], Idx);
84   }
85 
86   Value *Cond = CI->getArgOperand(0), *A, *B;
87   AddAffected(Cond);
88 
89   CmpInst::Predicate Pred;
90   if (match(Cond, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
91     AddAffected(A);
92     AddAffected(B);
93 
94     if (Pred == ICmpInst::ICMP_EQ) {
95       // For equality comparisons, we handle the case of bit inversion.
96       auto AddAffectedFromEq = [&AddAffected](Value *V) {
97         Value *A;
98         if (match(V, m_Not(m_Value(A)))) {
99           AddAffected(A);
100           V = A;
101         }
102 
103         Value *B;
104         // (A & B) or (A | B) or (A ^ B).
105         if (match(V, m_BitwiseLogic(m_Value(A), m_Value(B)))) {
106           AddAffected(A);
107           AddAffected(B);
108         // (A << C) or (A >>_s C) or (A >>_u C) where C is some constant.
109         } else if (match(V, m_Shift(m_Value(A), m_ConstantInt()))) {
110           AddAffected(A);
111         }
112       };
113 
114       AddAffectedFromEq(A);
115       AddAffectedFromEq(B);
116     }
117 
118     Value *X;
119     // Handle (A + C1) u< C2, which is the canonical form of A > C3 && A < C4,
120     // and recognized by LVI at least.
121     if (Pred == ICmpInst::ICMP_ULT &&
122         match(A, m_Add(m_Value(X), m_ConstantInt())) &&
123         match(B, m_ConstantInt()))
124       AddAffected(X);
125   }
126 
127   if (TTI) {
128     const Value *Ptr;
129     unsigned AS;
130     std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(Cond);
131     if (Ptr)
132       AddAffected(const_cast<Value *>(Ptr->stripInBoundsOffsets()));
133   }
134 }
135 
136 void AssumptionCache::updateAffectedValues(AssumeInst *CI) {
137   SmallVector<AssumptionCache::ResultElem, 16> Affected;
138   findAffectedValues(CI, TTI, Affected);
139 
140   for (auto &AV : Affected) {
141     auto &AVV = getOrInsertAffectedValues(AV.Assume);
142     if (llvm::none_of(AVV, [&](ResultElem &Elem) {
143           return Elem.Assume == CI && Elem.Index == AV.Index;
144         }))
145       AVV.push_back({CI, AV.Index});
146   }
147 }
148 
149 void AssumptionCache::unregisterAssumption(AssumeInst *CI) {
150   SmallVector<AssumptionCache::ResultElem, 16> Affected;
151   findAffectedValues(CI, TTI, Affected);
152 
153   for (auto &AV : Affected) {
154     auto AVI = AffectedValues.find_as(AV.Assume);
155     if (AVI == AffectedValues.end())
156       continue;
157     bool Found = false;
158     bool HasNonnull = false;
159     for (ResultElem &Elem : AVI->second) {
160       if (Elem.Assume == CI) {
161         Found = true;
162         Elem.Assume = nullptr;
163       }
164       HasNonnull |= !!Elem.Assume;
165       if (HasNonnull && Found)
166         break;
167     }
168     assert(Found && "already unregistered or incorrect cache state");
169     if (!HasNonnull)
170       AffectedValues.erase(AVI);
171   }
172 
173   erase_value(AssumeHandles, CI);
174 }
175 
176 void AssumptionCache::AffectedValueCallbackVH::deleted() {
177   AC->AffectedValues.erase(getValPtr());
178   // 'this' now dangles!
179 }
180 
181 void AssumptionCache::transferAffectedValuesInCache(Value *OV, Value *NV) {
182   auto &NAVV = getOrInsertAffectedValues(NV);
183   auto AVI = AffectedValues.find(OV);
184   if (AVI == AffectedValues.end())
185     return;
186 
187   for (auto &A : AVI->second)
188     if (!llvm::is_contained(NAVV, A))
189       NAVV.push_back(A);
190   AffectedValues.erase(OV);
191 }
192 
193 void AssumptionCache::AffectedValueCallbackVH::allUsesReplacedWith(Value *NV) {
194   if (!isa<Instruction>(NV) && !isa<Argument>(NV))
195     return;
196 
197   // Any assumptions that affected this value now affect the new value.
198 
199   AC->transferAffectedValuesInCache(getValPtr(), NV);
200   // 'this' now might dangle! If the AffectedValues map was resized to add an
201   // entry for NV then this object might have been destroyed in favor of some
202   // copy in the grown map.
203 }
204 
205 void AssumptionCache::scanFunction() {
206   assert(!Scanned && "Tried to scan the function twice!");
207   assert(AssumeHandles.empty() && "Already have assumes when scanning!");
208 
209   // Go through all instructions in all blocks, add all calls to @llvm.assume
210   // to this cache.
211   for (BasicBlock &B : F)
212     for (Instruction &I : B)
213       if (isa<AssumeInst>(&I))
214         AssumeHandles.push_back({&I, ExprResultIdx});
215 
216   // Mark the scan as complete.
217   Scanned = true;
218 
219   // Update affected values.
220   for (auto &A : AssumeHandles)
221     updateAffectedValues(cast<AssumeInst>(A));
222 }
223 
224 void AssumptionCache::registerAssumption(AssumeInst *CI) {
225   // If we haven't scanned the function yet, just drop this assumption. It will
226   // be found when we scan later.
227   if (!Scanned)
228     return;
229 
230   AssumeHandles.push_back({CI, ExprResultIdx});
231 
232 #ifndef NDEBUG
233   assert(CI->getParent() &&
234          "Cannot register @llvm.assume call not in a basic block");
235   assert(&F == CI->getParent()->getParent() &&
236          "Cannot register @llvm.assume call not in this function");
237 
238   // We expect the number of assumptions to be small, so in an asserts build
239   // check that we don't accumulate duplicates and that all assumptions point
240   // to the same function.
241   SmallPtrSet<Value *, 16> AssumptionSet;
242   for (auto &VH : AssumeHandles) {
243     if (!VH)
244       continue;
245 
246     assert(&F == cast<Instruction>(VH)->getParent()->getParent() &&
247            "Cached assumption not inside this function!");
248     assert(match(cast<CallInst>(VH), m_Intrinsic<Intrinsic::assume>()) &&
249            "Cached something other than a call to @llvm.assume!");
250     assert(AssumptionSet.insert(VH).second &&
251            "Cache contains multiple copies of a call!");
252   }
253 #endif
254 
255   updateAffectedValues(CI);
256 }
257 
258 AssumptionCache AssumptionAnalysis::run(Function &F,
259                                         FunctionAnalysisManager &FAM) {
260   auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
261   return AssumptionCache(F, &TTI);
262 }
263 
264 AnalysisKey AssumptionAnalysis::Key;
265 
266 PreservedAnalyses AssumptionPrinterPass::run(Function &F,
267                                              FunctionAnalysisManager &AM) {
268   AssumptionCache &AC = AM.getResult<AssumptionAnalysis>(F);
269 
270   OS << "Cached assumptions for function: " << F.getName() << "\n";
271   for (auto &VH : AC.assumptions())
272     if (VH)
273       OS << "  " << *cast<CallInst>(VH)->getArgOperand(0) << "\n";
274 
275   return PreservedAnalyses::all();
276 }
277 
278 void AssumptionCacheTracker::FunctionCallbackVH::deleted() {
279   auto I = ACT->AssumptionCaches.find_as(cast<Function>(getValPtr()));
280   if (I != ACT->AssumptionCaches.end())
281     ACT->AssumptionCaches.erase(I);
282   // 'this' now dangles!
283 }
284 
285 AssumptionCache &AssumptionCacheTracker::getAssumptionCache(Function &F) {
286   // We probe the function map twice to try and avoid creating a value handle
287   // around the function in common cases. This makes insertion a bit slower,
288   // but if we have to insert we're going to scan the whole function so that
289   // shouldn't matter.
290   auto I = AssumptionCaches.find_as(&F);
291   if (I != AssumptionCaches.end())
292     return *I->second;
293 
294   auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
295   auto *TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
296 
297   // Ok, build a new cache by scanning the function, insert it and the value
298   // handle into our map, and return the newly populated cache.
299   auto IP = AssumptionCaches.insert(std::make_pair(
300       FunctionCallbackVH(&F, this), std::make_unique<AssumptionCache>(F, TTI)));
301   assert(IP.second && "Scanning function already in the map?");
302   return *IP.first->second;
303 }
304 
305 AssumptionCache *AssumptionCacheTracker::lookupAssumptionCache(Function &F) {
306   auto I = AssumptionCaches.find_as(&F);
307   if (I != AssumptionCaches.end())
308     return I->second.get();
309   return nullptr;
310 }
311 
312 void AssumptionCacheTracker::verifyAnalysis() const {
313   // FIXME: In the long term the verifier should not be controllable with a
314   // flag. We should either fix all passes to correctly update the assumption
315   // cache and enable the verifier unconditionally or somehow arrange for the
316   // assumption list to be updated automatically by passes.
317   if (!VerifyAssumptionCache)
318     return;
319 
320   SmallPtrSet<const CallInst *, 4> AssumptionSet;
321   for (const auto &I : AssumptionCaches) {
322     for (auto &VH : I.second->assumptions())
323       if (VH)
324         AssumptionSet.insert(cast<CallInst>(VH));
325 
326     for (const BasicBlock &B : cast<Function>(*I.first))
327       for (const Instruction &II : B)
328         if (match(&II, m_Intrinsic<Intrinsic::assume>()) &&
329             !AssumptionSet.count(cast<CallInst>(&II)))
330           report_fatal_error("Assumption in scanned function not in cache");
331   }
332 }
333 
334 AssumptionCacheTracker::AssumptionCacheTracker() : ImmutablePass(ID) {
335   initializeAssumptionCacheTrackerPass(*PassRegistry::getPassRegistry());
336 }
337 
338 AssumptionCacheTracker::~AssumptionCacheTracker() = default;
339 
340 char AssumptionCacheTracker::ID = 0;
341 
342 INITIALIZE_PASS(AssumptionCacheTracker, "assumption-cache-tracker",
343                 "Assumption Cache Tracker", false, true)
344