LLVM 20.0.0git
GVN.h
Go to the documentation of this file.
1//===- GVN.h - Eliminate redundant values and loads -------------*- 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/// \file
9/// This file provides the interface for LLVM's Global Value Numbering pass
10/// which eliminates fully redundant instructions. It also does somewhat Ad-Hoc
11/// PRE and dead load elimination.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_TRANSFORMS_SCALAR_GVN_H
16#define LLVM_TRANSFORMS_SCALAR_GVN_H
17
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/SetVector.h"
22#include "llvm/IR/Dominators.h"
23#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/PassManager.h"
25#include "llvm/IR/ValueHandle.h"
28#include <cstdint>
29#include <optional>
30#include <utility>
31#include <vector>
32
33namespace llvm {
34
35class AAResults;
36class AssumeInst;
37class AssumptionCache;
38class BasicBlock;
39class BranchInst;
40class CallInst;
41class ExtractValueInst;
42class Function;
43class FunctionPass;
44class GetElementPtrInst;
45class ImplicitControlFlowTracking;
46class LoadInst;
47class LoopInfo;
48class MemDepResult;
49class MemoryDependenceResults;
50class MemorySSA;
51class MemorySSAUpdater;
52class NonLocalDepResult;
53class OptimizationRemarkEmitter;
54class PHINode;
55class TargetLibraryInfo;
56class Value;
57/// A private "module" namespace for types and utilities used by GVN. These
58/// are implementation details and should not be used by clients.
60
61struct AvailableValue;
63class GVNLegacyPass;
64
65} // end namespace gvn
66
67/// A set of parameters to control various transforms performed by GVN pass.
68// Each of the optional boolean parameters can be set to:
69/// true - enabling the transformation.
70/// false - disabling the transformation.
71/// None - relying on a global default.
72/// Intended use is to create a default object, modify parameters with
73/// additional setters and then pass it to GVN.
74struct GVNOptions {
75 std::optional<bool> AllowPRE;
76 std::optional<bool> AllowLoadPRE;
77 std::optional<bool> AllowLoadInLoopPRE;
78 std::optional<bool> AllowLoadPRESplitBackedge;
79 std::optional<bool> AllowMemDep;
80
81 GVNOptions() = default;
82
83 /// Enables or disables PRE in GVN.
84 GVNOptions &setPRE(bool PRE) {
85 AllowPRE = PRE;
86 return *this;
87 }
88
89 /// Enables or disables PRE of loads in GVN.
90 GVNOptions &setLoadPRE(bool LoadPRE) {
91 AllowLoadPRE = LoadPRE;
92 return *this;
93 }
94
95 GVNOptions &setLoadInLoopPRE(bool LoadInLoopPRE) {
96 AllowLoadInLoopPRE = LoadInLoopPRE;
97 return *this;
98 }
99
100 /// Enables or disables PRE of loads in GVN.
101 GVNOptions &setLoadPRESplitBackedge(bool LoadPRESplitBackedge) {
102 AllowLoadPRESplitBackedge = LoadPRESplitBackedge;
103 return *this;
104 }
105
106 /// Enables or disables use of MemDepAnalysis.
107 GVNOptions &setMemDep(bool MemDep) {
108 AllowMemDep = MemDep;
109 return *this;
110 }
111};
112
113/// The core GVN pass object.
114///
115/// FIXME: We should have a good summary of the GVN algorithm implemented by
116/// this particular pass here.
117class GVNPass : public PassInfoMixin<GVNPass> {
118 GVNOptions Options;
119
120public:
121 struct Expression;
122
124
125 /// Run the pass over the function.
126 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
127
128 void printPipeline(raw_ostream &OS,
129 function_ref<StringRef(StringRef)> MapClassName2PassName);
130
131 /// This removes the specified instruction from
132 /// our various maps and marks it for deletion.
134 VN.erase(I);
135 InstrsToErase.push_back(I);
136 }
137
138 DominatorTree &getDominatorTree() const { return *DT; }
140 MemoryDependenceResults &getMemDep() const { return *MD; }
141
142 bool isPREEnabled() const;
143 bool isLoadPREEnabled() const;
144 bool isLoadInLoopPREEnabled() const;
146 bool isMemDepEnabled() const;
147
148 /// This class holds the mapping between values and value numbers. It is used
149 /// as an efficient mechanism to determine the expression-wise equivalence of
150 /// two values.
152 DenseMap<Value *, uint32_t> valueNumbering;
153 DenseMap<Expression, uint32_t> expressionNumbering;
154
155 // Expressions is the vector of Expression. ExprIdx is the mapping from
156 // value number to the index of Expression in Expressions. We use it
157 // instead of a DenseMap because filling such mapping is faster than
158 // filling a DenseMap and the compile time is a little better.
159 uint32_t nextExprNumber = 0;
160
161 std::vector<Expression> Expressions;
162 std::vector<uint32_t> ExprIdx;
163
164 // Value number to PHINode mapping. Used for phi-translate in scalarpre.
166
167 // Cache for phi-translate in scalarpre.
168 using PhiTranslateMap =
170 PhiTranslateMap PhiTranslateTable;
171
172 AAResults *AA = nullptr;
173 MemoryDependenceResults *MD = nullptr;
174 DominatorTree *DT = nullptr;
175
176 uint32_t nextValueNumber = 1;
177
178 Expression createExpr(Instruction *I);
179 Expression createCmpExpr(unsigned Opcode, CmpInst::Predicate Predicate,
180 Value *LHS, Value *RHS);
181 Expression createExtractvalueExpr(ExtractValueInst *EI);
182 Expression createGEPExpr(GetElementPtrInst *GEP);
183 uint32_t lookupOrAddCall(CallInst *C);
184 uint32_t phiTranslateImpl(const BasicBlock *BB, const BasicBlock *PhiBlock,
185 uint32_t Num, GVNPass &Gvn);
186 bool areCallValsEqual(uint32_t Num, uint32_t NewNum, const BasicBlock *Pred,
187 const BasicBlock *PhiBlock, GVNPass &Gvn);
188 std::pair<uint32_t, bool> assignExpNewValueNum(Expression &exp);
189 bool areAllValsInBB(uint32_t num, const BasicBlock *BB, GVNPass &Gvn);
190
191 public:
197
199 uint32_t lookup(Value *V, bool Verify = true) const;
200 uint32_t lookupOrAddCmp(unsigned Opcode, CmpInst::Predicate Pred,
201 Value *LHS, Value *RHS);
202 uint32_t phiTranslate(const BasicBlock *BB, const BasicBlock *PhiBlock,
203 uint32_t Num, GVNPass &Gvn);
204 void eraseTranslateCacheEntry(uint32_t Num, const BasicBlock &CurrBlock);
205 bool exists(Value *V) const;
206 void add(Value *V, uint32_t num);
207 void clear();
208 void erase(Value *v);
209 void setAliasAnalysis(AAResults *A) { AA = A; }
210 AAResults *getAliasAnalysis() const { return AA; }
212 void setDomTree(DominatorTree *D) { DT = D; }
213 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
214 void verifyRemoved(const Value *) const;
215 };
216
217private:
218 friend class gvn::GVNLegacyPass;
219 friend struct DenseMapInfo<Expression>;
220
221 MemoryDependenceResults *MD = nullptr;
222 DominatorTree *DT = nullptr;
223 const TargetLibraryInfo *TLI = nullptr;
224 AssumptionCache *AC = nullptr;
225 SetVector<BasicBlock *> DeadBlocks;
226 OptimizationRemarkEmitter *ORE = nullptr;
227 ImplicitControlFlowTracking *ICF = nullptr;
228 LoopInfo *LI = nullptr;
229 MemorySSAUpdater *MSSAU = nullptr;
230
231 ValueTable VN;
232
233 /// A mapping from value numbers to lists of Value*'s that
234 /// have that value number. Use findLeader to query it.
235 class LeaderMap {
236 public:
240 };
241
242 private:
243 struct LeaderListNode {
244 LeaderTableEntry Entry;
245 LeaderListNode *Next;
246 };
248 BumpPtrAllocator TableAllocator;
249
250 public:
252 const LeaderListNode *Current;
253
254 public:
255 using iterator_category = std::forward_iterator_tag;
257 using difference_type = std::ptrdiff_t;
260
261 leader_iterator(const LeaderListNode *C) : Current(C) {}
263 assert(Current && "Dereferenced end of leader list!");
264 Current = Current->Next;
265 return *this;
266 }
267 bool operator==(const leader_iterator &Other) const {
268 return Current == Other.Current;
269 }
270 bool operator!=(const leader_iterator &Other) const {
271 return Current != Other.Current;
272 }
273 reference operator*() const { return Current->Entry; }
274 };
275
277 auto I = NumToLeaders.find(N);
278 if (I == NumToLeaders.end()) {
279 return iterator_range(leader_iterator(nullptr),
280 leader_iterator(nullptr));
281 }
282
283 return iterator_range(leader_iterator(&I->second),
284 leader_iterator(nullptr));
285 }
286
287 void insert(uint32_t N, Value *V, const BasicBlock *BB);
288 void erase(uint32_t N, Instruction *I, const BasicBlock *BB);
289 void verifyRemoved(const Value *Inst) const;
290 void clear() {
291 NumToLeaders.clear();
292 TableAllocator.Reset();
293 }
294 };
295 LeaderMap LeaderTable;
296
297 // Block-local map of equivalent values to their leader, does not
298 // propagate to any successors. Entries added mid-block are applied
299 // to the remaining instructions in the block.
300 SmallMapVector<Value *, Value *, 4> ReplaceOperandsWithMap;
301 SmallVector<Instruction *, 8> InstrsToErase;
302
303 // Map the block to reversed postorder traversal number. It is used to
304 // find back edge easily.
305 DenseMap<AssertingVH<BasicBlock>, uint32_t> BlockRPONumber;
306
307 // This is set 'true' initially and also when new blocks have been added to
308 // the function being analyzed. This boolean is used to control the updating
309 // of BlockRPONumber prior to accessing the contents of BlockRPONumber.
310 bool InvalidBlockRPONumbers = true;
311
312 using LoadDepVect = SmallVector<NonLocalDepResult, 64>;
313 using AvailValInBlkVect = SmallVector<gvn::AvailableValueInBlock, 64>;
314 using UnavailBlkVect = SmallVector<BasicBlock *, 64>;
315
316 bool runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
317 const TargetLibraryInfo &RunTLI, AAResults &RunAA,
318 MemoryDependenceResults *RunMD, LoopInfo &LI,
319 OptimizationRemarkEmitter *ORE, MemorySSA *MSSA = nullptr);
320
321 // List of critical edges to be split between iterations.
322 SmallVector<std::pair<Instruction *, unsigned>, 4> toSplit;
323
324 // Helper functions of redundant load elimination
325 bool processLoad(LoadInst *L);
326 bool processNonLocalLoad(LoadInst *L);
327 bool processAssumeIntrinsic(AssumeInst *II);
328
329 /// Given a local dependency (Def or Clobber) determine if a value is
330 /// available for the load.
331 std::optional<gvn::AvailableValue>
332 AnalyzeLoadAvailability(LoadInst *Load, MemDepResult DepInfo, Value *Address);
333
334 /// Given a list of non-local dependencies, determine if a value is
335 /// available for the load in each specified block. If it is, add it to
336 /// ValuesPerBlock. If not, add it to UnavailableBlocks.
337 void AnalyzeLoadAvailability(LoadInst *Load, LoadDepVect &Deps,
338 AvailValInBlkVect &ValuesPerBlock,
339 UnavailBlkVect &UnavailableBlocks);
340
341 /// Given a critical edge from Pred to LoadBB, find a load instruction
342 /// which is identical to Load from another successor of Pred.
343 LoadInst *findLoadToHoistIntoPred(BasicBlock *Pred, BasicBlock *LoadBB,
344 LoadInst *Load);
345
346 bool PerformLoadPRE(LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
347 UnavailBlkVect &UnavailableBlocks);
348
349 /// Try to replace a load which executes on each loop iteraiton with Phi
350 /// translation of load in preheader and load(s) in conditionally executed
351 /// paths.
352 bool performLoopLoadPRE(LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
353 UnavailBlkVect &UnavailableBlocks);
354
355 /// Eliminates partially redundant \p Load, replacing it with \p
356 /// AvailableLoads (connected by Phis if needed).
357 void eliminatePartiallyRedundantLoad(
358 LoadInst *Load, AvailValInBlkVect &ValuesPerBlock,
359 MapVector<BasicBlock *, Value *> &AvailableLoads,
360 MapVector<BasicBlock *, LoadInst *> *CriticalEdgePredAndLoad);
361
362 // Other helper routines
363 bool processInstruction(Instruction *I);
364 bool processBlock(BasicBlock *BB);
365 void dump(DenseMap<uint32_t, Value *> &d) const;
366 bool iterateOnFunction(Function &F);
367 bool performPRE(Function &F);
368 bool performScalarPRE(Instruction *I);
369 bool performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
370 BasicBlock *Curr, unsigned int ValNo);
371 Value *findLeader(const BasicBlock *BB, uint32_t num);
372 void cleanupGlobalSets();
373 void removeInstruction(Instruction *I);
374 void verifyRemoved(const Instruction *I) const;
375 bool splitCriticalEdges();
376 BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
377 bool replaceOperandsForInBlockEquality(Instruction *I) const;
378 bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root,
379 bool DominatesByEdge);
380 bool processFoldableCondBr(BranchInst *BI);
381 void addDeadBlock(BasicBlock *BB);
382 void assignValNumForDeadCode();
383 void assignBlockRPONumber(Function &F);
384};
385
386/// Create a legacy GVN pass. This also allows parameterizing whether or not
387/// MemDep is enabled.
388FunctionPass *createGVNPass(bool NoMemDepAnalysis = false);
389
390/// A simple and fast domtree-based GVN pass to hoist common expressions
391/// from sibling branches.
392struct GVNHoistPass : PassInfoMixin<GVNHoistPass> {
393 /// Run the pass over the function.
395};
396
397/// Uses an "inverted" value numbering to decide the similarity of
398/// expressions and sinks similar expressions into successors.
399struct GVNSinkPass : PassInfoMixin<GVNSinkPass> {
400 /// Run the pass over the function.
402};
403
404} // end namespace llvm
405
406#endif // LLVM_TRANSFORMS_SCALAR_GVN_H
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_LIBRARY_VISIBILITY
Definition: Compiler.h:131
This file defines the DenseMap class.
early cse Early CSE w MemorySSA
Definition: EarlyCSE.cpp:1948
Hexagon Common GEP
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
ppc ctr loops PowerPC CTR Loops Verify
This header defines various interfaces for pass management in LLVM.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
Value * RHS
Value * LHS
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:66
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it,...
Definition: Allocator.h:123
This class represents a function call, abstracting a target machine's calling convention.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:757
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
iterator end()
Definition: DenseMap.h:84
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
This instruction extracts a struct member or array element value from an aggregate value.
std::forward_iterator_tag iterator_category
Definition: GVN.h:255
bool operator==(const leader_iterator &Other) const
Definition: GVN.h:267
bool operator!=(const leader_iterator &Other) const
Definition: GVN.h:270
leader_iterator(const LeaderListNode *C)
Definition: GVN.h:261
leader_iterator & operator++()
Definition: GVN.h:262
This class holds the mapping between values and value numbers.
Definition: GVN.h:151
ValueTable(ValueTable &&Arg)
uint32_t lookupOrAddCmp(unsigned Opcode, CmpInst::Predicate Pred, Value *LHS, Value *RHS)
Returns the value number of the given comparison, assigning it a new number if it did not have one be...
Definition: GVN.cpp:693
uint32_t getNextUnusedValueNumber()
Definition: GVN.h:213
uint32_t lookupOrAdd(Value *V)
lookup_or_add - Returns the value number for the specified value, assigning it a new number if it did...
Definition: GVN.cpp:601
uint32_t lookup(Value *V, bool Verify=true) const
Returns the value number of the specified value.
Definition: GVN.cpp:680
ValueTable & operator=(const ValueTable &Arg)
void setAliasAnalysis(AAResults *A)
Definition: GVN.h:209
void clear()
Remove all entries from the ValueTable.
Definition: GVN.cpp:701
bool exists(Value *V) const
Returns true if a value number exists for the specified value.
Definition: GVN.cpp:595
ValueTable(const ValueTable &Arg)
AAResults * getAliasAnalysis() const
Definition: GVN.h:210
uint32_t phiTranslate(const BasicBlock *BB, const BasicBlock *PhiBlock, uint32_t Num, GVNPass &Gvn)
Wrap phiTranslateImpl to provide caching functionality.
Definition: GVN.cpp:2276
void setMemDep(MemoryDependenceResults *M)
Definition: GVN.h:211
void erase(Value *v)
Remove a value from the value numbering.
Definition: GVN.cpp:713
void add(Value *V, uint32_t num)
add - Insert a value into the table with a specified value number.
Definition: GVN.cpp:464
void setDomTree(DominatorTree *D)
Definition: GVN.h:212
void eraseTranslateCacheEntry(uint32_t Num, const BasicBlock &CurrBlock)
Erase stale entry from phiTranslate cache so phiTranslate can be computed again.
Definition: GVN.cpp:2379
void verifyRemoved(const Value *) const
verifyRemoved - Verify that the value is removed from all internal data structures.
Definition: GVN.cpp:723
The core GVN pass object.
Definition: GVN.h:117
bool isPREEnabled() const
Definition: GVN.cpp:795
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition: GVN.cpp:816
AAResults * getAliasAnalysis() const
Definition: GVN.h:139
bool isLoadPREEnabled() const
Definition: GVN.cpp:799
GVNPass(GVNOptions Options={})
Definition: GVN.h:123
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition: GVN.cpp:843
DominatorTree & getDominatorTree() const
Definition: GVN.h:138
bool isLoadInLoopPREEnabled() const
Definition: GVN.cpp:803
bool isLoadPRESplitBackedgeEnabled() const
Definition: GVN.cpp:807
void markInstructionForDeletion(Instruction *I)
This removes the specified instruction from our various maps and marks it for deletion.
Definition: GVN.h:133
bool isMemDepEnabled() const
Definition: GVN.cpp:812
MemoryDependenceResults & getMemDep() const
Definition: GVN.h:140
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:915
This class allows to keep track on instructions with implicit control flow.
Provides a lazy, caching interface for making common memory aliasing information queries,...
The optimization diagnostic interface.
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
A vector that has set insertion semantics.
Definition: SetVector.h:57
void push_back(const T &Elt)
Definition: SmallVector.h:427
Provides information about what library functions are available for the current target.
LLVM Value Representation.
Definition: Value.h:74
A range adaptor for a pair of iterators.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:71
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
Definition: PassManager.h:542
@ Other
Any other memory.
FunctionPass * createGVNPass(bool NoMemDepAnalysis=false)
Create a legacy GVN pass.
Definition: GVN.cpp:3396
#define N
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:52
A simple and fast domtree-based GVN pass to hoist common expressions from sibling branches.
Definition: GVN.h:392
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition: GVNHoist.cpp:1204
A set of parameters to control various transforms performed by GVN pass.
Definition: GVN.h:74
GVNOptions & setLoadPRE(bool LoadPRE)
Enables or disables PRE of loads in GVN.
Definition: GVN.h:90
std::optional< bool > AllowLoadPRESplitBackedge
Definition: GVN.h:78
GVNOptions & setPRE(bool PRE)
Enables or disables PRE in GVN.
Definition: GVN.h:84
GVNOptions & setLoadInLoopPRE(bool LoadInLoopPRE)
Definition: GVN.h:95
std::optional< bool > AllowPRE
Definition: GVN.h:75
std::optional< bool > AllowLoadInLoopPRE
Definition: GVN.h:77
std::optional< bool > AllowMemDep
Definition: GVN.h:79
GVNOptions & setMemDep(bool MemDep)
Enables or disables use of MemDepAnalysis.
Definition: GVN.h:107
std::optional< bool > AllowLoadPRE
Definition: GVN.h:76
GVNOptions & setLoadPRESplitBackedge(bool LoadPRESplitBackedge)
Enables or disables PRE of loads in GVN.
Definition: GVN.h:101
GVNOptions()=default
Uses an "inverted" value numbering to decide the similarity of expressions and sinks similar expressi...
Definition: GVN.h:399
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
Definition: GVNSink.cpp:940
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:69
Represents an AvailableValue which can be rematerialized at the end of the associated BasicBlock.
Definition: GVN.cpp:288
Represents a particular available value that we know how to materialize.
Definition: GVN.cpp:191