f6c54fb5bbf3266a8d9cdad96623ab3bc5b6b5de
[oota-llvm.git] / lib / Analysis / DataStructure / MemoryDepAnalysis.cpp
1 //===- MemoryDepAnalysis.cpp - Compute dep graph for memory ops -----------===//
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 pass (MemoryDepAnalysis) that computes memory-based
11 // data dependences between instructions for each function in a module.  
12 // Memory-based dependences occur due to load and store operations, but
13 // also the side-effects of call instructions.
14 //
15 // The result of this pass is a DependenceGraph for each function
16 // representing the memory-based data dependences between instructions.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "MemoryDepAnalysis.h"
21 #include "IPModRef.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/Analysis/DataStructure/DataStructure.h"
25 #include "llvm/Analysis/DataStructure/DSGraph.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/ADT/SCCIterator.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/hash_map"
32 #include "llvm/ADT/hash_set"
33
34 namespace llvm {
35
36 ///--------------------------------------------------------------------------
37 /// struct ModRefTable:
38 /// 
39 /// A data structure that tracks ModRefInfo for instructions:
40 ///   -- modRefMap is a map of Instruction* -> ModRefInfo for the instr.
41 ///   -- definers  is a vector of instructions that define    any node
42 ///   -- users     is a vector of instructions that reference any node
43 ///   -- numUsersBeforeDef is a vector indicating that the number of users
44 ///                seen before definers[i] is numUsersBeforeDef[i].
45 /// 
46 /// numUsersBeforeDef[] effectively tells us the exact interleaving of
47 /// definers and users within the ModRefTable.
48 /// This is only maintained when constructing the table for one SCC, and
49 /// not copied over from one table to another since it is no longer useful.
50 ///--------------------------------------------------------------------------
51
52 struct ModRefTable {
53   typedef hash_map<Instruction*, ModRefInfo> ModRefMap;
54   typedef ModRefMap::const_iterator                 const_map_iterator;
55   typedef ModRefMap::      iterator                       map_iterator;
56   typedef std::vector<Instruction*>::const_iterator const_ref_iterator;
57   typedef std::vector<Instruction*>::      iterator       ref_iterator;
58
59   ModRefMap                 modRefMap;
60   std::vector<Instruction*> definers;
61   std::vector<Instruction*> users;
62   std::vector<unsigned>     numUsersBeforeDef;
63
64   // Iterators to enumerate all the defining instructions
65   const_ref_iterator defsBegin()  const {  return definers.begin(); }
66         ref_iterator defsBegin()        {  return definers.begin(); }
67   const_ref_iterator defsEnd()    const {  return definers.end(); }
68         ref_iterator defsEnd()          {  return definers.end(); }
69
70   // Iterators to enumerate all the user instructions
71   const_ref_iterator usersBegin() const {  return users.begin(); }
72         ref_iterator usersBegin()       {  return users.begin(); }
73   const_ref_iterator usersEnd()   const {  return users.end(); }
74         ref_iterator usersEnd()         {  return users.end(); }
75
76   // Iterator identifying the last user that was seen *before* a
77   // specified def.  In particular, all users in the half-closed range
78   //    [ usersBegin(), usersBeforeDef_End(defPtr) )
79   // were seen *before* the specified def.  All users in the half-closed range
80   //    [ usersBeforeDef_End(defPtr), usersEnd() )
81   // were seen *after* the specified def.
82   // 
83   ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) {
84     unsigned defIndex = (unsigned) (defPtr - defsBegin());
85     assert(defIndex < numUsersBeforeDef.size());
86     assert(usersBegin() + numUsersBeforeDef[defIndex] <= usersEnd()); 
87     return usersBegin() + numUsersBeforeDef[defIndex]; 
88   }
89   const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
90     return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
91   }
92
93   // 
94   // Modifier methods
95   // 
96   void AddDef(Instruction* D) {
97     definers.push_back(D);
98     numUsersBeforeDef.push_back(users.size());
99   }
100   void AddUse(Instruction* U) {
101     users.push_back(U);
102   }
103   void Insert(const ModRefTable& fromTable) {
104     modRefMap.insert(fromTable.modRefMap.begin(), fromTable.modRefMap.end());
105     definers.insert(definers.end(),
106                     fromTable.definers.begin(), fromTable.definers.end());
107     users.insert(users.end(),
108                  fromTable.users.begin(), fromTable.users.end());
109     numUsersBeforeDef.clear(); /* fromTable.numUsersBeforeDef is ignored */
110   }
111 };
112
113
114 ///--------------------------------------------------------------------------
115 /// class ModRefInfoBuilder:
116 /// 
117 /// A simple InstVisitor<> class that retrieves the Mod/Ref info for
118 /// Load/Store/Call instructions and inserts this information in
119 /// a ModRefTable.  It also records all instructions that Mod any node
120 /// and all that use any node.
121 ///--------------------------------------------------------------------------
122
123 class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
124   const DSGraph&            funcGraph;
125   const FunctionModRefInfo& funcModRef;
126   struct ModRefTable&       modRefTable;
127
128   ModRefInfoBuilder();                         // DO NOT IMPLEMENT
129   ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
130   void operator=(const ModRefInfoBuilder&);    // DO NOT IMPLEMENT
131
132 public:
133   ModRefInfoBuilder(const DSGraph& _funcGraph,
134                     const FunctionModRefInfo& _funcModRef,
135                     ModRefTable& _modRefTable)
136     : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
137   {
138   }
139
140   // At a call instruction, retrieve the ModRefInfo using IPModRef results.
141   // Add the call to the defs list if it modifies any nodes and to the uses
142   // list if it refs any nodes.
143   // 
144   void visitCallInst(CallInst& callInst) {
145     ModRefInfo safeModRef(funcGraph.getGraphSize());
146     const ModRefInfo* callModRef = funcModRef.getModRefInfo(callInst);
147     if (callModRef == NULL) {
148       // call to external/unknown function: mark all nodes as Mod and Ref
149       safeModRef.getModSet().set();
150       safeModRef.getRefSet().set();
151       callModRef = &safeModRef;
152     }
153
154     modRefTable.modRefMap.insert(std::make_pair(&callInst,
155                                                 ModRefInfo(*callModRef)));
156     if (callModRef->getModSet().any())
157       modRefTable.AddDef(&callInst);
158     if (callModRef->getRefSet().any())
159       modRefTable.AddUse(&callInst);
160   }
161
162   // At a store instruction, add to the mod set the single node pointed to
163   // by the pointer argument of the store.  Interestingly, if there is no
164   // such node, that would be a null pointer reference!
165   void visitStoreInst(StoreInst& storeInst) {
166     const DSNodeHandle& ptrNode =
167       funcGraph.getNodeForValue(storeInst.getPointerOperand());
168     if (const DSNode* target = ptrNode.getNode()) {
169       unsigned nodeId = funcModRef.getNodeId(target);
170       ModRefInfo& minfo =
171         modRefTable.modRefMap.insert(
172           std::make_pair(&storeInst,
173                          ModRefInfo(funcGraph.getGraphSize()))).first->second;
174       minfo.setNodeIsMod(nodeId);
175       modRefTable.AddDef(&storeInst);
176     } else
177       std::cerr << "Warning: Uninitialized pointer reference!\n";
178   }
179
180   // At a load instruction, add to the ref set the single node pointed to
181   // by the pointer argument of the load.  Interestingly, if there is no
182   // such node, that would be a null pointer reference!
183   void visitLoadInst(LoadInst& loadInst) {
184     const DSNodeHandle& ptrNode =
185       funcGraph.getNodeForValue(loadInst.getPointerOperand());
186     if (const DSNode* target = ptrNode.getNode()) {
187       unsigned nodeId = funcModRef.getNodeId(target);
188       ModRefInfo& minfo =
189         modRefTable.modRefMap.insert(
190           std::make_pair(&loadInst,
191                          ModRefInfo(funcGraph.getGraphSize()))).first->second;
192       minfo.setNodeIsRef(nodeId);
193       modRefTable.AddUse(&loadInst);
194     } else
195       std::cerr << "Warning: Uninitialized pointer reference!\n";
196   }
197 };
198
199
200 //----------------------------------------------------------------------------
201 // class MemoryDepAnalysis: A dep. graph for load/store/call instructions
202 //----------------------------------------------------------------------------
203
204
205 /// getAnalysisUsage - This does not modify anything.  It uses the Top-Down DS
206 /// Graph and IPModRef.
207 ///
208 void MemoryDepAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
209   AU.setPreservesAll();
210   AU.addRequired<TDDataStructures>();
211   AU.addRequired<IPModRef>();
212 }
213
214
215 /// Basic dependence gathering algorithm, using scc_iterator on CFG:
216 /// 
217 /// for every SCC S in the CFG in PostOrder on the SCC DAG
218 ///     {
219 ///       for every basic block BB in S in *postorder*
220 ///         for every instruction I in BB in reverse
221 ///           Add (I, ModRef[I]) to ModRefCurrent
222 ///           if (Mod[I] != NULL)
223 ///               Add I to DefSetCurrent:  { I \in S : Mod[I] != NULL }
224 ///           if (Ref[I] != NULL)
225 ///               Add I to UseSetCurrent:  { I       : Ref[I] != NULL }
226 /// 
227 ///       for every def D in DefSetCurrent
228 /// 
229 ///           // NOTE: D comes after itself iff S contains a loop
230 ///           if (HasLoop(S) && D & D)
231 ///               Add output-dep: D -> D2
232 /// 
233 ///           for every def D2 *after* D in DefSetCurrent
234 ///               // NOTE: D2 comes before D in execution order
235 ///               if (D & D2)
236 ///                   Add output-dep: D2 -> D
237 ///                   if (HasLoop(S))
238 ///                       Add output-dep: D -> D2
239 /// 
240 ///           for every use U in UseSetCurrent that was seen *before* D
241 ///               // NOTE: U comes after D in execution order
242 ///               if (U & D)
243 ///                   if (U != D || HasLoop(S))
244 ///                       Add true-dep: D -> U
245 ///                   if (HasLoop(S))
246 ///                       Add anti-dep: U -> D
247 /// 
248 ///           for every use U in UseSetCurrent that was seen *after* D
249 ///               // NOTE: U comes before D in execution order
250 ///               if (U & D)
251 ///                   if (U != D || HasLoop(S))
252 ///                       Add anti-dep: U -> D
253 ///                   if (HasLoop(S))
254 ///                       Add true-dep: D -> U
255 /// 
256 ///           for every def Dnext in DefSetAfter
257 ///               // NOTE: Dnext comes after D in execution order
258 ///               if (Dnext & D)
259 ///                   Add output-dep: D -> Dnext
260 /// 
261 ///           for every use Unext in UseSetAfter
262 ///               // NOTE: Unext comes after D in execution order
263 ///               if (Unext & D)
264 ///                   Add true-dep: D -> Unext
265 /// 
266 ///       for every use U in UseSetCurrent
267 ///           for every def Dnext in DefSetAfter
268 ///               // NOTE: Dnext comes after U in execution order
269 ///               if (Dnext & D)
270 ///                   Add anti-dep: U -> Dnext
271 /// 
272 ///       Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
273 ///       Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
274 ///       Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
275 ///     }
276 ///         
277 ///
278 void MemoryDepAnalysis::ProcessSCC(std::vector<BasicBlock*> &S,
279                                    ModRefTable& ModRefAfter, bool hasLoop) {
280   ModRefTable ModRefCurrent;
281   ModRefTable::ModRefMap& mapCurrent = ModRefCurrent.modRefMap;
282   ModRefTable::ModRefMap& mapAfter   = ModRefAfter.modRefMap;
283
284   // Builder class fills out a ModRefTable one instruction at a time.
285   // To use it, we just invoke it's visit function for each basic block:
286   // 
287   //   for each basic block BB in the SCC in *postorder*
288   //       for each instruction  I in BB in *reverse*
289   //           ModRefInfoBuilder::visit(I)
290   //           : Add (I, ModRef[I]) to ModRefCurrent.modRefMap
291   //           : Add I  to ModRefCurrent.definers if it defines any node
292   //           : Add I  to ModRefCurrent.users    if it uses any node
293   // 
294   ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
295   for (std::vector<BasicBlock*>::iterator BI = S.begin(), BE = S.end();
296        BI != BE; ++BI)
297     // Note: BBs in the SCC<> created by scc_iterator are in postorder.
298     for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
299          II != IE; ++II)
300       builder.visit(*II);
301
302   ///       for every def D in DefSetCurrent
303   /// 
304   for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
305          IE=ModRefCurrent.defsEnd(); II != IE; ++II)
306     {
307       ///           // NOTE: D comes after itself iff S contains a loop
308       ///           if (HasLoop(S))
309       ///               Add output-dep: D -> D2
310       if (hasLoop)
311         funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
312
313       ///           for every def D2 *after* D in DefSetCurrent
314       ///               // NOTE: D2 comes before D in execution order
315       ///               if (D2 & D)
316       ///                   Add output-dep: D2 -> D
317       ///                   if (HasLoop(S))
318       ///                       Add output-dep: D -> D2
319       for (ModRefTable::ref_iterator JI=II+1; JI != IE; ++JI)
320         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
321                       mapCurrent.find(*JI)->second.getModSet()))
322           {
323             funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
324             if (hasLoop)
325               funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
326           }
327   
328       ///           for every use U in UseSetCurrent that was seen *before* D
329       ///               // NOTE: U comes after D in execution order
330       ///               if (U & D)
331       ///                   if (U != D || HasLoop(S))
332       ///                       Add true-dep: U -> D
333       ///                   if (HasLoop(S))
334       ///                       Add anti-dep: D -> U
335       ModRefTable::ref_iterator JI=ModRefCurrent.usersBegin();
336       ModRefTable::ref_iterator JE = ModRefCurrent.usersBeforeDef_End(II);
337       for ( ; JI != JE; ++JI)
338         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
339                       mapCurrent.find(*JI)->second.getRefSet()))
340           {
341             if (*II != *JI || hasLoop)
342               funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
343             if (hasLoop)
344               funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
345           }
346
347       ///           for every use U in UseSetCurrent that was seen *after* D
348       ///               // NOTE: U comes before D in execution order
349       ///               if (U & D)
350       ///                   if (U != D || HasLoop(S))
351       ///                       Add anti-dep: U -> D
352       ///                   if (HasLoop(S))
353       ///                       Add true-dep: D -> U
354       for (/*continue JI*/ JE = ModRefCurrent.usersEnd(); JI != JE; ++JI)
355         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
356                       mapCurrent.find(*JI)->second.getRefSet()))
357           {
358             if (*II != *JI || hasLoop)
359               funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
360             if (hasLoop)
361               funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
362           }
363
364       ///           for every def Dnext in DefSetPrev
365       ///               // NOTE: Dnext comes after D in execution order
366       ///               if (Dnext & D)
367       ///                   Add output-dep: D -> Dnext
368       for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
369              JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
370         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
371                       mapAfter.find(*JI)->second.getModSet()))
372           funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
373
374       ///           for every use Unext in UseSetAfter
375       ///               // NOTE: Unext comes after D in execution order
376       ///               if (Unext & D)
377       ///                   Add true-dep: D -> Unext
378       for (ModRefTable::ref_iterator JI=ModRefAfter.usersBegin(),
379              JE=ModRefAfter.usersEnd(); JI != JE; ++JI)
380         if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
381                       mapAfter.find(*JI)->second.getRefSet()))
382           funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
383     }
384
385   /// 
386   ///       for every use U in UseSetCurrent
387   ///           for every def Dnext in DefSetAfter
388   ///               // NOTE: Dnext comes after U in execution order
389   ///               if (Dnext & D)
390   ///                   Add anti-dep: U -> Dnext
391   for (ModRefTable::ref_iterator II=ModRefCurrent.usersBegin(),
392          IE=ModRefCurrent.usersEnd(); II != IE; ++II)
393     for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
394            JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
395       if (!Disjoint(mapCurrent.find(*II)->second.getRefSet(),
396                     mapAfter.find(*JI)->second.getModSet()))
397         funcDepGraph->AddSimpleDependence(**II, **JI, AntiDependence);
398     
399   ///       Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
400   ///       Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
401   ///       Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
402   ModRefAfter.Insert(ModRefCurrent);
403 }
404
405
406 /// Debugging support methods
407 /// 
408 void MemoryDepAnalysis::print(std::ostream &O) const
409 {
410   // TEMPORARY LOOP
411   for (hash_map<Function*, DependenceGraph*>::const_iterator
412          I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
413     {
414       Function* func = I->first;
415       DependenceGraph* depGraph = I->second;
416
417   O << "\n================================================================\n";
418   O << "DEPENDENCE GRAPH FOR MEMORY OPERATIONS IN FUNCTION " << func->getName();
419   O << "\n================================================================\n\n";
420   depGraph->print(*func, O);
421
422     }
423 }
424
425
426 /// 
427 /// Run the pass on a function
428 /// 
429 bool MemoryDepAnalysis::runOnFunction(Function &F) {
430   assert(!F.isExternal());
431
432   // Get the FunctionModRefInfo holding IPModRef results for this function.
433   // Use the TD graph recorded within the FunctionModRefInfo object, which
434   // may not be the same as the original TD graph computed by DS analysis.
435   // 
436   funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
437   funcGraph  = &funcModRef->getFuncGraph();
438
439   // TEMPORARY: ptr to depGraph (later just becomes "this").
440   assert(!funcMap.count(&F) && "Analyzing function twice?");
441   funcDepGraph = funcMap[&F] = new DependenceGraph();
442
443   ModRefTable ModRefAfter;
444
445   for (scc_iterator<Function*> I = scc_begin(&F), E = scc_end(&F); I != E; ++I)
446     ProcessSCC(*I, ModRefAfter, I.hasLoop());
447
448   return true;
449 }
450
451
452 //-------------------------------------------------------------------------
453 // TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
454 // These functions will go away once this class becomes a FunctionPass.
455 // 
456
457 // Driver function to compute dependence graphs for every function.
458 // This is temporary and will go away once this is a FunctionPass.
459 // 
460 bool MemoryDepAnalysis::runOnModule(Module& M)
461 {
462   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
463     if (! FI->isExternal())
464       runOnFunction(*FI); // automatically inserts each depGraph into funcMap
465   return true;
466 }
467   
468 // Release all the dependence graphs in the map.
469 void MemoryDepAnalysis::releaseMemory()
470 {
471   for (hash_map<Function*, DependenceGraph*>::const_iterator
472          I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
473     delete I->second;
474   funcMap.clear();
475
476   // Clear pointers because the pass constructor will not be invoked again.
477   funcDepGraph = NULL;
478   funcGraph = NULL;
479   funcModRef = NULL;
480 }
481
482 MemoryDepAnalysis::~MemoryDepAnalysis()
483 {
484   releaseMemory();
485 }
486
487 //----END TEMPORARY FUNCTIONS----------------------------------------------
488
489
490 void MemoryDepAnalysis::dump() const
491 {
492   this->print(std::cerr);
493 }
494
495 static RegisterAnalysis<MemoryDepAnalysis>
496 Z("memdep", "Memory Dependence Analysis");
497
498
499 } // End llvm namespace