1 //===- MemoryDepAnalysis.cpp - Compute dep graph for memory ops -----------===//
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 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.
15 // The result of this pass is a DependenceGraph for each function
16 // representing the memory-based data dependences between instructions.
18 //===----------------------------------------------------------------------===//
20 #include "MemoryDepAnalysis.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"
36 ///--------------------------------------------------------------------------
37 /// struct ModRefTable:
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].
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 ///--------------------------------------------------------------------------
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;
60 std::vector<Instruction*> definers;
61 std::vector<Instruction*> users;
62 std::vector<unsigned> numUsersBeforeDef;
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(); }
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(); }
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.
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];
89 const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
90 return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
96 void AddDef(Instruction* D) {
97 definers.push_back(D);
98 numUsersBeforeDef.push_back(users.size());
100 void AddUse(Instruction* U) {
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 */
114 ///--------------------------------------------------------------------------
115 /// class ModRefInfoBuilder:
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 ///--------------------------------------------------------------------------
123 class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
124 const DSGraph& funcGraph;
125 const FunctionModRefInfo& funcModRef;
126 struct ModRefTable& modRefTable;
128 ModRefInfoBuilder(); // DO NOT IMPLEMENT
129 ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
130 void operator=(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
133 ModRefInfoBuilder(const DSGraph& _funcGraph,
134 const FunctionModRefInfo& _funcModRef,
135 ModRefTable& _modRefTable)
136 : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
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.
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;
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);
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);
171 modRefTable.modRefMap.insert(
172 std::make_pair(&storeInst,
173 ModRefInfo(funcGraph.getGraphSize()))).first->second;
174 minfo.setNodeIsMod(nodeId);
175 modRefTable.AddDef(&storeInst);
177 std::cerr << "Warning: Uninitialized pointer reference!\n";
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);
189 modRefTable.modRefMap.insert(
190 std::make_pair(&loadInst,
191 ModRefInfo(funcGraph.getGraphSize()))).first->second;
192 minfo.setNodeIsRef(nodeId);
193 modRefTable.AddUse(&loadInst);
195 std::cerr << "Warning: Uninitialized pointer reference!\n";
200 //----------------------------------------------------------------------------
201 // class MemoryDepAnalysis: A dep. graph for load/store/call instructions
202 //----------------------------------------------------------------------------
205 /// getAnalysisUsage - This does not modify anything. It uses the Top-Down DS
206 /// Graph and IPModRef.
208 void MemoryDepAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
209 AU.setPreservesAll();
210 AU.addRequired<TDDataStructures>();
211 AU.addRequired<IPModRef>();
215 /// Basic dependence gathering algorithm, using scc_iterator on CFG:
217 /// for every SCC S in the CFG in PostOrder on the SCC DAG
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 }
227 /// for every def D in DefSetCurrent
229 /// // NOTE: D comes after itself iff S contains a loop
230 /// if (HasLoop(S) && D & D)
231 /// Add output-dep: D -> D2
233 /// for every def D2 *after* D in DefSetCurrent
234 /// // NOTE: D2 comes before D in execution order
236 /// Add output-dep: D2 -> D
238 /// Add output-dep: D -> D2
240 /// for every use U in UseSetCurrent that was seen *before* D
241 /// // NOTE: U comes after D in execution order
243 /// if (U != D || HasLoop(S))
244 /// Add true-dep: D -> U
246 /// Add anti-dep: U -> D
248 /// for every use U in UseSetCurrent that was seen *after* D
249 /// // NOTE: U comes before D in execution order
251 /// if (U != D || HasLoop(S))
252 /// Add anti-dep: U -> D
254 /// Add true-dep: D -> U
256 /// for every def Dnext in DefSetAfter
257 /// // NOTE: Dnext comes after D in execution order
259 /// Add output-dep: D -> Dnext
261 /// for every use Unext in UseSetAfter
262 /// // NOTE: Unext comes after D in execution order
264 /// Add true-dep: D -> Unext
266 /// for every use U in UseSetCurrent
267 /// for every def Dnext in DefSetAfter
268 /// // NOTE: Dnext comes after U in execution order
270 /// Add anti-dep: U -> Dnext
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 }
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;
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:
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
294 ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
295 for (std::vector<BasicBlock*>::iterator BI = S.begin(), BE = S.end();
297 // Note: BBs in the SCC<> created by scc_iterator are in postorder.
298 for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
302 /// for every def D in DefSetCurrent
304 for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
305 IE=ModRefCurrent.defsEnd(); II != IE; ++II)
307 /// // NOTE: D comes after itself iff S contains a loop
309 /// Add output-dep: D -> D2
311 funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
313 /// for every def D2 *after* D in DefSetCurrent
314 /// // NOTE: D2 comes before D in execution order
316 /// Add output-dep: D2 -> D
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()))
323 funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
325 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
328 /// for every use U in UseSetCurrent that was seen *before* D
329 /// // NOTE: U comes after D in execution order
331 /// if (U != D || HasLoop(S))
332 /// Add true-dep: U -> D
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()))
341 if (*II != *JI || hasLoop)
342 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
344 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
347 /// for every use U in UseSetCurrent that was seen *after* D
348 /// // NOTE: U comes before D in execution order
350 /// if (U != D || HasLoop(S))
351 /// Add anti-dep: U -> D
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()))
358 if (*II != *JI || hasLoop)
359 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
361 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
364 /// for every def Dnext in DefSetPrev
365 /// // NOTE: Dnext comes after D in execution order
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);
374 /// for every use Unext in UseSetAfter
375 /// // NOTE: Unext comes after D in execution order
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);
386 /// for every use U in UseSetCurrent
387 /// for every def Dnext in DefSetAfter
388 /// // NOTE: Dnext comes after U in execution order
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);
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);
406 /// Debugging support methods
408 void MemoryDepAnalysis::print(std::ostream &O) const
411 for (hash_map<Function*, DependenceGraph*>::const_iterator
412 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
414 Function* func = I->first;
415 DependenceGraph* depGraph = I->second;
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);
427 /// Run the pass on a function
429 bool MemoryDepAnalysis::runOnFunction(Function &F) {
430 assert(!F.isExternal());
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.
436 funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
437 funcGraph = &funcModRef->getFuncGraph();
439 // TEMPORARY: ptr to depGraph (later just becomes "this").
440 assert(!funcMap.count(&F) && "Analyzing function twice?");
441 funcDepGraph = funcMap[&F] = new DependenceGraph();
443 ModRefTable ModRefAfter;
445 for (scc_iterator<Function*> I = scc_begin(&F), E = scc_end(&F); I != E; ++I)
446 ProcessSCC(*I, ModRefAfter, I.hasLoop());
452 //-------------------------------------------------------------------------
453 // TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
454 // These functions will go away once this class becomes a FunctionPass.
457 // Driver function to compute dependence graphs for every function.
458 // This is temporary and will go away once this is a FunctionPass.
460 bool MemoryDepAnalysis::runOnModule(Module& M)
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
468 // Release all the dependence graphs in the map.
469 void MemoryDepAnalysis::releaseMemory()
471 for (hash_map<Function*, DependenceGraph*>::const_iterator
472 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
476 // Clear pointers because the pass constructor will not be invoked again.
482 MemoryDepAnalysis::~MemoryDepAnalysis()
487 //----END TEMPORARY FUNCTIONS----------------------------------------------
490 void MemoryDepAnalysis::dump() const
492 this->print(std::cerr);
495 static RegisterAnalysis<MemoryDepAnalysis>
496 Z("memdep", "Memory Dependence Analysis");
499 } // End llvm namespace