LLVM 23.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.
167 if (!Scanned)
168 scanFunction();
169
170 auto AVI = AffectedValues.find_as(const_cast<Value *>(V));
171 if (AVI == AffectedValues.end())
173
174 return AVI->second;
175 }
176
177 /// Determine which values are affected by this assume operand bundle.
178 LLVM_ABI static void
180 function_ref<void(Value *)> InsertAffected);
181};
182
183/// A function analysis which provides an \c AssumptionCache.
184///
185/// This analysis is intended for use with the new pass manager and will vend
186/// assumption caches for a given function.
187class AssumptionAnalysis : public AnalysisInfoMixin<AssumptionAnalysis> {
189
190 LLVM_ABI static AnalysisKey Key;
191
192public:
194
196};
197
198/// Printer pass for the \c AssumptionAnalysis results.
200 : public RequiredPassInfoMixin<AssumptionPrinterPass> {
201 raw_ostream &OS;
202
203public:
204 explicit AssumptionPrinterPass(raw_ostream &OS) : OS(OS) {}
205
207};
208
209/// An immutable pass that tracks lazily created \c AssumptionCache
210/// objects.
211///
212/// This is essentially a workaround for the legacy pass manager's weaknesses
213/// which associates each assumption cache with Function and clears it if the
214/// function is deleted. The nature of the AssumptionCache is that it is not
215/// invalidated by any changes to the function body and so this is sufficient
216/// to be conservatively correct.
218 /// A callback value handle applied to function objects, which we use to
219 /// delete our cache of intrinsics for a function when it is deleted.
220 class LLVM_ABI FunctionCallbackVH final : public CallbackVH {
222
223 void deleted() override;
224
225 public:
226 using DMI = DenseMapInfo<Value *>;
227
228 FunctionCallbackVH(Value *V, AssumptionCacheTracker *ACT = nullptr)
229 : CallbackVH(V), ACT(ACT) {}
230 };
231
232 friend FunctionCallbackVH;
233
234 using FunctionCallsMap =
236 FunctionCallbackVH::DMI>;
237
238 FunctionCallsMap AssumptionCaches;
239
240public:
241 /// Get the cached assumptions for a function.
242 ///
243 /// If no assumptions are cached, this will scan the function. Otherwise, the
244 /// existing cache will be returned.
246
247 /// Return the cached assumptions for a function if it has already been
248 /// scanned. Otherwise return nullptr.
250
253
254 void releaseMemory() override {
256 AssumptionCaches.shrink_and_clear();
257 }
258
259 void verifyAnalysis() const override;
260
261 bool doFinalization(Module &) override {
263 return false;
264 }
265
266 static char ID; // Pass identification, replacement for typeid
267};
268
269template<> struct simplify_type<AssumptionCache::ResultElem> {
270 using SimpleType = Value *;
271
273 return Val;
274 }
275};
276template<> struct simplify_type<const AssumptionCache::ResultElem> {
277 using SimpleType = /*const*/ Value *;
278
280 return Val;
281 }
282};
283
284} // end namespace llvm
285
286#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.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
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