1 //===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements a value numbering pass that value #'s load instructions.
11 // To do this, it finds lexically identical load instructions, and uses alias
12 // analysis to determine which loads are guaranteed to produce the same value.
14 // This pass builds off of another value numbering pass to implement value
15 // numbering for non-load instructions. It uses Alias Analysis so that it can
16 // disambiguate the load instructions. The more powerful these base analyses
17 // are, the more powerful the resultant analysis will be.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Analysis/LoadValueNumbering.h"
22 #include "llvm/Analysis/ValueNumbering.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Type.h"
28 #include "llvm/iMemory.h"
29 #include "llvm/BasicBlock.h"
30 #include "llvm/Support/CFG.h"
35 // FIXME: This should not be a FunctionPass.
36 struct LoadVN : public FunctionPass, public ValueNumbering {
38 /// Pass Implementation stuff. This doesn't do any analysis.
40 bool runOnFunction(Function &) { return false; }
42 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
43 /// and Alias Analysis.
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
47 /// getEqualNumberNodes - Return nodes with the same value number as the
48 /// specified Value. This fills in the argument vector with any equal
51 virtual void getEqualNumberNodes(Value *V1,
52 std::vector<Value*> &RetVals) const;
54 /// haveEqualValueNumber - Given two load instructions, determine if they
55 /// both produce the same value on every execution of the program, assuming
56 /// that their source operands always give the same value. This uses the
57 /// AliasAnalysis implementation to invalidate loads when stores or function
58 /// calls occur that could modify the value produced by the load.
60 bool haveEqualValueNumber(LoadInst *LI, LoadInst *LI2, AliasAnalysis &AA,
61 DominatorSet &DomSetInfo) const;
62 bool haveEqualValueNumber(LoadInst *LI, StoreInst *SI, AliasAnalysis &AA,
63 DominatorSet &DomSetInfo) const;
66 // Register this pass...
67 RegisterOpt<LoadVN> X("load-vn", "Load Value Numbering");
69 // Declare that we implement the ValueNumbering interface
70 RegisterAnalysisGroup<ValueNumbering, LoadVN> Y;
73 Pass *llvm::createLoadValueNumberingPass() { return new LoadVN(); }
76 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering and
79 void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const {
81 AU.addRequired<AliasAnalysis>();
82 AU.addRequired<ValueNumbering>();
83 AU.addRequired<DominatorSet>();
84 AU.addRequired<TargetData>();
87 // getEqualNumberNodes - Return nodes with the same value number as the
88 // specified Value. This fills in the argument vector with any equal values.
90 void LoadVN::getEqualNumberNodes(Value *V,
91 std::vector<Value*> &RetVals) const {
92 // If the alias analysis has any must alias information to share with us, we
93 // can definitely use it.
94 if (isa<PointerType>(V->getType()))
95 getAnalysis<AliasAnalysis>().getMustAliases(V, RetVals);
97 if (!isa<LoadInst>(V)) {
98 // Not a load instruction? Just chain to the base value numbering
99 // implementation to satisfy the request...
100 assert(&getAnalysis<ValueNumbering>() != (ValueNumbering*)this &&
101 "getAnalysis() returned this!");
103 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
106 // Volatile loads cannot be replaced with the value of other loads.
107 LoadInst *LI = cast<LoadInst>(V);
108 if (LI->isVolatile())
109 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
111 // If we have a load instruction, find all of the load and store instructions
112 // that use the same source operand. We implement this recursively, because
113 // there could be a load of a load of a load that are all identical. We are
114 // guaranteed that this cannot be an infinite recursion because load
115 // instructions would have to pass through a PHI node in order for there to be
116 // a cycle. The PHI node would be handled by the else case here, breaking the
117 // infinite recursion.
119 std::vector<Value*> PointerSources;
120 getEqualNumberNodes(LI->getOperand(0), PointerSources);
121 PointerSources.push_back(LI->getOperand(0));
123 Function *F = LI->getParent()->getParent();
125 // Now that we know the set of equivalent source pointers for the load
126 // instruction, look to see if there are any load or store candidates that are
129 std::vector<LoadInst*> CandidateLoads;
130 std::vector<StoreInst*> CandidateStores;
132 while (!PointerSources.empty()) {
133 Value *Source = PointerSources.back();
134 PointerSources.pop_back(); // Get a source pointer...
136 for (Value::use_iterator UI = Source->use_begin(), UE = Source->use_end();
138 if (LoadInst *Cand = dyn_cast<LoadInst>(*UI)) {// Is a load of source?
139 if (Cand->getParent()->getParent() == F && // In the same function?
140 Cand != LI && !Cand->isVolatile()) // Not LI itself?
141 CandidateLoads.push_back(Cand); // Got one...
142 } else if (StoreInst *Cand = dyn_cast<StoreInst>(*UI)) {
143 if (Cand->getParent()->getParent() == F && !Cand->isVolatile() &&
144 Cand->getOperand(1) == Source) // It's a store THROUGH the ptr...
145 CandidateStores.push_back(Cand);
149 // Get Alias Analysis...
150 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
151 DominatorSet &DomSetInfo = getAnalysis<DominatorSet>();
153 // Loop over all of the candidate loads. If they are not invalidated by
154 // stores or calls between execution of them and LI, then add them to RetVals.
155 for (unsigned i = 0, e = CandidateLoads.size(); i != e; ++i)
156 if (haveEqualValueNumber(LI, CandidateLoads[i], AA, DomSetInfo))
157 RetVals.push_back(CandidateLoads[i]);
158 for (unsigned i = 0, e = CandidateStores.size(); i != e; ++i)
159 if (haveEqualValueNumber(LI, CandidateStores[i], AA, DomSetInfo))
160 RetVals.push_back(CandidateStores[i]->getOperand(0));
164 // CheckForInvalidatingInst - Return true if BB or any of the predecessors of BB
165 // (until DestBB) contain an instruction that might invalidate Ptr.
167 static bool CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
168 Value *Ptr, unsigned Size,
170 std::set<BasicBlock*> &VisitedSet) {
171 // Found the termination point!
172 if (BB == DestBB || VisitedSet.count(BB)) return false;
174 // Avoid infinite recursion!
175 VisitedSet.insert(BB);
177 // Can this basic block modify Ptr?
178 if (AA.canBasicBlockModify(*BB, Ptr, Size))
181 // Check all of our predecessor blocks...
182 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
183 if (CheckForInvalidatingInst(*PI, DestBB, Ptr, Size, AA, VisitedSet))
186 // None of our predecessor blocks contain an invalidating instruction, and we
192 /// haveEqualValueNumber - Given two load instructions, determine if they both
193 /// produce the same value on every execution of the program, assuming that
194 /// their source operands always give the same value. This uses the
195 /// AliasAnalysis implementation to invalidate loads when stores or function
196 /// calls occur that could modify the value produced by the load.
198 bool LoadVN::haveEqualValueNumber(LoadInst *L1, LoadInst *L2,
200 DominatorSet &DomSetInfo) const {
201 assert(L1 != L2 && "haveEqualValueNumber assumes differing loads!");
202 assert(L1->getType() == L2->getType() &&
203 "How could the same source pointer return different types?");
204 Value *LoadAddress = L1->getOperand(0);
206 // Find out how many bytes of memory are loaded by the load instruction...
207 unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(L1->getType());
209 // If the two loads are in the same basic block, just do a local analysis.
210 if (L1->getParent() == L2->getParent()) {
211 // It can be _very_ expensive to determine which instruction occurs first in
212 // the basic block if the block is large (see PR209). For this reason,
213 // instead of figuring out which block is first, then scanning all of the
214 // instructions, we scan the instructions both ways from L1 until we find
215 // L2. Along the way if we find a potentially modifying instruction, we
216 // kill the search. This helps in cases where we have large blocks the have
217 // potentially modifying instructions in them which stop the search.
219 BasicBlock *BB = L1->getParent();
220 BasicBlock::iterator UpIt = L1, DownIt = L1; ++DownIt;
221 bool NoModifiesUp = true, NoModifiesDown = true;
223 // Scan up and down looking for L2, a modifying instruction, or the end of a
225 while (UpIt != BB->begin() && DownIt != BB->end()) {
229 return NoModifiesUp; // No instructions invalidate the loads!
232 !(AA.getModRefInfo(UpIt, LoadAddress, LoadSize) & AliasAnalysis::Mod);
235 return NoModifiesDown;
238 !(AA.getModRefInfo(DownIt, LoadAddress, LoadSize)
239 & AliasAnalysis::Mod);
243 // If we got here, we ran into one end of the basic block or the other.
244 if (UpIt != BB->begin()) {
245 // If we know that the upward scan found a modifier, return false.
246 if (!NoModifiesUp) return false;
248 // Otherwise, continue the scan looking for a modifier or L2.
249 for (--UpIt; &*UpIt != L2; --UpIt)
250 if (AA.getModRefInfo(UpIt, LoadAddress, LoadSize) & AliasAnalysis::Mod)
254 // If we know that the downward scan found a modifier, return false.
255 assert(DownIt != BB->end() && "Didn't find instructions??");
256 if (!NoModifiesDown) return false;
258 // Otherwise, continue the scan looking for a modifier or L2.
259 for (; &*DownIt != L2; ++DownIt) {
260 if (AA.getModRefInfo(DownIt, LoadAddress, LoadSize) &AliasAnalysis::Mod)
266 // Figure out which load dominates the other one. If neither dominates the
267 // other we cannot eliminate them.
269 // FIXME: This could be enhanced greatly!
271 if (DomSetInfo.dominates(L2, L1))
272 std::swap(L1, L2); // Make L1 dominate L2
273 else if (!DomSetInfo.dominates(L1, L2))
274 return false; // Neither instruction dominates the other one...
276 BasicBlock *BB1 = L1->getParent(), *BB2 = L2->getParent();
278 // L1 now dominates L2. Check to see if the intervening instructions
279 // between the two loads might modify the loaded location.
281 // Make sure that there are no modifying instructions between L1 and the end
282 // of its basic block.
284 if (AA.canInstructionRangeModify(*L1, *BB1->getTerminator(), LoadAddress,
286 return false; // Cannot eliminate load
288 // Make sure that there are no modifying instructions between the start of
289 // BB2 and the second load instruction.
291 if (AA.canInstructionRangeModify(BB2->front(), *L2, LoadAddress, LoadSize))
292 return false; // Cannot eliminate load
294 // Do a depth first traversal of the inverse CFG starting at L2's block,
295 // looking for L1's block. The inverse CFG is made up of the predecessor
296 // nodes of a block... so all of the edges in the graph are "backward".
298 std::set<BasicBlock*> VisitedSet;
299 for (pred_iterator PI = pred_begin(BB2), PE = pred_end(BB2); PI != PE; ++PI)
300 if (CheckForInvalidatingInst(*PI, BB1, LoadAddress, LoadSize, AA,
304 // If we passed all of these checks then we are sure that the two loads
305 // produce the same value.
311 /// haveEqualValueNumber - Given a load instruction and a store instruction,
312 /// determine if the stored value reaches the loaded value unambiguously on
313 /// every execution of the program. This uses the AliasAnalysis implementation
314 /// to invalidate the stored value when stores or function calls occur that
315 /// could modify the value produced by the load.
317 bool LoadVN::haveEqualValueNumber(LoadInst *Load, StoreInst *Store,
319 DominatorSet &DomSetInfo) const {
320 // If the store does not dominate the load, we cannot do anything...
321 if (!DomSetInfo.dominates(Store, Load))
324 BasicBlock *BB1 = Store->getParent(), *BB2 = Load->getParent();
325 Value *LoadAddress = Load->getOperand(0);
327 assert(LoadAddress->getType() == Store->getOperand(1)->getType() &&
328 "How could the same source pointer return different types?");
330 // Find out how many bytes of memory are loaded by the load instruction...
331 unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(Load->getType());
333 // Compute a basic block iterator pointing to the instruction after the store.
334 BasicBlock::iterator StoreIt = Store; ++StoreIt;
336 // Check to see if the intervening instructions between the two store and load
337 // include a store or call...
339 if (BB1 == BB2) { // In same basic block?
340 // In this degenerate case, no checking of global basic blocks has to occur
341 // just check the instructions BETWEEN Store & Load...
343 if (AA.canInstructionRangeModify(*StoreIt, *Load, LoadAddress, LoadSize))
344 return false; // Cannot eliminate load
346 // No instructions invalidate the stored value, they produce the same value!
349 // Make sure that there are no store instructions between the Store and the
350 // end of its basic block...
352 if (AA.canInstructionRangeModify(*StoreIt, *BB1->getTerminator(),
353 LoadAddress, LoadSize))
354 return false; // Cannot eliminate load
356 // Make sure that there are no store instructions between the start of BB2
357 // and the second load instruction...
359 if (AA.canInstructionRangeModify(BB2->front(), *Load, LoadAddress,LoadSize))
360 return false; // Cannot eliminate load
362 // Do a depth first traversal of the inverse CFG starting at L2's block,
363 // looking for L1's block. The inverse CFG is made up of the predecessor
364 // nodes of a block... so all of the edges in the graph are "backward".
366 std::set<BasicBlock*> VisitedSet;
367 for (pred_iterator PI = pred_begin(BB2), PE = pred_end(BB2); PI != PE; ++PI)
368 if (CheckForInvalidatingInst(*PI, BB1, LoadAddress, LoadSize, AA,
372 // If we passed all of these checks then we are sure that the two loads
373 // produce the same value.