1 //===- MemoryDepAnalysis.cpp - Compute dep graph for memory ops --*-C++-*--===//
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.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Analysis/MemoryDepAnalysis.h"
20 #include "llvm/Analysis/IPModRef.h"
21 #include "llvm/Analysis/DataStructure.h"
22 #include "llvm/Analysis/DSGraph.h"
23 #include "llvm/Module.h"
24 #include "llvm/iMemory.h"
25 #include "llvm/iOther.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "llvm/Support/CFG.h"
28 #include "Support/SCCIterator.h"
29 #include "Support/Statistic.h"
30 #include "Support/STLExtras.h"
31 #include "Support/hash_map"
32 #include "Support/hash_set"
35 ///--------------------------------------------------------------------------
36 /// struct ModRefTable:
38 /// A data structure that tracks ModRefInfo for instructions:
39 /// -- modRefMap is a map of Instruction* -> ModRefInfo for the instr.
40 /// -- definers is a vector of instructions that define any node
41 /// -- users is a vector of instructions that reference any node
42 /// -- numUsersBeforeDef is a vector indicating that the number of users
43 /// seen before definers[i] is numUsersBeforeDef[i].
45 /// numUsersBeforeDef[] effectively tells us the exact interleaving of
46 /// definers and users within the ModRefTable.
47 /// This is only maintained when constructing the table for one SCC, and
48 /// not copied over from one table to another since it is no longer useful.
49 ///--------------------------------------------------------------------------
52 typedef hash_map<Instruction*, ModRefInfo> ModRefMap;
53 typedef ModRefMap::const_iterator const_map_iterator;
54 typedef ModRefMap:: iterator map_iterator;
55 typedef std::vector<Instruction*>::const_iterator const_ref_iterator;
56 typedef std::vector<Instruction*>:: iterator ref_iterator;
59 std::vector<Instruction*> definers;
60 std::vector<Instruction*> users;
61 std::vector<unsigned> numUsersBeforeDef;
63 // Iterators to enumerate all the defining instructions
64 const_ref_iterator defsBegin() const { return definers.begin(); }
65 ref_iterator defsBegin() { return definers.begin(); }
66 const_ref_iterator defsEnd() const { return definers.end(); }
67 ref_iterator defsEnd() { return definers.end(); }
69 // Iterators to enumerate all the user instructions
70 const_ref_iterator usersBegin() const { return users.begin(); }
71 ref_iterator usersBegin() { return users.begin(); }
72 const_ref_iterator usersEnd() const { return users.end(); }
73 ref_iterator usersEnd() { return users.end(); }
75 // Iterator identifying the last user that was seen *before* a
76 // specified def. In particular, all users in the half-closed range
77 // [ usersBegin(), usersBeforeDef_End(defPtr) )
78 // were seen *before* the specified def. All users in the half-closed range
79 // [ usersBeforeDef_End(defPtr), usersEnd() )
80 // were seen *after* the specified def.
82 ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) {
83 unsigned defIndex = (unsigned) (defPtr - defsBegin());
84 assert(defIndex < numUsersBeforeDef.size());
85 assert(usersBegin() + numUsersBeforeDef[defIndex] <= usersEnd());
86 return usersBegin() + numUsersBeforeDef[defIndex];
88 const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
89 return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
95 void AddDef(Instruction* D) {
96 definers.push_back(D);
97 numUsersBeforeDef.push_back(users.size());
99 void AddUse(Instruction* U) {
102 void Insert(const ModRefTable& fromTable) {
103 modRefMap.insert(fromTable.modRefMap.begin(), fromTable.modRefMap.end());
104 definers.insert(definers.end(),
105 fromTable.definers.begin(), fromTable.definers.end());
106 users.insert(users.end(),
107 fromTable.users.begin(), fromTable.users.end());
108 numUsersBeforeDef.clear(); /* fromTable.numUsersBeforeDef is ignored */
113 ///--------------------------------------------------------------------------
114 /// class ModRefInfoBuilder:
116 /// A simple InstVisitor<> class that retrieves the Mod/Ref info for
117 /// Load/Store/Call instructions and inserts this information in
118 /// a ModRefTable. It also records all instructions that Mod any node
119 /// and all that use any node.
120 ///--------------------------------------------------------------------------
122 class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
123 const DSGraph& funcGraph;
124 const FunctionModRefInfo& funcModRef;
125 ModRefTable& modRefTable;
127 ModRefInfoBuilder(); // DO NOT IMPLEMENT
128 ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
129 void operator=(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
132 /*ctor*/ ModRefInfoBuilder(const DSGraph& _funcGraph,
133 const FunctionModRefInfo& _funcModRef,
134 ModRefTable& _modRefTable)
135 : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
139 // At a call instruction, retrieve the ModRefInfo using IPModRef results.
140 // Add the call to the defs list if it modifies any nodes and to the uses
141 // list if it refs any nodes.
143 void visitCallInst (CallInst& callInst) {
144 ModRefInfo safeModRef(funcGraph.getGraphSize());
145 const ModRefInfo* callModRef = funcModRef.getModRefInfo(callInst);
146 if (callModRef == NULL)
147 { // call to external/unknown function: mark all nodes as Mod and Ref
148 safeModRef.getModSet().set();
149 safeModRef.getRefSet().set();
150 callModRef = &safeModRef;
153 modRefTable.modRefMap.insert(std::make_pair(&callInst,
154 ModRefInfo(*callModRef)));
155 if (callModRef->getModSet().any())
156 modRefTable.AddDef(&callInst);
157 if (callModRef->getRefSet().any())
158 modRefTable.AddUse(&callInst);
161 // At a store instruction, add to the mod set the single node pointed to
162 // by the pointer argument of the store. Interestingly, if there is no
163 // such node, that would be a null pointer reference!
164 void visitStoreInst (StoreInst& storeInst) {
165 const DSNodeHandle& ptrNode =
166 funcGraph.getNodeForValue(storeInst.getPointerOperand());
167 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);
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())
189 unsigned nodeId = funcModRef.getNodeId(target);
191 modRefTable.modRefMap.insert(
192 std::make_pair(&loadInst,
193 ModRefInfo(funcGraph.getGraphSize()))).first->second;
194 minfo.setNodeIsRef(nodeId);
195 modRefTable.AddUse(&loadInst);
198 std::cerr << "Warning: Uninitialized pointer reference!\n";
203 //----------------------------------------------------------------------------
204 // class MemoryDepAnalysis: A dep. graph for load/store/call instructions
205 //----------------------------------------------------------------------------
208 /// getAnalysisUsage - This does not modify anything. It uses the Top-Down DS
209 /// Graph and IPModRef.
211 void MemoryDepAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
212 AU.setPreservesAll();
213 AU.addRequired<TDDataStructures>();
214 AU.addRequired<IPModRef>();
218 /// Basic dependence gathering algorithm, using scc_iterator on CFG:
220 /// for every SCC S in the CFG in PostOrder on the SCC DAG
222 /// for every basic block BB in S in *postorder*
223 /// for every instruction I in BB in reverse
224 /// Add (I, ModRef[I]) to ModRefCurrent
225 /// if (Mod[I] != NULL)
226 /// Add I to DefSetCurrent: { I \in S : Mod[I] != NULL }
227 /// if (Ref[I] != NULL)
228 /// Add I to UseSetCurrent: { I : Ref[I] != NULL }
230 /// for every def D in DefSetCurrent
232 /// // NOTE: D comes after itself iff S contains a loop
233 /// if (HasLoop(S) && D & D)
234 /// Add output-dep: D -> D2
236 /// for every def D2 *after* D in DefSetCurrent
237 /// // NOTE: D2 comes before D in execution order
239 /// Add output-dep: D2 -> D
241 /// Add output-dep: D -> D2
243 /// for every use U in UseSetCurrent that was seen *before* D
244 /// // NOTE: U comes after D in execution order
246 /// if (U != D || HasLoop(S))
247 /// Add true-dep: D -> U
249 /// Add anti-dep: U -> D
251 /// for every use U in UseSetCurrent that was seen *after* D
252 /// // NOTE: U comes before D in execution order
254 /// if (U != D || HasLoop(S))
255 /// Add anti-dep: U -> D
257 /// Add true-dep: D -> U
259 /// for every def Dnext in DefSetAfter
260 /// // NOTE: Dnext comes after D in execution order
262 /// Add output-dep: D -> Dnext
264 /// for every use Unext in UseSetAfter
265 /// // NOTE: Unext comes after D in execution order
267 /// Add true-dep: D -> Unext
269 /// for every use U in UseSetCurrent
270 /// for every def Dnext in DefSetAfter
271 /// // NOTE: Dnext comes after U in execution order
273 /// Add anti-dep: U -> Dnext
275 /// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
276 /// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
277 /// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
281 void MemoryDepAnalysis::ProcessSCC(std::vector<BasicBlock*> &S,
282 ModRefTable& ModRefAfter, bool hasLoop) {
283 ModRefTable ModRefCurrent;
284 ModRefTable::ModRefMap& mapCurrent = ModRefCurrent.modRefMap;
285 ModRefTable::ModRefMap& mapAfter = ModRefAfter.modRefMap;
287 // Builder class fills out a ModRefTable one instruction at a time.
288 // To use it, we just invoke it's visit function for each basic block:
290 // for each basic block BB in the SCC in *postorder*
291 // for each instruction I in BB in *reverse*
292 // ModRefInfoBuilder::visit(I)
293 // : Add (I, ModRef[I]) to ModRefCurrent.modRefMap
294 // : Add I to ModRefCurrent.definers if it defines any node
295 // : Add I to ModRefCurrent.users if it uses any node
297 ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
298 for (std::vector<BasicBlock*>::iterator BI = S.begin(), BE = S.end();
300 // Note: BBs in the SCC<> created by scc_iterator are in postorder.
301 for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
305 /// for every def D in DefSetCurrent
307 for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
308 IE=ModRefCurrent.defsEnd(); II != IE; ++II)
310 /// // NOTE: D comes after itself iff S contains a loop
312 /// Add output-dep: D -> D2
314 funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
316 /// for every def D2 *after* D in DefSetCurrent
317 /// // NOTE: D2 comes before D in execution order
319 /// Add output-dep: D2 -> D
321 /// Add output-dep: D -> D2
322 for (ModRefTable::ref_iterator JI=II+1; JI != IE; ++JI)
323 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
324 mapCurrent.find(*JI)->second.getModSet()))
326 funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
328 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
331 /// for every use U in UseSetCurrent that was seen *before* D
332 /// // NOTE: U comes after D in execution order
334 /// if (U != D || HasLoop(S))
335 /// Add true-dep: U -> D
337 /// Add anti-dep: D -> U
338 ModRefTable::ref_iterator JI=ModRefCurrent.usersBegin();
339 ModRefTable::ref_iterator JE = ModRefCurrent.usersBeforeDef_End(II);
340 for ( ; JI != JE; ++JI)
341 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
342 mapCurrent.find(*JI)->second.getRefSet()))
344 if (*II != *JI || hasLoop)
345 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
347 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
350 /// for every use U in UseSetCurrent that was seen *after* D
351 /// // NOTE: U comes before D in execution order
353 /// if (U != D || HasLoop(S))
354 /// Add anti-dep: U -> D
356 /// Add true-dep: D -> U
357 for (/*continue JI*/ JE = ModRefCurrent.usersEnd(); JI != JE; ++JI)
358 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
359 mapCurrent.find(*JI)->second.getRefSet()))
361 if (*II != *JI || hasLoop)
362 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
364 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
367 /// for every def Dnext in DefSetPrev
368 /// // NOTE: Dnext comes after D in execution order
370 /// Add output-dep: D -> Dnext
371 for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
372 JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
373 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
374 mapAfter.find(*JI)->second.getModSet()))
375 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
377 /// for every use Unext in UseSetAfter
378 /// // NOTE: Unext comes after D in execution order
380 /// Add true-dep: D -> Unext
381 for (ModRefTable::ref_iterator JI=ModRefAfter.usersBegin(),
382 JE=ModRefAfter.usersEnd(); JI != JE; ++JI)
383 if (!Disjoint(mapCurrent.find(*II)->second.getModSet(),
384 mapAfter.find(*JI)->second.getRefSet()))
385 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
389 /// for every use U in UseSetCurrent
390 /// for every def Dnext in DefSetAfter
391 /// // NOTE: Dnext comes after U in execution order
393 /// Add anti-dep: U -> Dnext
394 for (ModRefTable::ref_iterator II=ModRefCurrent.usersBegin(),
395 IE=ModRefCurrent.usersEnd(); II != IE; ++II)
396 for (ModRefTable::ref_iterator JI=ModRefAfter.defsBegin(),
397 JE=ModRefAfter.defsEnd(); JI != JE; ++JI)
398 if (!Disjoint(mapCurrent.find(*II)->second.getRefSet(),
399 mapAfter.find(*JI)->second.getModSet()))
400 funcDepGraph->AddSimpleDependence(**II, **JI, AntiDependence);
402 /// Add ModRefCurrent to ModRefAfter: { (I, ModRef[I] ) }
403 /// Add DefSetCurrent to DefSetAfter: { I : Mod[I] != NULL }
404 /// Add UseSetCurrent to UseSetAfter: { I : Ref[I] != NULL }
405 ModRefAfter.Insert(ModRefCurrent);
409 /// Debugging support methods
411 void MemoryDepAnalysis::print(std::ostream &O) const
414 for (hash_map<Function*, DependenceGraph*>::const_iterator
415 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
417 Function* func = I->first;
418 DependenceGraph* depGraph = I->second;
420 O << "\n================================================================\n";
421 O << "DEPENDENCE GRAPH FOR MEMORY OPERATIONS IN FUNCTION " << func->getName();
422 O << "\n================================================================\n\n";
423 depGraph->print(*func, O);
430 /// Run the pass on a function
432 bool MemoryDepAnalysis::runOnFunction(Function &F) {
433 assert(!F.isExternal());
435 // Get the FunctionModRefInfo holding IPModRef results for this function.
436 // Use the TD graph recorded within the FunctionModRefInfo object, which
437 // may not be the same as the original TD graph computed by DS analysis.
439 funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
440 funcGraph = &funcModRef->getFuncGraph();
442 // TEMPORARY: ptr to depGraph (later just becomes "this").
443 assert(!funcMap.count(&F) && "Analyzing function twice?");
444 funcDepGraph = funcMap[&F] = new DependenceGraph();
446 ModRefTable ModRefAfter;
448 for (scc_iterator<Function*> I = scc_begin(&F), E = scc_end(&F); I != E; ++I)
449 ProcessSCC(*I, ModRefAfter, I.hasLoop());
455 //-------------------------------------------------------------------------
456 // TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
457 // These functions will go away once this class becomes a FunctionPass.
460 // Driver function to compute dependence graphs for every function.
461 // This is temporary and will go away once this is a FunctionPass.
463 bool MemoryDepAnalysis::run(Module& M)
465 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
466 if (! FI->isExternal())
467 runOnFunction(*FI); // automatically inserts each depGraph into funcMap
471 // Release all the dependence graphs in the map.
472 void MemoryDepAnalysis::releaseMemory()
474 for (hash_map<Function*, DependenceGraph*>::const_iterator
475 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
479 // Clear pointers because the pass constructor will not be invoked again.
485 MemoryDepAnalysis::~MemoryDepAnalysis()
490 //----END TEMPORARY FUNCTIONS----------------------------------------------
493 void MemoryDepAnalysis::dump() const
495 this->print(std::cerr);
498 static RegisterAnalysis<MemoryDepAnalysis>
499 Z("memdep", "Memory Dependence Analysis");