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 ///--------------------------------------------------------------------------
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;
61 std::vector<Instruction*> definers;
62 std::vector<Instruction*> users;
63 std::vector<unsigned> numUsersBeforeDef;
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(); }
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(); }
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.
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];
90 const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
91 return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
97 void AddDef(Instruction* D) {
98 definers.push_back(D);
99 numUsersBeforeDef.push_back(users.size());
101 void AddUse(Instruction* U) {
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 */
115 ///--------------------------------------------------------------------------
116 /// class ModRefInfoBuilder:
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 ///--------------------------------------------------------------------------
124 class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
125 const DSGraph& funcGraph;
126 const FunctionModRefInfo& funcModRef;
127 struct ModRefTable& modRefTable;
129 ModRefInfoBuilder(); // DO NOT IMPLEMENT
130 ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
131 void operator=(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
134 ModRefInfoBuilder(const DSGraph& _funcGraph,
135 const FunctionModRefInfo& _funcModRef,
136 ModRefTable& _modRefTable)
137 : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
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.
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;
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);
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);
172 modRefTable.modRefMap.insert(
173 std::make_pair(&storeInst,
174 ModRefInfo(funcGraph.getGraphSize()))).first->second;
175 minfo.setNodeIsMod(nodeId);
176 modRefTable.AddDef(&storeInst);
178 std::cerr << "Warning: Uninitialized pointer reference!\n";
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);
190 modRefTable.modRefMap.insert(
191 std::make_pair(&loadInst,
192 ModRefInfo(funcGraph.getGraphSize()))).first->second;
193 minfo.setNodeIsRef(nodeId);
194 modRefTable.AddUse(&loadInst);
196 std::cerr << "Warning: Uninitialized pointer reference!\n";
201 //----------------------------------------------------------------------------
202 // class MemoryDepAnalysis: A dep. graph for load/store/call instructions
203 //----------------------------------------------------------------------------
206 /// getAnalysisUsage - This does not modify anything. It uses the Top-Down DS
207 /// Graph and IPModRef.
209 void MemoryDepAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
210 AU.setPreservesAll();
211 AU.addRequired<TDDataStructures>();
212 AU.addRequired<IPModRef>();
216 /// Basic dependence gathering algorithm, using scc_iterator on CFG:
218 /// for every SCC S in the CFG in PostOrder on the SCC DAG
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 }
228 /// for every def D in DefSetCurrent
230 /// // NOTE: D comes after itself iff S contains a loop
231 /// if (HasLoop(S) && D & D)
232 /// Add output-dep: D -> D2
234 /// for every def D2 *after* D in DefSetCurrent
235 /// // NOTE: D2 comes before D in execution order
237 /// Add output-dep: D2 -> D
239 /// Add output-dep: D -> D2
241 /// for every use U in UseSetCurrent that was seen *before* D
242 /// // NOTE: U comes after D in execution order
244 /// if (U != D || HasLoop(S))
245 /// Add true-dep: D -> U
247 /// Add anti-dep: U -> D
249 /// for every use U in UseSetCurrent that was seen *after* D
250 /// // NOTE: U comes before D in execution order
252 /// if (U != D || HasLoop(S))
253 /// Add anti-dep: U -> D
255 /// Add true-dep: D -> U
257 /// for every def Dnext in DefSetAfter
258 /// // NOTE: Dnext comes after D in execution order
260 /// Add output-dep: D -> Dnext
262 /// for every use Unext in UseSetAfter
263 /// // NOTE: Unext comes after D in execution order
265 /// Add true-dep: D -> Unext
267 /// for every use U in UseSetCurrent
268 /// for every def Dnext in DefSetAfter
269 /// // NOTE: Dnext comes after U in execution order
271 /// Add anti-dep: U -> Dnext
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 }
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;
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:
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
295 ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
296 for (std::vector<BasicBlock*>::iterator BI = S.begin(), BE = S.end();
298 // Note: BBs in the SCC<> created by scc_iterator are in postorder.
299 for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
303 /// for every def D in DefSetCurrent
305 for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
306 IE=ModRefCurrent.defsEnd(); II != IE; ++II)
308 /// // NOTE: D comes after itself iff S contains a loop
310 /// Add output-dep: D -> D2
312 funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
314 /// for every def D2 *after* D in DefSetCurrent
315 /// // NOTE: D2 comes before D in execution order
317 /// Add output-dep: D2 -> D
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()))
324 funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
326 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
329 /// for every use U in UseSetCurrent that was seen *before* D
330 /// // NOTE: U comes after D in execution order
332 /// if (U != D || HasLoop(S))
333 /// Add true-dep: U -> D
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()))
342 if (*II != *JI || hasLoop)
343 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
345 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
348 /// for every use U in UseSetCurrent that was seen *after* D
349 /// // NOTE: U comes before D in execution order
351 /// if (U != D || HasLoop(S))
352 /// Add anti-dep: U -> D
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()))
359 if (*II != *JI || hasLoop)
360 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
362 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
365 /// for every def Dnext in DefSetPrev
366 /// // NOTE: Dnext comes after D in execution order
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);
375 /// for every use Unext in UseSetAfter
376 /// // NOTE: Unext comes after D in execution order
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);
387 /// for every use U in UseSetCurrent
388 /// for every def Dnext in DefSetAfter
389 /// // NOTE: Dnext comes after U in execution order
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);
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);
407 /// Debugging support methods
409 void MemoryDepAnalysis::print(std::ostream &O, const Module*) const
412 for (hash_map<Function*, DependenceGraph*>::const_iterator
413 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
415 Function* func = I->first;
416 DependenceGraph* depGraph = I->second;
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);
428 /// Run the pass on a function
430 bool MemoryDepAnalysis::runOnFunction(Function &F) {
431 assert(!F.isExternal());
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.
437 funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
438 funcGraph = &funcModRef->getFuncGraph();
440 // TEMPORARY: ptr to depGraph (later just becomes "this").
441 assert(!funcMap.count(&F) && "Analyzing function twice?");
442 funcDepGraph = funcMap[&F] = new DependenceGraph();
444 ModRefTable ModRefAfter;
446 for (scc_iterator<Function*> I = scc_begin(&F), E = scc_end(&F); I != E; ++I)
447 ProcessSCC(*I, ModRefAfter, I.hasLoop());
453 //-------------------------------------------------------------------------
454 // TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
455 // These functions will go away once this class becomes a FunctionPass.
458 // Driver function to compute dependence graphs for every function.
459 // This is temporary and will go away once this is a FunctionPass.
461 bool MemoryDepAnalysis::runOnModule(Module& M)
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
469 // Release all the dependence graphs in the map.
470 void MemoryDepAnalysis::releaseMemory()
472 for (hash_map<Function*, DependenceGraph*>::const_iterator
473 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
477 // Clear pointers because the pass constructor will not be invoked again.
483 MemoryDepAnalysis::~MemoryDepAnalysis()
488 //----END TEMPORARY FUNCTIONS----------------------------------------------
491 void MemoryDepAnalysis::dump() const
493 this->print(std::cerr);
496 static RegisterAnalysis<MemoryDepAnalysis>
497 Z("memdep", "Memory Dependence Analysis");
500 } // End llvm namespace