LLVM 24.0.0git
AssumptionCache.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/STLExtras.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Function.h"
25#include "llvm/IR/InstrTypes.h"
26#include "llvm/IR/Instruction.h"
28#include "llvm/IR/PassManager.h"
31#include "llvm/Pass.h"
36#include <cassert>
37#include <limits>
38
39using namespace llvm;
40using namespace llvm::PatternMatch;
41
42static cl::opt<bool>
43 VerifyAssumptionCache("verify-assumption-cache", cl::Hidden,
44 cl::desc("Enable verification of assumption cache"),
45 cl::init(false));
46
48
50 "max-assumes-per-value", cl::Hidden, cl::location(MaxAssumesPerValue),
51 cl::init(1024),
52 cl::desc("Maximum number of assumptions affecting a single value that "
53 "analyses will inspect"));
54
56AssumptionCache::getOrInsertAffectedValues(Value *V) {
57 // Try using find_as first to avoid creating extra value handles just for the
58 // purpose of doing the lookup.
59 auto AVI = AffectedValues.find_as(V);
60 if (AVI != AffectedValues.end())
61 return AVI->second;
62
63 return AffectedValues[AffectedValueCallbackVH(V, this)];
64}
65
67 OperandBundleUse Bundle, function_ref<void(Value *)> InsertAffected) {
68 auto AddAffectedVal = [&](Value *V) {
70 InsertAffected(V);
71 };
72
73 if (Bundle.getTagName() == "separate_storage") {
74 assert(Bundle.Inputs.size() == 2 && "separate_storage must have two args");
75 AddAffectedVal(getUnderlyingObject(Bundle.Inputs[0]));
76 AddAffectedVal(getUnderlyingObject(Bundle.Inputs[1]));
77 } else if (Bundle.Inputs.size() > ABA_WasOn &&
78 Bundle.getTagName() != IgnoreBundleTag)
79 AddAffectedVal(Bundle.Inputs[ABA_WasOn]);
80}
81
82static void
85 // Note: This code must be kept in-sync with the code in
86 // computeKnownBitsFromAssume in ValueTracking.
87
88 auto InsertAffected = [&Affected](Value *V) {
90 };
91
92 auto AddAffectedVal = [&Affected](Value *V, unsigned Idx) {
94 Affected.push_back({V, Idx});
95 }
96 };
97
98 for (unsigned Idx = 0; Idx != CI->getNumOperandBundles(); Idx++)
100 CI->getOperandBundleAt(Idx),
101 [&](Value *V) { Affected.push_back({V, Idx}); });
102
103 Value *Cond = CI->getArgOperand(0);
104 findValuesAffectedByCondition(Cond, /*IsAssume=*/true, InsertAffected);
105
106 if (TTI) {
107 const Value *Ptr;
108 unsigned AS;
109 std::tie(Ptr, AS) = TTI->getPredicatedAddrSpace(Cond);
110 if (Ptr)
111 AddAffectedVal(const_cast<Value *>(Ptr->stripInBoundsOffsets()),
113 }
114}
115
118 findAffectedValues(CI, TTI, Affected);
119
120 for (auto &AV : Affected) {
121 auto &AVV = getOrInsertAffectedValues(AV.Assume);
122 if (llvm::none_of(AVV, [&](ResultElem &Elem) {
123 return Elem.Assume == CI && Elem.Index == AV.Index;
124 }))
125 AVV.push_back({CI, AV.Index});
126 }
127}
128
129void AssumptionCache::removeAffectedValues(AssumeInst *CI) {
131 findAffectedValues(CI, TTI, Affected);
132
133 for (auto &AV : Affected) {
134 auto AVI = AffectedValues.find_as(AV.Assume);
135 if (AVI == AffectedValues.end())
136 continue;
137 bool Found = false;
138 bool HasNonnull = false;
139 for (ResultElem &Elem : AVI->second) {
140 if (Elem.Assume == CI) {
141 Found = true;
142 Elem.Assume = nullptr;
143 }
144
145 // We need to iterate through this loop to determine the value of
146 // HasNonnull, to avoid prematurely calling AffectedValues.erase(AVI).
147 HasNonnull |= !!Elem.Assume;
148 if (HasNonnull && Found)
149 break;
150 }
151
152 if (!Found) {
153 // It may well be the case that we fail to find an affected value in the
154 // cache. In particular, if an assume call is updated via `Use::set()`, we
155 // won't be notified that the affected value has changed and the cache
156 // will silently go stale.
157 } else if (!HasNonnull)
158 AffectedValues.erase(AVI);
159 }
160}
161
163 removeAffectedValues(CI);
164 llvm::erase(AssumeHandles, CI);
165}
166
168 removeAffectedValues(cast<AssumeInst>(Handle));
169 Handle = New;
171}
172
174 AC->AffectedValues.erase(getValPtr());
175 // 'this' now dangles!
176}
177
178void AssumptionCache::transferAffectedValuesInCache(Value *OV, Value *NV) {
179 auto &NAVV = getOrInsertAffectedValues(NV);
180 auto AVI = AffectedValues.find(OV);
181 if (AVI == AffectedValues.end())
182 return;
183
184 for (auto &A : AVI->second)
185 if (!llvm::is_contained(NAVV, A))
186 NAVV.push_back(A);
187 AffectedValues.erase(OV);
188}
189
190void AssumptionCache::AffectedValueCallbackVH::allUsesReplacedWith(Value *NV) {
191 if (!isa<Instruction>(NV) && !isa<Argument>(NV))
192 return;
193
194 // Any assumptions that affected this value now affect the new value.
195
196 AC->transferAffectedValuesInCache(getValPtr(), NV);
197 // 'this' now might dangle! If the AffectedValues map was resized to add an
198 // entry for NV then this object might have been destroyed in favor of some
199 // copy in the grown map.
200}
201
202void AssumptionCache::scanFunction() {
203 assert(!Scanned && "Tried to scan the function twice!");
204 assert(AssumeHandles.empty() && "Already have assumes when scanning!");
205
206 // Go through all instructions in all blocks, add all calls to @llvm.assume
207 // to this cache.
208 for (BasicBlock &B : F)
209 for (Instruction &I : B)
210 if (isa<AssumeInst>(&I))
211 AssumeHandles.push_back(&I);
212
213 // Mark the scan as complete.
214 Scanned = true;
215
216 // Update affected values.
217 for (auto &A : AssumeHandles)
219}
220
221/// Check the assumptions cached for \p F, collecting them in \p Cached. Returns
222/// a description of the first invariant violated, or nullptr if there is none.
223static const char *
226 for (const WeakVH &VH : Assumptions) {
227 if (!VH)
228 continue;
229
230 const auto *CI = cast<CallInst>(VH);
231 if (CI->getFunction() != &F)
232 return "Cached assumption not inside this function";
234 return "Cached something other than a call to @llvm.assume";
235 if (!Cached.insert(CI).second)
236 return "Cache contains multiple copies of a call";
237 }
238
239 return nullptr;
240}
241
243 // If we haven't scanned the function yet, just drop this assumption. It will
244 // be found when we scan later.
245 if (!Scanned)
246 return;
247
248 AssumeHandles.push_back(CI);
249
250#ifndef NDEBUG
251 assert(CI->getParent() &&
252 "Cannot register @llvm.assume call not in a basic block");
253 assert(&F == CI->getParent()->getParent() &&
254 "Cannot register @llvm.assume call not in this function");
255
256 // We expect the number of assumptions to be small, so in an asserts build
257 // check that we don't accumulate duplicates and that all assumptions point
258 // to the same function. Scanning the whole cache on every registration is
259 // quadratic, so stop once it outgrows that expectation unless expensive
260 // checks are enabled. Larger caches are checked by
261 // AssumptionCacheTracker::verifyAnalysis() instead.
262#ifdef EXPENSIVE_CHECKS
263 constexpr unsigned MaxAssumesToVerify = std::numeric_limits<unsigned>::max();
264#else
265 constexpr unsigned MaxAssumesToVerify = 64;
266#endif
267 if (AssumeHandles.size() <= MaxAssumesToVerify) {
269 if (const char *Violation = findCacheViolation(F, AssumeHandles, Cached))
270 llvm_unreachable(Violation);
271 }
272#endif
273
275}
276
282
283AnalysisKey AssumptionAnalysis::Key;
284
288
289 OS << "Cached assumptions for function: " << F.getName() << "\n";
290 for (auto &VH : AC.assumptions()) {
291 if (!VH)
292 continue;
293
294 auto *Assume = cast<CallInst>(VH);
295 if (!Assume->hasOperandBundles()) {
296 OS << " " << *Assume->getArgOperand(0) << "\n";
297 continue;
298 }
299
300 assert(match(Assume->getArgOperand(0), m_One()) &&
301 "assume must have trivial cond");
302 OS << " [ ";
303 ListSeparator LS;
304 for (const OperandBundleUse &BU : Assume->operand_bundles()) {
305 OS << LS << '"' << BU.getTagName() << "\"(";
306 interleaveComma(BU.Inputs, OS,
307 [&](const Use &Input) { Input->printAsOperand(OS); });
308 OS << ')';
309 }
310 OS << " ]\n";
311 }
312
313 return PreservedAnalyses::all();
314}
315
317 auto I = ACT->AssumptionCaches.find_as(cast<Function>(getValPtr()));
318 if (I != ACT->AssumptionCaches.end())
319 ACT->AssumptionCaches.erase(I);
320 // 'this' now dangles!
321}
322
324 // We probe the function map twice to try and avoid creating a value handle
325 // around the function in common cases. This makes insertion a bit slower,
326 // but if we have to insert we're going to scan the whole function so that
327 // shouldn't matter.
328 auto I = AssumptionCaches.find_as(&F);
329 if (I != AssumptionCaches.end())
330 return *I->second;
331
333 auto *TTI = TTIWP ? &TTIWP->getTTI(F) : nullptr;
334
335 // Ok, build a new cache by scanning the function, insert it and the value
336 // handle into our map, and return the newly populated cache.
337 auto IP = AssumptionCaches.insert(std::make_pair(
338 FunctionCallbackVH(&F, this), std::make_unique<AssumptionCache>(F, TTI)));
339 assert(IP.second && "Scanning function already in the map?");
340 return *IP.first->second;
341}
342
344 auto I = AssumptionCaches.find_as(&F);
345 if (I != AssumptionCaches.end())
346 return I->second.get();
347 return nullptr;
348}
349
351 // FIXME: In the long term the verifier should not be controllable with a
352 // flag. We should either fix all passes to correctly update the assumption
353 // cache and enable the verifier unconditionally or somehow arrange for the
354 // assumption list to be updated automatically by passes.
356 return;
357
358 for (const auto &I : AssumptionCaches) {
359 const Function &F = cast<Function>(*I.first);
360
362 if (const char *Violation =
363 findCacheViolation(F, I.second->assumptions(), Cached))
364 report_fatal_error(Violation);
365
366 for (const BasicBlock &B : F)
367 for (const Instruction &II : B)
369 !Cached.count(cast<CallInst>(&II)))
370 report_fatal_error("Assumption in scanned function not in cache");
371 }
372}
373
375
377
379
380INITIALIZE_PASS(AssumptionCacheTracker, "assumption-cache-tracker",
381 "Assumption Cache Tracker", false, true)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const char * findCacheViolation(const Function &F, ArrayRef< WeakVH > Assumptions, SmallPtrSetImpl< const CallInst * > &Cached)
Check the assumptions cached for F, collecting them in Cached.
static void findAffectedValues(CallBase *CI, TargetTransformInfo *TTI, SmallVectorImpl< AssumptionCache::ResultElem > &Affected)
static cl::opt< bool > VerifyAssumptionCache("verify-assumption-cache", cl::Hidden, cl::desc("Enable verification of assumption cache"), cl::init(false))
static cl::opt< unsigned, true > MaxAssumesPerValueOpt("max-assumes-per-value", cl::Hidden, cl::location(MaxAssumesPerValue), cl::init(1024), cl::desc("Maximum number of assumptions affecting a single value that " "analyses will inspect"))
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseSet and SmallDenseSet classes.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
This pass exposes codegen information to IR-level passes.
The Input class is used to parse a yaml document into in-memory structs and vectors.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
LLVM_ABI AssumptionCache run(Function &F, FunctionAnalysisManager &)
An immutable pass that tracks lazily created AssumptionCache objects.
AssumptionCache * lookupAssumptionCache(Function &F)
Return the cached assumptions for a function if it has already been scanned.
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
AssumptionCache & getAssumptionCache(Function &F)
Get the cached assumptions for a function.
A cache of @llvm.assume calls within a function.
static LLVM_ABI void findValuesAffectedByOperandBundle(OperandBundleUse Bundle, function_ref< void(Value *)> InsertAffected)
Determine which values are affected by this assume operand bundle.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM_ABI void replaceAssumption(WeakVH &Handle, AssumeInst *New)
Replace the assumption referenced by Handle (must be a valid handle for a registered assumption) with...
LLVM_ABI void updateAffectedValues(AssumeInst *CI)
Update the cache of values being affected by this assumption (i.e.
MutableArrayRef< WeakVH > assumptions()
Access the list of assumption handles currently tracked for this function.
LLVM_ABI void unregisterAssumption(AssumeInst *CI)
Remove an @llvm.assume intrinsic from this function's cache if it has been added to the cache earlier...
AssumptionCache(Function &F, TargetTransformInfo *TTI=nullptr)
Construct an AssumptionCache from a function by scanning all of its instructions.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
virtual void deleted()
Callback for Value destruction.
ImmutablePass(char &pid)
Definition Pass.h:287
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
A helper class to return the specified delimiter string after the first invocation of operator String...
AnalysisType * getAnalysisIfAvailable() const
getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to get analysis information tha...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getValPtr() const
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI const Value * stripInBoundsOffsets(function_ref< void(const Value *)> Func=[](const Value *) {}) const
Strip off pointer casts and inbounds GEPs.
Definition Value.cpp:828
A nullable Value handle that is nullable.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool match(Val *V, const Pattern &P)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
initializer< Ty > init(const Ty &Val)
LocationClass< Ty > location(Ty &L)
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI unsigned MaxAssumesPerValue
Set by -max-assumes-per-value; see AssumptionCache::assumptionsFor().
constexpr StringRef IgnoreBundleTag
Tag in operand bundle indicating that this bundle should be ignored.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2313
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2200
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
TargetTransformInfo TTI
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
unsigned Index
contains either ExprResultIdx or the index of the operand bundle containing the knowledge.
A lightweight accessor for an operand bundle meant to be passed around by value.
StringRef getTagName() const
Return the tag of this operand bundle as a string.
ArrayRef< Use > Inputs