This is a big diff with no functionality change. We just reorder some code,
[oota-llvm.git] / lib / Analysis / LoadValueNumbering.cpp
1 //===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
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.
18 //
19 //===----------------------------------------------------------------------===//
20
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"
31 #include <set>
32 using namespace llvm;
33
34 namespace {
35   // FIXME: This should not be a FunctionPass.
36   struct LoadVN : public FunctionPass, public ValueNumbering {
37     
38     /// Pass Implementation stuff.  This doesn't do any analysis.
39     ///
40     bool runOnFunction(Function &) { return false; }
41     
42     /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering
43     /// and Alias Analysis.
44     ///
45     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
46     
47     /// getEqualNumberNodes - Return nodes with the same value number as the
48     /// specified Value.  This fills in the argument vector with any equal
49     /// values.
50     ///
51     virtual void getEqualNumberNodes(Value *V1,
52                                      std::vector<Value*> &RetVals) const;
53   private:
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.
59     ///
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;
64   };
65
66   // Register this pass...
67   RegisterOpt<LoadVN> X("load-vn", "Load Value Numbering");
68
69   // Declare that we implement the ValueNumbering interface
70   RegisterAnalysisGroup<ValueNumbering, LoadVN> Y;
71 }
72
73 Pass *llvm::createLoadValueNumberingPass() { return new LoadVN(); }
74
75
76 /// getAnalysisUsage - Does not modify anything.  It uses Value Numbering and
77 /// Alias Analysis.
78 ///
79 void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const {
80   AU.setPreservesAll();
81   AU.addRequired<AliasAnalysis>();
82   AU.addRequired<ValueNumbering>();
83   AU.addRequired<DominatorSet>();
84   AU.addRequired<TargetData>();
85 }
86
87 // getEqualNumberNodes - Return nodes with the same value number as the
88 // specified Value.  This fills in the argument vector with any equal values.
89 //
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);
96
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!");
102
103     return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
104   }
105
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);
110   
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.
118   //
119   std::vector<Value*> PointerSources;
120   getEqualNumberNodes(LI->getOperand(0), PointerSources);
121   PointerSources.push_back(LI->getOperand(0));
122   
123   Function *F = LI->getParent()->getParent();
124   
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
127   // identical.
128   //
129   std::vector<LoadInst*> CandidateLoads;
130   std::vector<StoreInst*> CandidateStores;
131   
132   while (!PointerSources.empty()) {
133     Value *Source = PointerSources.back();
134     PointerSources.pop_back();                // Get a source pointer...
135     
136     for (Value::use_iterator UI = Source->use_begin(), UE = Source->use_end();
137          UI != UE; ++UI)
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);
146       }
147   }
148   
149   // Get Alias Analysis...
150   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
151   DominatorSet &DomSetInfo = getAnalysis<DominatorSet>();
152   
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));
161   
162 }
163
164 // CheckForInvalidatingInst - Return true if BB or any of the predecessors of BB
165 // (until DestBB) contain an instruction that might invalidate Ptr.
166 //
167 static bool CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
168                                      Value *Ptr, unsigned Size,
169                                      AliasAnalysis &AA,
170                                      std::set<BasicBlock*> &VisitedSet) {
171   // Found the termination point!
172   if (BB == DestBB || VisitedSet.count(BB)) return false;
173
174   // Avoid infinite recursion!
175   VisitedSet.insert(BB);
176
177   // Can this basic block modify Ptr?
178   if (AA.canBasicBlockModify(*BB, Ptr, Size))
179     return true;
180
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))
184       return true;
185
186   // None of our predecessor blocks contain an invalidating instruction, and we
187   // don't either!
188   return false;
189 }
190
191
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.
197 ///
198 bool LoadVN::haveEqualValueNumber(LoadInst *L1, LoadInst *L2,
199                                   AliasAnalysis &AA,
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);
205
206   // Find out how many bytes of memory are loaded by the load instruction...
207   unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(L1->getType());
208
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.
218
219     BasicBlock *BB = L1->getParent();
220     BasicBlock::iterator UpIt = L1, DownIt = L1; ++DownIt;
221     bool NoModifiesUp = true, NoModifiesDown = true;
222
223     // Scan up and down looking for L2, a modifying instruction, or the end of a
224     // basic block.
225     while (UpIt != BB->begin() && DownIt != BB->end()) {
226       // Scan up...
227       --UpIt;
228       if (&*UpIt == L2)
229         return NoModifiesUp;  // No instructions invalidate the loads!
230       if (NoModifiesUp)
231         NoModifiesUp &=
232           !(AA.getModRefInfo(UpIt, LoadAddress, LoadSize) & AliasAnalysis::Mod);
233
234       if (&*DownIt == L2)
235         return NoModifiesDown;
236       if (NoModifiesDown)
237         NoModifiesDown &=
238           !(AA.getModRefInfo(DownIt, LoadAddress, LoadSize)
239             & AliasAnalysis::Mod);
240       ++DownIt;
241     }
242
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;
247
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)
251           return false;
252       return true;
253     } else {
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;
257       
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)
261           return false;
262       }
263       return true;
264     }
265   } else {
266     // Figure out which load dominates the other one.  If neither dominates the
267     // other we cannot eliminate them.
268     //
269     // FIXME: This could be enhanced greatly!
270     //
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...
275
276     BasicBlock *BB1 = L1->getParent(), *BB2 = L2->getParent();
277     
278     // L1 now dominates L2.  Check to see if the intervening instructions
279     // between the two loads might modify the loaded location.
280
281     // Make sure that there are no modifying instructions between L1 and the end
282     // of its basic block.
283     //
284     if (AA.canInstructionRangeModify(*L1, *BB1->getTerminator(), LoadAddress,
285                                      LoadSize))
286       return false;   // Cannot eliminate load
287
288     // Make sure that there are no modifying instructions between the start of
289     // BB2 and the second load instruction.
290     //
291     if (AA.canInstructionRangeModify(BB2->front(), *L2, LoadAddress, LoadSize))
292       return false;   // Cannot eliminate load
293
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".
297     //
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,
301                                    VisitedSet))
302         return false;
303     
304     // If we passed all of these checks then we are sure that the two loads
305     // produce the same value.
306     return true;
307   }
308 }
309
310
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.
316 ///
317 bool LoadVN::haveEqualValueNumber(LoadInst *Load, StoreInst *Store,
318                                   AliasAnalysis &AA,
319                                   DominatorSet &DomSetInfo) const {
320   // If the store does not dominate the load, we cannot do anything...
321   if (!DomSetInfo.dominates(Store, Load)) 
322     return false;
323
324   BasicBlock *BB1 = Store->getParent(), *BB2 = Load->getParent();
325   Value *LoadAddress = Load->getOperand(0);
326
327   assert(LoadAddress->getType() == Store->getOperand(1)->getType() &&
328          "How could the same source pointer return different types?");
329
330   // Find out how many bytes of memory are loaded by the load instruction...
331   unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(Load->getType());
332
333   // Compute a basic block iterator pointing to the instruction after the store.
334   BasicBlock::iterator StoreIt = Store; ++StoreIt;
335
336   // Check to see if the intervening instructions between the two store and load
337   // include a store or call...
338   //
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...
342     //
343     if (AA.canInstructionRangeModify(*StoreIt, *Load, LoadAddress, LoadSize))
344       return false;   // Cannot eliminate load
345
346     // No instructions invalidate the stored value, they produce the same value!
347     return true;
348   } else {
349     // Make sure that there are no store instructions between the Store and the
350     // end of its basic block...
351     //
352     if (AA.canInstructionRangeModify(*StoreIt, *BB1->getTerminator(),
353                                      LoadAddress, LoadSize))
354       return false;   // Cannot eliminate load
355
356     // Make sure that there are no store instructions between the start of BB2
357     // and the second load instruction...
358     //
359     if (AA.canInstructionRangeModify(BB2->front(), *Load, LoadAddress,LoadSize))
360       return false;   // Cannot eliminate load
361
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".
365     //
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,
369                                    VisitedSet))
370         return false;
371
372     // If we passed all of these checks then we are sure that the two loads
373     // produce the same value.
374     return true;
375   }
376 }