LLVM 24.0.0git
AssumptionCache.h
Go to the documentation of this file.
1//===- llvm/Analysis/AssumptionCache.h - Track @llvm.assume -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains a pass that keeps track of @llvm.assume intrinsics in
10// the functions of a module (allowing assumptions within any function to be
11// found cheaply by other parts of the optimizer).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ANALYSIS_ASSUMPTIONCACHE_H
16#define LLVM_ANALYSIS_ASSUMPTIONCACHE_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
22#include "llvm/IR/PassManager.h"
23#include "llvm/IR/ValueHandle.h"
24#include "llvm/Pass.h"
26#include <memory>
27
28namespace llvm {
29
30class AssumeInst;
31struct OperandBundleUse;
32class Function;
33class raw_ostream;
35class Value;
36
37/// A cache of \@llvm.assume calls within a function.
38///
39/// This cache provides fast lookup of assumptions within a function by caching
40/// them and amortizing the cost of scanning for them across all queries. Passes
41/// that create new assumptions are required to call registerAssumption() to
42/// register any new \@llvm.assume calls that they create. Deletions of
43/// \@llvm.assume calls do not require special handling.
45public:
46 /// Value of ResultElem::Index indicating that the argument to the call of the
47 /// llvm.assume.
48 enum : unsigned { ExprResultIdx = std::numeric_limits<unsigned>::max() };
49
50 struct ResultElem {
52
53 /// contains either ExprResultIdx or the index of the operand bundle
54 /// containing the knowledge.
55 unsigned Index;
56 operator Value *() const { return Assume; }
57 };
58
59private:
60 /// The function for which this cache is handling assumptions.
61 ///
62 /// We track this to lazily populate our assumptions.
63 Function &F;
64
66
67 /// Vector of weak value handles to calls of the \@llvm.assume
68 /// intrinsic.
69 SmallVector<WeakVH, 4> AssumeHandles;
70
71 class LLVM_ABI AffectedValueCallbackVH final : public CallbackVH {
73
74 void deleted() override;
75 void allUsesReplacedWith(Value *) override;
76
77 public:
78 using DMI = DenseMapInfo<Value *>;
79
80 AffectedValueCallbackVH(Value *V, AssumptionCache *AC = nullptr)
81 : CallbackVH(V), AC(AC) {}
82 };
83
84 friend AffectedValueCallbackVH;
85
86 /// A map of values about which an assumption might be providing
87 /// information to the relevant set of assumptions.
88 using AffectedValuesMap =
89 DenseMap<AffectedValueCallbackVH, SmallVector<ResultElem, 1>,
90 AffectedValueCallbackVH::DMI>;
91 AffectedValuesMap AffectedValues;
92
93 /// Get the vector of assumptions which affect a value from the cache.
94 SmallVector<ResultElem, 1> &getOrInsertAffectedValues(Value *V);
95
96 /// Move affected values in the cache for OV to be affected values for NV.
97 void transferAffectedValuesInCache(Value *OV, Value *NV);
98
99 /// Remove the entries in the affected-values cache that point to \p CI.
100 void removeAffectedValues(AssumeInst *CI);
101
102 /// Flag tracking whether we have scanned the function yet.
103 ///
104 /// We want to be as lazy about this as possible, and so we scan the function
105 /// at the last moment.
106 bool Scanned = false;
107
108 /// Scan the function for assumptions and add them to the cache.
109 LLVM_ABI void scanFunction();
110
111public:
112 /// Construct an AssumptionCache from a function by scanning all of
113 /// its instructions.
115 : F(F), TTI(TTI) {}
116
117 /// This cache is designed to be self-updating and so it should never be
118 /// invalidated.
120 FunctionAnalysisManager::Invalidator &) {
121 return false;
122 }
123
124 /// Add an \@llvm.assume intrinsic to this function's cache.
125 ///
126 /// The call passed in must be an instruction within this function and must
127 /// not already be in the cache.
129
130 /// Remove an \@llvm.assume intrinsic from this function's cache if it has
131 /// been added to the cache earlier.
133
134 /// Replace the assumption referenced by \p Handle (must be a valid handle for
135 /// a registered assumption) with \p New.
136 LLVM_ABI void replaceAssumption(WeakVH &Handle, AssumeInst *New);
137
138 /// Update the cache of values being affected by this assumption (i.e.
139 /// the values about which this assumption provides information).
141
142 /// Clear the cache of \@llvm.assume intrinsics for a function.
143 ///
144 /// It will be re-scanned the next time it is requested.
145 void clear() {
146 AssumeHandles.clear();
147 AffectedValues.clear();
148 Scanned = false;
149 }
150
151 /// Access the list of assumption handles currently tracked for this
152 /// function.
153 ///
154 /// Note that these produce weak handles that may be null. The caller must
155 /// handle that case.
156 /// FIXME: We should replace this with pointee_iterator<filter_iterator<...>>
157 /// when we can write that to filter out the null values. Then caller code
158 /// will become simpler.
160 if (!Scanned)
161 scanFunction();
162 return AssumeHandles;
163 }
164
165 /// Access the list of assumptions which affect this value.
166 ///
167 /// No more than -max-assumes-per-value of them are cached.
169 if (!Scanned)
170 scanFunction();
171
172 auto AVI = AffectedValues.find_as(const_cast<Value *>(V));
173 if (AVI == AffectedValues.end())
175
176 return AVI->second;
177 }
178
179 /// Determine which values are affected by this assume operand bundle.
180 LLVM_ABI static void
182 function_ref<void(Value *)> InsertAffected);
183};
184
185/// A function analysis which provides an \c AssumptionCache.
186///
187/// This analysis is intended for use with the new pass manager and will vend
188/// assumption caches for a given function.
189class AssumptionAnalysis : public AnalysisInfoMixin<AssumptionAnalysis> {
191
192 LLVM_ABI static AnalysisKey Key;
193
194public:
196
198};
199
200/// Printer pass for the \c AssumptionAnalysis results.
202 : public RequiredPassInfoMixin<AssumptionPrinterPass> {
203 raw_ostream &OS;
204
205public:
206 explicit AssumptionPrinterPass(raw_ostream &OS) : OS(OS) {}
207
209};
210
211/// An immutable pass that tracks lazily created \c AssumptionCache
212/// objects.
213///
214/// This is essentially a workaround for the legacy pass manager's weaknesses
215/// which associates each assumption cache with Function and clears it if the
216/// function is deleted. The nature of the AssumptionCache is that it is not
217/// invalidated by any changes to the function body and so this is sufficient
218/// to be conservatively correct.
220 /// A callback value handle applied to function objects, which we use to
221 /// delete our cache of intrinsics for a function when it is deleted.
222 class LLVM_ABI FunctionCallbackVH final : public CallbackVH {
224
225 void deleted() override;
226
227 public:
228 using DMI = DenseMapInfo<Value *>;
229
230 FunctionCallbackVH(Value *V, AssumptionCacheTracker *ACT = nullptr)
231 : CallbackVH(V), ACT(ACT) {}
232 };
233
234 friend FunctionCallbackVH;
235
236 using FunctionCallsMap =
238 FunctionCallbackVH::DMI>;
239
240 FunctionCallsMap AssumptionCaches;
241
242public:
243 /// Get the cached assumptions for a function.
244 ///
245 /// If no assumptions are cached, this will scan the function. Otherwise, the
246 /// existing cache will be returned.
248
249 /// Return the cached assumptions for a function if it has already been
250 /// scanned. Otherwise return nullptr.
252
255
256 void releaseMemory() override {
258 AssumptionCaches.shrink_and_clear();
259 }
260
261 void verifyAnalysis() const override;
262
263 bool doFinalization(Module &) override {
265 return false;
266 }
267
268 static char ID; // Pass identification, replacement for typeid
269};
270
271template<> struct simplify_type<AssumptionCache::ResultElem> {
272 using SimpleType = Value *;
273
275 return Val;
276 }
277};
278template<> struct simplify_type<const AssumptionCache::ResultElem> {
279 using SimpleType = /*const*/ Value *;
280
282 return Val;
283 }
284};
285
286} // end namespace llvm
287
288#endif // LLVM_ANALYSIS_ASSUMPTIONCACHE_H
aarch64 promote const
#define LLVM_ABI
Definition Compiler.h:215
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
This file defines the SmallVector class.
This represents the llvm.assume intrinsic.
A function analysis which provides an AssumptionCache.
LLVM_ABI AssumptionCache run(Function &F, FunctionAnalysisManager &)
bool doFinalization(Module &) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
AssumptionCache * lookupAssumptionCache(Function &F)
Return the cached assumptions for a function if it has already been scanned.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
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.
void clear()
Clear the cache of @llvm.assume intrinsics for a function.
LLVM_ABI void replaceAssumption(WeakVH &Handle, AssumeInst *New)
Replace the assumption referenced by Handle (must be a valid handle for a registered assumption) with...
bool invalidate(Function &, const PreservedAnalyses &, FunctionAnalysisManager::Invalidator &)
This cache is designed to be self-updating and so it should never be invalidated.
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.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
AssumptionPrinterPass(raw_ostream &OS)
Value handle with callbacks on RAUW and destruction.
ImmutablePass(char &pid)
Definition Pass.h:287
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM Value Representation.
Definition Value.h:75
A nullable Value handle that is nullable.
An efficient, type-erasing, non-owning reference to a callable.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
TargetTransformInfo TTI
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
A CRTP mix-in that provides informational APIs needed for analysis passes.
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.
An information struct used to provide DenseMap with the various necessary components for a given valu...
A lightweight accessor for an operand bundle meant to be passed around by value.
A CRTP mix-in for passes that should not be skipped.
static SimpleType getSimplifiedValue(AssumptionCache::ResultElem &Val)
static SimpleType getSimplifiedValue(const AssumptionCache::ResultElem &Val)
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...
Definition Casting.h:34