1 //===- MemoryDepAnalysis.cpp - Compute dep graph for memory ops --*-C++-*--===//
3 // This file implements a pass (MemoryDepAnalysis) that computes memory-based
4 // data dependences between instructions for each function in a module.
5 // Memory-based dependences occur due to load and store operations, but
6 // also the side-effects of call instructions.
8 // The result of this pass is a DependenceGraph for each function
9 // representing the memory-based data dependences between instructions.
10 //===----------------------------------------------------------------------===//
12 #include "llvm/Analysis/MemoryDepAnalysis.h"
13 #include "llvm/Analysis/IPModRef.h"
14 #include "llvm/Analysis/DataStructure.h"
15 #include "llvm/Analysis/DSGraph.h"
16 #include "llvm/Module.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/iOther.h"
19 #include "llvm/Support/InstVisitor.h"
20 #include "llvm/Support/CFG.h"
21 #include "Support/TarjanSCCIterator.h"
22 #include "Support/Statistic.h"
23 #include "Support/STLExtras.h"
24 #include "Support/hash_map"
25 #include "Support/hash_set"
28 ///--------------------------------------------------------------------------
29 /// struct ModRefTable:
31 /// A data structure that tracks ModRefInfo for instructions:
32 /// -- modRefMap is a map of Instruction* -> ModRefInfo for the instr.
33 /// -- definers is a vector of instructions that define any node
34 /// -- users is a vector of instructions that reference any node
35 /// -- numUsersBeforeDef is a vector indicating that the number of users
36 /// seen before definers[i] is numUsersBeforeDef[i].
38 /// numUsersBeforeDef[] effectively tells us the exact interleaving of
39 /// definers and users within the ModRefTable.
40 /// This is only maintained when constructing the table for one SCC, and
41 /// not copied over from one table to another since it is no longer useful.
42 ///--------------------------------------------------------------------------
46 typedef hash_map<Instruction*, ModRefInfo> ModRefMap;
47 typedef ModRefMap::const_iterator const_map_iterator;
48 typedef ModRefMap:: iterator map_iterator;
49 typedef std::vector<Instruction*>::const_iterator const_ref_iterator;
50 typedef std::vector<Instruction*>:: iterator ref_iterator;
53 std::vector<Instruction*> definers;
54 std::vector<Instruction*> users;
55 std::vector<unsigned> numUsersBeforeDef;
57 // Iterators to enumerate all the defining instructions
58 const_ref_iterator defsBegin() const { return definers.begin(); }
59 ref_iterator defsBegin() { return definers.begin(); }
60 const_ref_iterator defsEnd() const { return definers.end(); }
61 ref_iterator defsEnd() { return definers.end(); }
63 // Iterators to enumerate all the user instructions
64 const_ref_iterator usersBegin() const { return users.begin(); }
65 ref_iterator usersBegin() { return users.begin(); }
66 const_ref_iterator usersEnd() const { return users.end(); }
67 ref_iterator usersEnd() { return users.end(); }
69 // Iterator identifying the last user that was seen *before* a
70 // specified def. In particular, all users in the half-closed range
71 // [ usersBegin(), usersBeforeDef_End(defPtr) )
72 // were seen *before* the specified def. All users in the half-closed range
73 // [ usersBeforeDef_End(defPtr), usersEnd() )
74 // were seen *after* the specified def.
76 ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) {
77 unsigned defIndex = (unsigned) (defPtr - defsBegin());
78 assert(defIndex < numUsersBeforeDef.size());
79 assert(usersBegin() + numUsersBeforeDef[defIndex] <= usersEnd());
80 return usersBegin() + numUsersBeforeDef[defIndex];
82 const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
83 return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
89 void AddDef(Instruction* D) {
90 definers.push_back(D);
91 numUsersBeforeDef.push_back(users.size());
93 void AddUse(Instruction* U) {
96 void Insert(const ModRefTable& fromTable) {
97 modRefMap.insert(fromTable.modRefMap.begin(), fromTable.modRefMap.end());
98 definers.insert(definers.end(),
99 fromTable.definers.begin(), fromTable.definers.end());
100 users.insert(users.end(),
101 fromTable.users.begin(), fromTable.users.end());
102 numUsersBeforeDef.clear(); /* fromTable.numUsersBeforeDef is ignored */
107 ///--------------------------------------------------------------------------
108 /// class ModRefInfoBuilder:
110 /// A simple InstVisitor<> class that retrieves the Mod/Ref info for
111 /// Load/Store/Call instructions and inserts this information in
112 /// a ModRefTable. It also records all instructions that Mod any node
113 /// and all that use any node.
114 ///--------------------------------------------------------------------------
116 class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
117 const DSGraph& funcGraph;
118 const FunctionModRefInfo& funcModRef;
119 ModRefTable& modRefTable;
121 ModRefInfoBuilder(); // DO NOT IMPLEMENT
122 ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
123 void operator=(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
126 /*ctor*/ ModRefInfoBuilder(const DSGraph& _funcGraph,
127 const FunctionModRefInfo& _funcModRef,
128 ModRefTable& _modRefTable)
129 : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
133 // At a call instruction, retrieve the ModRefInfo using IPModRef results.
134 // Add the call to the defs list if it modifies any nodes and to the uses
135 // list if it refs any nodes.
137 void visitCallInst (CallInst& callInst) {
138 ModRefInfo safeModRef(funcGraph.getGraphSize());
139 const ModRefInfo* callModRef = funcModRef.getModRefInfo(callInst);
140 if (callModRef == NULL)
141 { // call to external/unknown function: mark all nodes as Mod and Ref
142 safeModRef.getModSet().set();
143 safeModRef.getRefSet().set();
144 callModRef = &safeModRef;
147 modRefTable.modRefMap.insert(std::make_pair(&callInst,
148 ModRefInfo(*callModRef)));
149 if (callModRef->getModSet().any())
150 modRefTable.AddDef(&callInst);
151 if (callModRef->getRefSet().any())
152 modRefTable.AddUse(&callInst);
155 // At a store instruction, add to the mod set the single node pointed to
156 // by the pointer argument of the store. Interestingly, if there is no
157 // such node, that would be a null pointer reference!
158 void visitStoreInst (StoreInst& storeInst) {
159 const DSNodeHandle& ptrNode =
160 funcGraph.getNodeForValue(storeInst.getPointerOperand());
161 if (const DSNode* target = ptrNode.getNode())
163 unsigned nodeId = funcModRef.getNodeId(target);
165 modRefTable.modRefMap.insert(
166 std::make_pair(&storeInst,
167 ModRefInfo(funcGraph.getGraphSize()))).first->second;
168 minfo.setNodeIsMod(nodeId);
169 modRefTable.AddDef(&storeInst);
172 std::cerr << "Warning: Uninitialized pointer reference!\n";
175 // At a load instruction, add to the ref set the single node pointed to
176 // by the pointer argument of the load. Interestingly, if there is no
177 // such node, that would be a null pointer reference!
178 void visitLoadInst (LoadInst& loadInst) {
179 const DSNodeHandle& ptrNode =
180 funcGraph.getNodeForValue(loadInst.getPointerOperand());
181 if (const DSNode* target = ptrNode.getNode())
183 unsigned nodeId = funcModRef.getNodeId(target);
185 modRefTable.modRefMap.insert(
186 std::make_pair(&loadInst,
187 ModRefInfo(funcGraph.getGraphSize()))).first->second;
188 minfo.setNodeIsRef(nodeId);
189 modRefTable.AddUse(&loadInst);
192 std::cerr << "Warning: Uninitialized pointer reference!\n";
197 //----------------------------------------------------------------------------
198 // class MemoryDepAnalysis: A dep. graph for load/store/call instructions
199 //----------------------------------------------------------------------------
201 /// Basic dependence gathering algorithm, using TarjanSCCIterator on CFG:
203 /// for every SCC S in the CFG in PostOrder on the SCC DAG
205 /// for every basic block BB in S in *postorder*
206 /// for every instruction I in BB in reverse
207 /// Add (I, ModRef[I]) to ModRefCurrent
208 /// if (Mod[I] != NULL)
209 /// Add I to DefSetCurrent: { I \in S : Mod[I] != NULL }
210 /// if (Ref[I] != NULL)
211 /// Add I to UseSetCurrent: { I : Ref[I] != NULL }
213 /// for every def D in DefSetCurrent
215 /// // NOTE: D comes after itself iff S contains a loop
216 /// if (HasLoop(S) && D & D)
217 /// Add output-dep: D -> D2
219 /// for every def D2 *after* D in DefSetCurrent
220 /// // NOTE: D2 comes before D in execution order
222 /// Add output-dep: D2 -> D
224 /// Add output-dep: D -> D2
226 /// for every use U in UseSetCurrent that was seen *before* D
227 /// // NOTE: U comes after D in execution order
229 /// if (U != D || HasLoop(S))
230 /// Add true-dep: D -> U
232 /// Add anti-dep: U -> D
234 /// for every use U in UseSetCurrent that was seen *after* D
235 /// // NOTE: U comes before D in execution order
237 /// if (U != D || HasLoop(S))
238 /// Add anti-dep: U -> D
240 /// Add true-dep: D -> U
242 /// for every def Dnext in DefSetAfter
243 /// // NOTE: Dnext comes after D in execution order
245 /// Add output-dep: D -> Dnext
247 /// for every use Unext in UseSetAfter
248 /// // NOTE: Unext comes after D in execution order
250 /// Add true-dep: D -> Unext
252 /// for every use U in UseSetCurrent
253 /// for every def Dnext in DefSetAfter
254 /// // NOTE: Dnext comes after U in execution order
256 /// Add anti-dep: U -> Dnext
258 /// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
259 /// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
260 /// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
264 void MemoryDepAnalysis::ProcessSCC(SCC<Function*>& S,
265 ModRefTable& ModRefAfter) {
266 ModRefTable ModRefCurrent;
267 ModRefTable::ModRefMap& mapCurrent = ModRefCurrent.modRefMap;
268 ModRefTable::ModRefMap& mapAfter = ModRefAfter.modRefMap;
270 bool hasLoop = S.HasLoop();
272 // Builder class fills out a ModRefTable one instruction at a time.
273 // To use it, we just invoke it's visit function for each basic block:
275 // for each basic block BB in the SCC in *postorder*
276 // for each instruction I in BB in *reverse*
277 // ModRefInfoBuilder::visit(I)
278 // : Add (I, ModRef[I]) to ModRefCurrent.modRefMap
279 // : Add I to ModRefCurrent.definers if it defines any node
280 // : Add I to ModRefCurrent.users if it uses any node
282 ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
283 for (SCC<Function*>::iterator BI=S.begin(), BE=S.end(); BI != BE; ++BI)
284 // Note: BBs in the SCC<> created by TarjanSCCIterator are in postorder.
285 for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
289 /// for every def D in DefSetCurrent
291 for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
292 IE=ModRefCurrent.defsEnd(); II != IE; ++II)
294 /// // NOTE: D comes after itself iff S contains a loop
296 /// Add output-dep: D -> D2
298 funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
300 /// for every def D2 *after* D in DefSetCurrent
301 /// // NOTE: D2 comes before D in execution order
303 /// Add output-dep: D2 -> D
305 /// Add output-dep: D -> D2
306 for (ModRefTable::ref_iterator JI=II+1; JI != IE; ++JI)
307 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
308 mapCurrent.find(*JI)->second.getModSet()))
310 funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
312 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
315 /// for every use U in UseSetCurrent that was seen *before* D
316 /// // NOTE: U comes after D in execution order
318 /// if (U != D || HasLoop(S))
319 /// Add true-dep: U -> D
321 /// Add anti-dep: D -> U
322 ModRefTable::ref_iterator JI=ModRefCurrent.usersBegin();
323 ModRefTable::ref_iterator JE = ModRefCurrent.usersBeforeDef_End(II);
324 for ( ; JI != JE; ++JI)
325 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
326 mapCurrent.find(*JI)->second.getRefSet()))
328 if (*II != *JI || hasLoop)
329 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
331 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
334 /// for every use U in UseSetCurrent that was seen *after* D
335 /// // NOTE: U comes before D in execution order
337 /// if (U != D || HasLoop(S))
338 /// Add anti-dep: U -> D
340 /// Add true-dep: D -> U
341 for (/*continue JI*/ JE = ModRefCurrent.usersEnd(); JI != JE; ++JI)
342 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
343 mapCurrent.find(*JI)->second.getRefSet()))
345 if (*II != *JI || hasLoop)
346 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
348 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
351 /// for every def Dnext in DefSetPrev
352 /// // NOTE: Dnext comes after D in execution order
354 /// Add output-dep: D -> Dnext
355 for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
356 JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
357 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
358 mapAfter.find(*JI)->second.getModSet()))
359 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
361 /// for every use Unext in UseSetAfter
362 /// // NOTE: Unext comes after D in execution order
364 /// Add true-dep: D -> Unext
365 for (ModRefTable::ref_iterator JI=ModRefAfter.usersBegin(),
366 JE=ModRefAfter.usersEnd(); JI != JE; ++JI)
367 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
368 mapAfter.find(*JI)->second.getRefSet()))
369 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
373 /// for every use U in UseSetCurrent
374 /// for every def Dnext in DefSetAfter
375 /// // NOTE: Dnext comes after U in execution order
377 /// Add anti-dep: U -> Dnext
378 for (ModRefTable::ref_iterator II=ModRefCurrent.usersBegin(),
379 IE=ModRefCurrent.usersEnd(); II != IE; ++II)
380 for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
381 JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
382 if (!Disjoint(mapCurrent.find(*II)->second.getRefSet(),
383 mapAfter.find(*JI)->second.getModSet()))
384 funcDepGraph->AddSimpleDependence(**II, **JI, AntiDependence);
386 /// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
387 /// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
388 /// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
389 ModRefAfter.Insert(ModRefCurrent);
393 /// Debugging support methods
395 void MemoryDepAnalysis::print(std::ostream &O) const
398 for (hash_map<Function*, DependenceGraph*>::const_iterator
399 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
401 Function* func = I->first;
402 DependenceGraph* depGraph = I->second;
404 O << "\n================================================================\n";
405 O << "DEPENDENCE GRAPH FOR MEMORY OPERATIONS IN FUNCTION " << func->getName();
406 O << "\n================================================================\n\n";
407 depGraph->print(*func, O);
414 /// Run the pass on a function
416 bool MemoryDepAnalysis::runOnFunction(Function &F) {
417 assert(!F.isExternal());
419 // Get the FunctionModRefInfo holding IPModRef results for this function.
420 // Use the TD graph recorded within the FunctionModRefInfo object, which
421 // may not be the same as the original TD graph computed by DS analysis.
423 funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
424 funcGraph = &funcModRef->getFuncGraph();
426 // TEMPORARY: ptr to depGraph (later just becomes "this").
427 assert(!funcMap.count(&F) && "Analyzing function twice?");
428 funcDepGraph = funcMap[&F] = new DependenceGraph();
430 ModRefTable ModRefAfter;
432 SCC<Function*>* nextSCC;
433 for (TarjanSCC_iterator<Function*> I = tarj_begin(&F), E = tarj_end(&F);
435 ProcessSCC(**I, ModRefAfter);
441 //-------------------------------------------------------------------------
442 // TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
443 // These functions will go away once this class becomes a FunctionPass.
446 // Driver function to compute dependence graphs for every function.
447 // This is temporary and will go away once this is a FunctionPass.
449 bool MemoryDepAnalysis::run(Module& M)
451 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
452 if (! FI->isExternal())
453 runOnFunction(*FI); // automatically inserts each depGraph into funcMap
457 // Release all the dependence graphs in the map.
458 void MemoryDepAnalysis::releaseMemory()
460 for (hash_map<Function*, DependenceGraph*>::const_iterator
461 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
465 // Clear pointers because the pass constructor will not be invoked again.
471 MemoryDepAnalysis::~MemoryDepAnalysis()
476 //----END TEMPORARY FUNCTIONS----------------------------------------------
479 void MemoryDepAnalysis::dump() const
481 this->print(std::cerr);
484 static RegisterAnalysis<MemoryDepAnalysis>
485 Z("memdep", "Memory Dependence Analysis");