LLVM 24.0.0git
Loads.h
Go to the documentation of this file.
1//===- Loads.h - Local load analysis --------------------------------------===//
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 declares simple local analyses for load instructions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ANALYSIS_LOADS_H
14#define LLVM_ANALYSIS_LOADS_H
15
16#include "llvm/ADT/APInt.h"
18#include "llvm/IR/BasicBlock.h"
22#include <optional>
23
24namespace llvm {
25
26class BatchAAResults;
27class AssumptionCache;
28class DataLayout;
29class DominatorTree;
30class Instruction;
31class IRBuilderBase;
32class LoadInst;
34class Loop;
35class MemoryLocation;
36class SCEV;
37class ScalarEvolution;
38class SCEVPredicate;
39class StoreInst;
40template <typename T> class SmallVectorImpl;
41
42/// Returns true if V is always a dereferenceable pointer with alignment
43/// greater or equal than requested. If the context instruction is specified
44/// performs context-sensitive analysis and returns true if the pointer is
45/// dereferenceable at the specified instruction.
46/// If \p IgnoreFree is set, ignore potential frees of the object.
48 Align Alignment,
49 const SimplifyQuery &Q,
50 bool IgnoreFree = false);
51
52/// Returns true if V is always dereferenceable for Size byte with alignment
53/// greater or equal than requested. If the context instruction is specified
54/// performs context-sensitive analysis and returns true if the pointer is
55/// dereferenceable at the specified instruction.
56/// If \p IgnoreFree is set, ignore potential frees of the object.
58 Align Alignment,
59 const APInt &Size,
60 const SimplifyQuery &Q,
61 bool IgnoreFree = false);
62
63/// Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
65 const SimplifyQuery &Q,
66 bool IgnoreFree = false);
67
68/// Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
70 const SimplifyQuery &Q,
71 bool IgnoreFree = false);
72
73/// Return true if we know that executing a load from this value cannot trap.
74///
75/// If SQ.CtxI is specified this method performs context-sensitive analysis
76/// and returns true if it is safe to load immediately before SQ.CtxI.
77///
78/// If it is not obviously safe to load from the specified pointer, we do a
79/// quick local scan of the basic block containing SQ.CtxI, to determine if
80/// the address is already accessed.
82 const APInt &Size,
83 const SimplifyQuery &SQ,
84 bool IgnoreFree = false);
85
86/// Return true if we can prove that the given load (which is assumed to be
87/// within the specified loop) would access only dereferenceable memory, and
88/// be properly aligned on every iteration of the specified loop regardless of
89/// its placement within the loop. (i.e. does not require predication beyond
90/// that required by the header itself and could be hoisted into the header
91/// if desired.) This is more powerful than the variants above when the
92/// address loaded from is analyzeable by SCEV.
95 AssumptionCache *AC = nullptr,
96 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
97
98/// Overload for isDereferenceableAndAlignedInLoop taking the pointer and access
99/// size directly as SCEVs.
101 const SCEV *PtrSCEV, Align Alignment, const SCEV *EltSizeSCEV, Loop *L,
102 ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC = nullptr,
103 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
104
105/// Returns true if the loop contains read-only memory accesses and doesn't
106/// throw. Puts loads that may fault into \p NonDereferenceableAndAlignedLoads.
107LLVM_ABI bool
109 AssumptionCache *AC,
110 SmallVectorImpl<LoadInst *> &NonDereferenceableAndAlignedLoads,
111 SmallVectorImpl<const SCEVPredicate *> *Predicates = nullptr);
112
113/// Return true if we know that executing a load from this value cannot trap.
114///
115/// If SQ.CtxI is specified this method performs context-sensitive analysis
116/// and returns true if it is safe to load immediately before SQ.CtxI.
117///
118/// If it is not obviously safe to load from the specified pointer, we do a
119/// quick local scan of the basic block containing SQ.CtxI, to determine if
120/// the address is already accessed.
122 const SimplifyQuery &SQ,
123 bool IgnoreFree = false);
124
125/// Return true if speculation of the given load must be suppressed to avoid
126/// ordering or interfering with an active sanitizer. If not suppressed,
127/// dereferenceability and alignment must be proven separately. Note: This
128/// is only needed for raw reasoning; if you use the interface below
129/// (isSafeToSpeculativelyExecute), this is handled internally.
131
132/// The default number of maximum instructions to scan in the block, used by
133/// FindAvailableLoadedValue().
135
136/// Scan backwards to see if we have the value of the given load available
137/// locally within a small number of instructions.
138///
139/// You can use this function to scan across multiple blocks: after you call
140/// this function, if ScanFrom points at the beginning of the block, it's safe
141/// to continue scanning the predecessors.
142///
143/// Note that performing load CSE requires special care to make sure the
144/// metadata is set appropriately. In particular, aliasing metadata needs
145/// to be merged. (This doesn't matter for store-to-load forwarding because
146/// the only relevant load gets deleted.)
147///
148/// \param Load The load we want to replace.
149/// \param ScanBB The basic block to scan.
150/// \param [in,out] ScanFrom The location to start scanning from. When this
151/// function returns, it points at the last instruction scanned.
152/// \param MaxInstsToScan The maximum number of instructions to scan. If this
153/// is zero, the whole block will be scanned.
154/// \param AA Optional pointer to alias analysis, to make the scan more
155/// precise.
156/// \param [out] IsLoadCSE Whether the returned value is a load from the same
157/// location in memory, as opposed to the value operand of a store.
158///
159/// \returns The found value, or nullptr if no value is found.
161 LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom,
162 unsigned MaxInstsToScan = DefMaxInstsToScan, BatchAAResults *AA = nullptr,
163 bool *IsLoadCSE = nullptr, unsigned *NumScanedInst = nullptr);
164
165/// This overload provides a more efficient implementation of
166/// FindAvailableLoadedValue() for the case where we are not interested in
167/// finding the closest clobbering instruction if no available load is found.
168/// This overload cannot be used to scan across multiple blocks.
171 unsigned MaxInstsToScan = DefMaxInstsToScan);
172
173/// Check whether \p SI, which may alias \p MemLoc, can be safely skipped.
174/// This is possible when \p SI does only MustAlias or NoAlias \p MemLoc (no
175/// partial overlap possible), and it stores the value \p MemLoc currently
176/// holds (loaded before the store and not modified in between).
178 const MemoryLocation &MemLoc,
179 Align MemLocAlign,
181 unsigned ScanLimit);
182
183/// Scan backwards to see if we have the value of the given pointer available
184/// locally within a small number of instructions.
185///
186/// You can use this function to scan across multiple blocks: after you call
187/// this function, if ScanFrom points at the beginning of the block, it's safe
188/// to continue scanning the predecessors.
189///
190/// \param Loc The location we want the load and store to originate from.
191/// \param AccessTy The access type of the pointer.
192/// \param AccessProps The properties of the load we want to replace.
193/// \param ScanBB The basic block to scan.
194/// \param [in,out] ScanFrom The location to start scanning from. When this
195/// function returns, it points at the last instruction scanned.
196/// \param MaxInstsToScan The maximum number of instructions to scan. If this
197/// is zero, the whole block will be scanned.
198/// \param AA Optional pointer to alias analysis, to make the scan more
199/// precise.
200/// \param [out] IsLoadCSE Whether the returned value is a load from the same
201/// location in memory, as opposed to the value operand of a store.
202///
203/// \returns The found value, or nullptr if no value is found.
206 const LoadStoreInstProperties &AccessProps,
207 BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom,
208 unsigned MaxInstsToScan, BatchAAResults *AA,
209 bool *IsLoadCSE, unsigned *NumScanedInst);
210
211/// Returns true if a pointer value \p From can be replaced with another pointer
212/// value \To if they are deemed equal through some means (e.g. information from
213/// conditions).
214/// NOTE: The current implementation allows replacement in Icmp and PtrToInt
215/// instructions, as well as when we are replacing with a null pointer.
216/// Additionally it also allows replacement of pointers when both pointers have
217/// the same underlying object.
218LLVM_ABI bool canReplacePointersIfEqual(const Value *From, const Value *To,
219 const DataLayout &DL);
220LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To,
221 const DataLayout &DL);
222
223/// Linear expression BasePtr + Index * Scale + Offset.
224/// Index, Scale and Offset all have the same bit width, which matches the
225/// pointer index size of BasePtr.
226/// Index may be nullptr if Scale is 0.
237
238/// Decompose a pointer into a linear expression. This may look through
239/// multiple GEPs.
240LLVM_ABI LinearExpression decomposeLinearExpression(const DataLayout &DL,
241 Value *Ptr);
242
243/// A helper to analyze a load from a constant global.
244///
245/// Provides an API that allows canonicalizing the indices in generated code to
246/// allow comparing indexes with known indices, and to access the global
247/// elements with canonical index values at compile time.
248///
249/// Currently the analysis requires constant offsets to the global to be less
250/// than the stride, so the global is always accessed with 0 as the first valid
251/// index.
252///
253/// Canonicalization masks the index values to handle wrapping. `getElementAt`
254/// takes canonical indices, instead of index values that may wrap around to
255/// access the global.
256class ConstGlobalLoad {
257 LinearExpression Expr;
258 uint64_t ElementCount;
259 Type *EltTy;
260
261 ConstGlobalLoad(const DataLayout &DL, LinearExpression Expr,
262 uint64_t ArrayElementCount, GlobalVariable *GV, Type *EltTy)
263 : Expr(std::move(Expr)), ElementCount(ArrayElementCount), EltTy(EltTy) {}
264
265public:
266 /// Analyze a load instruction to a linear expression that loads from a
267 /// constant global.
268 LLVM_ABI static std::optional<ConstGlobalLoad> fromLoadInst(LoadInst *LI);
269
270 /// Get the element of the global that the load instruction reads for the
271 /// given canonical index.
272 ///
273 /// This uses `ConstantFoldLoadFromConst` and returns null under the same
274 /// circumstances that `ConstantFoldLoadFromConst` returns null. (e.g. when
275 /// the value being loaded cannot be reinterpreted as the load type)
277
278 /// Number of elements that can be read from the global.
279 uint64_t getElementCount() const { return ElementCount; }
280
281 /// Build the canonicalized index that will index the global without
282 /// wrapping.
283 ///
284 /// When the offset calculations do not wrap, this returns the original index
285 /// value as-is.
286 ///
287 /// Otherwise this masks the index value as necessary to convert it into the
288 /// canonical index.
289 ///
290 /// After canonicalization, the index values can be compared against known
291 /// index values of global elements.
292 ///
293 /// When you don't need to compare canonical indices and just want to index
294 /// the table, `getIndex` can be used to get original index value.
296
297 /// Returns the index value of the linear expression that indexes the global.
298 ///
299 /// This can't be used to compare known canonical index values with runtime
300 /// values of the index, use `buildCanonicalIndex` for that.
301 Value *getIndex() const { return Expr.Index; }
302};
303}
304
305#endif
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_ABI
Definition Compiler.h:211
Class for arbitrary precision integers.
Definition APInt.h:78
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
LLVM_ABI Value * buildCanonicalIndex(IRBuilderBase &Builder) const
Build the canonicalized index that will index the global without wrapping.
Definition Loads.cpp:1138
static LLVM_ABI std::optional< ConstGlobalLoad > fromLoadInst(LoadInst *LI)
Analyze a load instruction to a linear expression that loads from a constant global.
Definition Loads.cpp:1073
Value * getIndex() const
Returns the index value of the linear expression that indexes the global.
Definition Loads.h:301
uint64_t getElementCount() const
Number of elements that can be read from the global.
Definition Loads.h:279
LLVM_ABI Constant * getElementAt(uint64_t Idx) const
Get the element of the global that the load instruction reads for the given canonical index.
Definition Loads.cpp:1130
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags all()
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
An instruction for reading from memory.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Representation for a specific memory location.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
This class represents an analyzed expression in the program.
The main scalar evolution driver.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
An instruction for storing to memory.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
Abstract Attribute helper functions.
Definition Attributor.h:166
This is an optimization pass for GlobalISel generic memory operations.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool isStorePreservingMemoryLocation(const StoreInst *SI, const MemoryLocation &MemLoc, Align MemLocAlign, BatchAAResults &AA, unsigned ScanLimit)
Check whether SI, which may alias MemLoc, can be safely skipped.
Definition Loads.cpp:846
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:453
LLVM_ABI Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition Loads.cpp:555
LLVM_ABI bool canReplacePointersInUseIfEqual(const Use &U, const Value *To, const DataLayout &DL)
Definition Loads.cpp:927
LLVM_ABI bool canReplacePointersIfEqual(const Value *From, const Value *To, const DataLayout &DL)
Returns true if a pointer value From can be replaced with another pointer value \To if they are deeme...
Definition Loads.cpp:947
LLVM_ABI LinearExpression decomposeLinearExpression(const DataLayout &DL, Value *Ptr)
Decompose a pointer into a linear expression.
Definition Loads.cpp:979
LLVM_ABI cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:457
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:247
constexpr unsigned BitWidth
LLVM_ABI bool isReadOnlyLoop(Loop *L, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, SmallVectorImpl< LoadInst * > &NonDereferenceableAndAlignedLoads, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns true if the loop contains read-only memory accesses and doesn't throw.
Definition Loads.cpp:957
LLVM_ABI bool isDereferenceablePointer(const Value *V, Type *Ty, const SimplifyQuery &Q, bool IgnoreFree=false)
Equivalent to isDereferenceableAndAlignedPointer with an alignment of 1.
Definition Loads.cpp:267
LLVM_ABI Value * findAvailablePtrLoadStore(const MemoryLocation &Loc, Type *AccessTy, const LoadStoreInstProperties &AccessProps, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan, BatchAAResults *AA, bool *IsLoadCSE, unsigned *NumScanedInst)
Scan backwards to see if we have the value of the given pointer available locally within a small numb...
Definition Loads.cpp:716
LLVM_ABI bool isDereferenceableAndAlignedInLoop(LoadInst *LI, Loop *L, ScalarEvolution &SE, DominatorTree &DT, AssumptionCache *AC=nullptr, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Return true if we can prove that the given load (which is assumed to be within the specified loop) wo...
Definition Loads.cpp:307
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Linear expression BasePtr + Index * Scale + Offset.
Definition Loads.h:227
LinearExpression(Value *BasePtr, unsigned BitWidth)
Definition Loads.h:234
GEPNoWrapFlags Flags
Definition Loads.h:232
A structure representing the properties of a load or store instruction.