1 //===- GVN.h - Eliminate redundant values and loads -------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file provides the interface for LLVM's Global Value Numbering pass
11 /// which eliminates fully redundant instructions. It also does somewhat Ad-Hoc
12 /// PRE and dead load elimination.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_TRANSFORMS_SCALAR_GVN_H
17 #define LLVM_TRANSFORMS_SCALAR_GVN_H
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/AssumptionCache.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/IntrinsicInst.h"
29 #include "llvm/IR/PassManager.h"
32 class OptimizationRemarkEmitter;
34 /// A private "module" namespace for types and utilities used by GVN. These
35 /// are implementation details and should not be used by clients.
36 namespace gvn LLVM_LIBRARY_VISIBILITY {
37 struct AvailableValue;
38 struct AvailableValueInBlock;
42 /// The core GVN pass object.
44 /// FIXME: We should have a good summary of the GVN algorithm implemented by
45 /// this particular pass here.
46 class GVN : public PassInfoMixin<GVN> {
49 /// \brief Run the pass over the function.
50 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
52 /// This removes the specified instruction from
53 /// our various maps and marks it for deletion.
54 void markInstructionForDeletion(Instruction *I) {
56 InstrsToErase.push_back(I);
59 DominatorTree &getDominatorTree() const { return *DT; }
60 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
61 MemoryDependenceResults &getMemDep() const { return *MD; }
65 /// This class holds the mapping between values and value numbers. It is used
66 /// as an efficient mechanism to determine the expression-wise equivalence of
69 DenseMap<Value *, uint32_t> valueNumbering;
70 DenseMap<Expression, uint32_t> expressionNumbering;
72 // Expressions is the vector of Expression. ExprIdx is the mapping from
73 // value number to the index of Expression in Expressions. We use it
74 // instead of a DenseMap because filling such mapping is faster than
75 // filling a DenseMap and the compile time is a little better.
76 uint32_t nextExprNumber;
77 std::vector<Expression> Expressions;
78 std::vector<uint32_t> ExprIdx;
79 // Value number to PHINode mapping. Used for phi-translate in scalarpre.
80 DenseMap<uint32_t, PHINode *> NumberingPhi;
81 // Cache for phi-translate in scalarpre.
82 typedef DenseMap<std::pair<uint32_t, const BasicBlock *>, uint32_t>
84 PhiTranslateMap PhiTranslateTable;
85 // Map the block to reversed postorder traversal number. It is used to
86 // find back edge easily.
87 DenseMap<const BasicBlock *, uint32_t> BlockRPONumber;
90 MemoryDependenceResults *MD;
93 uint32_t nextValueNumber;
95 Expression createExpr(Instruction *I);
96 Expression createCmpExpr(unsigned Opcode, CmpInst::Predicate Predicate,
97 Value *LHS, Value *RHS);
98 Expression createExtractvalueExpr(ExtractValueInst *EI);
99 uint32_t lookupOrAddCall(CallInst *C);
100 uint32_t phiTranslateImpl(const BasicBlock *BB, const BasicBlock *PhiBlock,
101 uint32_t Num, GVN &Gvn);
102 std::pair<uint32_t, bool> assignExpNewValueNum(Expression &exp);
103 bool areAllValsInBB(uint32_t num, const BasicBlock *BB, GVN &Gvn);
107 ValueTable(const ValueTable &Arg);
108 ValueTable(ValueTable &&Arg);
111 uint32_t lookupOrAdd(Value *V);
112 uint32_t lookup(Value *V, bool Verify = true) const;
113 uint32_t lookupOrAddCmp(unsigned Opcode, CmpInst::Predicate Pred,
114 Value *LHS, Value *RHS);
115 uint32_t phiTranslate(const BasicBlock *BB, const BasicBlock *PhiBlock,
116 uint32_t Num, GVN &Gvn);
117 void assignBlockRPONumber(Function &F);
118 bool exists(Value *V) const;
119 void add(Value *V, uint32_t num);
121 void erase(Value *v);
122 void setAliasAnalysis(AliasAnalysis *A) { AA = A; }
123 AliasAnalysis *getAliasAnalysis() const { return AA; }
124 void setMemDep(MemoryDependenceResults *M) { MD = M; }
125 void setDomTree(DominatorTree *D) { DT = D; }
126 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
127 void verifyRemoved(const Value *) const;
131 friend class gvn::GVNLegacyPass;
132 friend struct DenseMapInfo<Expression>;
134 MemoryDependenceResults *MD;
136 const TargetLibraryInfo *TLI;
138 SetVector<BasicBlock *> DeadBlocks;
139 OptimizationRemarkEmitter *ORE;
143 /// A mapping from value numbers to lists of Value*'s that
144 /// have that value number. Use findLeader to query it.
145 struct LeaderTableEntry {
147 const BasicBlock *BB;
148 LeaderTableEntry *Next;
150 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
151 BumpPtrAllocator TableAllocator;
153 // Block-local map of equivalent values to their leader, does not
154 // propagate to any successors. Entries added mid-block are applied
155 // to the remaining instructions in the block.
156 SmallMapVector<llvm::Value *, llvm::Constant *, 4> ReplaceWithConstMap;
157 SmallVector<Instruction *, 8> InstrsToErase;
159 typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
160 typedef SmallVector<gvn::AvailableValueInBlock, 64> AvailValInBlkVect;
161 typedef SmallVector<BasicBlock *, 64> UnavailBlkVect;
163 bool runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
164 const TargetLibraryInfo &RunTLI, AAResults &RunAA,
165 MemoryDependenceResults *RunMD, LoopInfo *LI,
166 OptimizationRemarkEmitter *ORE);
168 /// Push a new Value to the LeaderTable onto the list for its value number.
169 void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
170 LeaderTableEntry &Curr = LeaderTable[N];
177 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
180 Node->Next = Curr.Next;
184 /// Scan the list of values corresponding to a given
185 /// value number, and remove the given instruction if encountered.
186 void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
187 LeaderTableEntry *Prev = nullptr;
188 LeaderTableEntry *Curr = &LeaderTable[N];
190 while (Curr && (Curr->Val != I || Curr->BB != BB)) {
199 Prev->Next = Curr->Next;
205 LeaderTableEntry *Next = Curr->Next;
206 Curr->Val = Next->Val;
208 Curr->Next = Next->Next;
213 // List of critical edges to be split between iterations.
214 SmallVector<std::pair<TerminatorInst *, unsigned>, 4> toSplit;
216 // Helper functions of redundant load elimination
217 bool processLoad(LoadInst *L);
218 bool processNonLocalLoad(LoadInst *L);
219 bool processAssumeIntrinsic(IntrinsicInst *II);
220 /// Given a local dependency (Def or Clobber) determine if a value is
221 /// available for the load. Returns true if an value is known to be
222 /// available and populates Res. Returns false otherwise.
223 bool AnalyzeLoadAvailability(LoadInst *LI, MemDepResult DepInfo,
224 Value *Address, gvn::AvailableValue &Res);
225 /// Given a list of non-local dependencies, determine if a value is
226 /// available for the load in each specified block. If it is, add it to
227 /// ValuesPerBlock. If not, add it to UnavailableBlocks.
228 void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
229 AvailValInBlkVect &ValuesPerBlock,
230 UnavailBlkVect &UnavailableBlocks);
231 bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
232 UnavailBlkVect &UnavailableBlocks);
234 // Other helper routines
235 bool processInstruction(Instruction *I);
236 bool processBlock(BasicBlock *BB);
237 void dump(DenseMap<uint32_t, Value *> &d);
238 bool iterateOnFunction(Function &F);
239 bool performPRE(Function &F);
240 bool performScalarPRE(Instruction *I);
241 bool performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
243 Value *findLeader(const BasicBlock *BB, uint32_t num);
244 void cleanupGlobalSets();
245 void verifyRemoved(const Instruction *I) const;
246 bool splitCriticalEdges();
247 BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
248 bool replaceOperandsWithConsts(Instruction *I) const;
249 bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root,
250 bool DominatesByEdge);
251 bool processFoldableCondBr(BranchInst *BI);
252 void addDeadBlock(BasicBlock *BB);
253 void assignValNumForDeadCode();
256 /// Create a legacy GVN pass. This also allows parameterizing whether or not
257 /// loads are eliminated by the pass.
258 FunctionPass *createGVNPass(bool NoLoads = false);
260 /// \brief A simple and fast domtree-based GVN pass to hoist common expressions
261 /// from sibling branches.
262 struct GVNHoistPass : PassInfoMixin<GVNHoistPass> {
263 /// \brief Run the pass over the function.
264 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
266 /// \brief Uses an "inverted" value numbering to decide the similarity of
267 /// expressions and sinks similar expressions into successors.
268 struct GVNSinkPass : PassInfoMixin<GVNSinkPass> {
269 /// \brief Run the pass over the function.
270 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);