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