blob: 8934279a2dfcb59a64d231a1a0dfa66ec6e9ffde [file] [log] [blame]
Chris Lattner71c7ec92002-08-30 20:28:10 +00001//===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
2//
3// This file implements a value numbering pass that value #'s load instructions.
4// To do this, it finds lexically identical load instructions, and uses alias
5// analysis to determine which loads are guaranteed to produce the same value.
6//
7// This pass builds off of another value numbering pass to implement value
8// numbering for non-load instructions. It uses Alias Analysis so that it can
9// disambiguate the load instructions. The more powerful these base analyses
10// are, the more powerful the resultant analysis will be.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/LoadValueNumbering.h"
15#include "llvm/Analysis/ValueNumbering.h"
16#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/Dominators.h"
Chris Lattnerf98d8d82003-02-26 19:27:35 +000018#include "llvm/Target/TargetData.h"
Chris Lattner71c7ec92002-08-30 20:28:10 +000019#include "llvm/Pass.h"
20#include "llvm/iMemory.h"
21#include "llvm/BasicBlock.h"
22#include "llvm/Support/CFG.h"
23#include <algorithm>
24#include <set>
25
26namespace {
27 // FIXME: This should not be a functionpass.
28 struct LoadVN : public FunctionPass, public ValueNumbering {
29
30 /// Pass Implementation stuff. This doesn't do any analysis.
31 ///
32 bool runOnFunction(Function &) { return false; }
33
34 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
35 /// and Alias Analysis.
36 ///
37 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
38
39 /// getEqualNumberNodes - Return nodes with the same value number as the
40 /// specified Value. This fills in the argument vector with any equal
41 /// values.
42 ///
43 virtual void getEqualNumberNodes(Value *V1,
44 std::vector<Value*> &RetVals) const;
45 private:
46 /// haveEqualValueNumber - Given two load instructions, determine if they
47 /// both produce the same value on every execution of the program, assuming
48 /// that their source operands always give the same value. This uses the
49 /// AliasAnalysis implementation to invalidate loads when stores or function
50 /// calls occur that could modify the value produced by the load.
51 ///
52 bool haveEqualValueNumber(LoadInst *LI, LoadInst *LI2, AliasAnalysis &AA,
53 DominatorSet &DomSetInfo) const;
54 };
55
56 // Register this pass...
57 RegisterOpt<LoadVN> X("load-vn", "Load Value Numbering");
58
59 // Declare that we implement the ValueNumbering interface
60 RegisterAnalysisGroup<ValueNumbering, LoadVN> Y;
61}
62
63
64
65Pass *createLoadValueNumberingPass() { return new LoadVN(); }
66
67
68/// getAnalysisUsage - Does not modify anything. It uses Value Numbering and
69/// Alias Analysis.
70///
71void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.setPreservesAll();
73 AU.addRequired<AliasAnalysis>();
74 AU.addRequired<ValueNumbering>();
75 AU.addRequired<DominatorSet>();
Chris Lattnerf98d8d82003-02-26 19:27:35 +000076 AU.addRequired<TargetData>();
Chris Lattner71c7ec92002-08-30 20:28:10 +000077}
78
79// getEqualNumberNodes - Return nodes with the same value number as the
80// specified Value. This fills in the argument vector with any equal values.
81//
82void LoadVN::getEqualNumberNodes(Value *V,
83 std::vector<Value*> &RetVals) const {
84
85 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
Chris Lattnerf98d8d82003-02-26 19:27:35 +000086 // If we have a load instruction, find all of the load instructions that use
Chris Lattner71c7ec92002-08-30 20:28:10 +000087 // the same source operand. We implement this recursively, because there
88 // could be a load of a load of a load that are all identical. We are
89 // guaranteed that this cannot be an infinite recursion because load
90 // instructions would have to pass through a PHI node in order for there to
91 // be a cycle. The PHI node would be handled by the else case here,
92 // breaking the infinite recursion.
93 //
94 std::vector<Value*> PointerSources;
95 getEqualNumberNodes(LI->getOperand(0), PointerSources);
96 PointerSources.push_back(LI->getOperand(0));
97
98 Function *F = LI->getParent()->getParent();
99
100 // Now that we know the set of equivalent source pointers for the load
101 // instruction, look to see if there are any load candiates that are
102 // identical.
103 //
104 std::vector<LoadInst*> CandidateLoads;
105 while (!PointerSources.empty()) {
106 Value *Source = PointerSources.back();
107 PointerSources.pop_back(); // Get a source pointer...
108
109 for (Value::use_iterator UI = Source->use_begin(), UE = Source->use_end();
110 UI != UE; ++UI)
111 if (LoadInst *Cand = dyn_cast<LoadInst>(*UI)) // Is a load of source?
112 if (Cand->getParent()->getParent() == F && // In the same function?
113 Cand != LI) // Not LI itself?
114 CandidateLoads.push_back(Cand); // Got one...
115 }
116
117 // Remove duplicates from the CandidateLoads list because alias analysis
118 // processing may be somewhat expensive and we don't want to do more work
119 // than neccesary.
120 //
121 std::sort(CandidateLoads.begin(), CandidateLoads.end());
122 CandidateLoads.erase(std::unique(CandidateLoads.begin(),
123 CandidateLoads.end()),
124 CandidateLoads.end());
125
126 // Get Alias Analysis...
127 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
128 DominatorSet &DomSetInfo = getAnalysis<DominatorSet>();
129
130 // Loop over all of the candindate loads. If they are not invalidated by
131 // stores or calls between execution of them and LI, then add them to
132 // RetVals.
133 for (unsigned i = 0, e = CandidateLoads.size(); i != e; ++i)
134 if (haveEqualValueNumber(LI, CandidateLoads[i], AA, DomSetInfo))
135 RetVals.push_back(CandidateLoads[i]);
136
137 } else {
138 // Make sure passmanager doesn't try to fulfill our request with ourself!
139 assert(&getAnalysis<ValueNumbering>() != (ValueNumbering*)this &&
140 "getAnalysis() returned this!");
141
142 // Not a load instruction? Just chain to the base value numbering
143 // implementation to satisfy the request...
144 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
145 }
146}
147
148// CheckForInvalidatingInst - Return true if BB or any of the predecessors of BB
149// (until DestBB) contain an instruction that might invalidate Ptr.
150//
151static bool CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000152 Value *Ptr, unsigned Size,
153 AliasAnalysis &AA,
Chris Lattner71c7ec92002-08-30 20:28:10 +0000154 std::set<BasicBlock*> &VisitedSet) {
155 // Found the termination point!
156 if (BB == DestBB || VisitedSet.count(BB)) return false;
157
158 // Avoid infinite recursion!
159 VisitedSet.insert(BB);
160
161 // Can this basic block modify Ptr?
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000162 if (AA.canBasicBlockModify(*BB, Ptr, Size))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000163 return true;
164
165 // Check all of our predecessor blocks...
166 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000167 if (CheckForInvalidatingInst(*PI, DestBB, Ptr, Size, AA, VisitedSet))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000168 return true;
169
170 // None of our predecessor blocks contain an invalidating instruction, and we
171 // don't either!
172 return false;
173}
174
175
176/// haveEqualValueNumber - Given two load instructions, determine if they both
177/// produce the same value on every execution of the program, assuming that
178/// their source operands always give the same value. This uses the
179/// AliasAnalysis implementation to invalidate loads when stores or function
180/// calls occur that could modify the value produced by the load.
181///
182bool LoadVN::haveEqualValueNumber(LoadInst *L1, LoadInst *L2,
183 AliasAnalysis &AA,
184 DominatorSet &DomSetInfo) const {
185 // Figure out which load dominates the other one. If neither dominates the
186 // other we cannot eliminate them.
187 //
188 // FIXME: This could be enhanced to some cases with a shared dominator!
189 //
190 if (DomSetInfo.dominates(L2, L1))
191 std::swap(L1, L2); // Make L1 dominate L2
192 else if (!DomSetInfo.dominates(L1, L2))
193 return false; // Neither instruction dominates the other one...
194
195 BasicBlock *BB1 = L1->getParent(), *BB2 = L2->getParent();
196 Value *LoadAddress = L1->getOperand(0);
197
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000198 assert(L1->getType() == L2->getType() &&
199 "How could the same source pointer return different types?");
200
201 // Find out how many bytes of memory are loaded by the load instruction...
202 unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(L1->getType());
203
Chris Lattner71c7ec92002-08-30 20:28:10 +0000204 // L1 now dominates L2. Check to see if the intervening instructions between
205 // the two loads include a store or call...
206 //
207 if (BB1 == BB2) { // In same basic block?
208 // In this degenerate case, no checking of global basic blocks has to occur
209 // just check the instructions BETWEEN L1 & L2...
210 //
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000211 if (AA.canInstructionRangeModify(*L1, *L2, LoadAddress, LoadSize))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000212 return false; // Cannot eliminate load
213
214 // No instructions invalidate the loads, they produce the same value!
215 return true;
216 } else {
217 // Make sure that there are no store instructions between L1 and the end of
218 // it's basic block...
219 //
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000220 if (AA.canInstructionRangeModify(*L1, *BB1->getTerminator(), LoadAddress,
221 LoadSize))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000222 return false; // Cannot eliminate load
223
224 // Make sure that there are no store instructions between the start of BB2
225 // and the second load instruction...
226 //
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000227 if (AA.canInstructionRangeModify(BB2->front(), *L2, LoadAddress, LoadSize))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000228 return false; // Cannot eliminate load
229
230 // Do a depth first traversal of the inverse CFG starting at L2's block,
231 // looking for L1's block. The inverse CFG is made up of the predecessor
232 // nodes of a block... so all of the edges in the graph are "backward".
233 //
234 std::set<BasicBlock*> VisitedSet;
235 for (pred_iterator PI = pred_begin(BB2), PE = pred_end(BB2); PI != PE; ++PI)
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000236 if (CheckForInvalidatingInst(*PI, BB1, LoadAddress, LoadSize, AA,
237 VisitedSet))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000238 return false;
239
240 // If we passed all of these checks then we are sure that the two loads
241 // produce the same value.
242 return true;
243 }
244}