blob: 076836a5cea50b106ff4a9e301b59460a0fac032 [file] [log] [blame]
Vikram S. Adve96b21c12002-12-08 13:26:29 +00001//===- MemoryDepAnalysis.cpp - Compute dep graph for memory ops --*-C++-*--===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Vikram S. Adve96b21c12002-12-08 13:26:29 +00009//
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#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"
Vikram S. Adve96b21c12002-12-08 13:26:29 +000024#include "llvm/iMemory.h"
25#include "llvm/iOther.h"
26#include "llvm/Support/InstVisitor.h"
27#include "llvm/Support/CFG.h"
Chris Lattner55b2eb32003-08-31 20:01:57 +000028#include "Support/SCCIterator.h"
Vikram S. Adve96b21c12002-12-08 13:26:29 +000029#include "Support/Statistic.h"
Vikram S. Adve96b21c12002-12-08 13:26:29 +000030#include "Support/STLExtras.h"
31#include "Support/hash_map"
32#include "Support/hash_set"
Vikram S. Adve96b21c12002-12-08 13:26:29 +000033
34
35///--------------------------------------------------------------------------
36/// struct ModRefTable:
37///
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].
44///
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///--------------------------------------------------------------------------
50
Chris Lattner95008bc2003-08-31 19:40:57 +000051struct ModRefTable {
Vikram S. Adve96b21c12002-12-08 13:26:29 +000052 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;
57
58 ModRefMap modRefMap;
59 std::vector<Instruction*> definers;
60 std::vector<Instruction*> users;
61 std::vector<unsigned> numUsersBeforeDef;
62
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(); }
68
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(); }
74
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.
81 //
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];
87 }
88 const_ref_iterator usersBeforeDef_End(const_ref_iterator defPtr) const {
89 return const_cast<ModRefTable*>(this)->usersBeforeDef_End(defPtr);
90 }
91
92 //
93 // Modifier methods
94 //
95 void AddDef(Instruction* D) {
96 definers.push_back(D);
97 numUsersBeforeDef.push_back(users.size());
98 }
99 void AddUse(Instruction* U) {
100 users.push_back(U);
101 }
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 */
109 }
110};
111
112
113///--------------------------------------------------------------------------
114/// class ModRefInfoBuilder:
115///
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///--------------------------------------------------------------------------
121
Chris Lattner80431272003-08-06 17:16:24 +0000122class ModRefInfoBuilder : public InstVisitor<ModRefInfoBuilder> {
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000123 const DSGraph& funcGraph;
124 const FunctionModRefInfo& funcModRef;
125 ModRefTable& modRefTable;
126
Chris Lattner80431272003-08-06 17:16:24 +0000127 ModRefInfoBuilder(); // DO NOT IMPLEMENT
128 ModRefInfoBuilder(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
129 void operator=(const ModRefInfoBuilder&); // DO NOT IMPLEMENT
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000130
131public:
132 /*ctor*/ ModRefInfoBuilder(const DSGraph& _funcGraph,
133 const FunctionModRefInfo& _funcModRef,
134 ModRefTable& _modRefTable)
135 : funcGraph(_funcGraph), funcModRef(_funcModRef), modRefTable(_modRefTable)
136 {
137 }
138
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.
142 //
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;
151 }
152
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);
159 }
160
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())
168 {
169 unsigned nodeId = funcModRef.getNodeId(target);
170 ModRefInfo& minfo =
171 modRefTable.modRefMap.insert(
172 std::make_pair(&storeInst,
173 ModRefInfo(funcGraph.getGraphSize()))).first->second;
174 minfo.setNodeIsMod(nodeId);
175 modRefTable.AddDef(&storeInst);
176 }
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 {
189 unsigned nodeId = funcModRef.getNodeId(target);
190 ModRefInfo& minfo =
191 modRefTable.modRefMap.insert(
192 std::make_pair(&loadInst,
193 ModRefInfo(funcGraph.getGraphSize()))).first->second;
194 minfo.setNodeIsRef(nodeId);
195 modRefTable.AddUse(&loadInst);
196 }
197 else
198 std::cerr << "Warning: Uninitialized pointer reference!\n";
199 }
200};
201
202
203//----------------------------------------------------------------------------
204// class MemoryDepAnalysis: A dep. graph for load/store/call instructions
205//----------------------------------------------------------------------------
206
Chris Lattner95008bc2003-08-31 19:40:57 +0000207
208/// getAnalysisUsage - This does not modify anything. It uses the Top-Down DS
209/// Graph and IPModRef.
210///
211void MemoryDepAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
212 AU.setPreservesAll();
213 AU.addRequired<TDDataStructures>();
214 AU.addRequired<IPModRef>();
215}
216
217
Chris Lattner55b2eb32003-08-31 20:01:57 +0000218/// Basic dependence gathering algorithm, using scc_iterator on CFG:
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000219///
220/// for every SCC S in the CFG in PostOrder on the SCC DAG
221/// {
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 }
229///
230/// for every def D in DefSetCurrent
231///
232/// // NOTE: D comes after itself iff S contains a loop
233/// if (HasLoop(S) && D & D)
234/// Add output-dep: D -> D2
235///
236/// for every def D2 *after* D in DefSetCurrent
237/// // NOTE: D2 comes before D in execution order
238/// if (D & D2)
239/// Add output-dep: D2 -> D
240/// if (HasLoop(S))
241/// Add output-dep: D -> D2
242///
243/// for every use U in UseSetCurrent that was seen *before* D
244/// // NOTE: U comes after D in execution order
245/// if (U & D)
246/// if (U != D || HasLoop(S))
247/// Add true-dep: D -> U
248/// if (HasLoop(S))
249/// Add anti-dep: U -> D
250///
251/// for every use U in UseSetCurrent that was seen *after* D
252/// // NOTE: U comes before D in execution order
253/// if (U & D)
254/// if (U != D || HasLoop(S))
255/// Add anti-dep: U -> D
256/// if (HasLoop(S))
257/// Add true-dep: D -> U
258///
259/// for every def Dnext in DefSetAfter
260/// // NOTE: Dnext comes after D in execution order
261/// if (Dnext & D)
262/// Add output-dep: D -> Dnext
263///
264/// for every use Unext in UseSetAfter
265/// // NOTE: Unext comes after D in execution order
266/// if (Unext & D)
267/// Add true-dep: D -> Unext
268///
269/// for every use U in UseSetCurrent
270/// for every def Dnext in DefSetAfter
271/// // NOTE: Dnext comes after U in execution order
272/// if (Dnext & D)
273/// Add anti-dep: U -> Dnext
274///
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 }
278/// }
279///
280///
Chris Lattnerfe8d8802003-08-31 19:46:48 +0000281void MemoryDepAnalysis::ProcessSCC(std::vector<BasicBlock*> &S,
282 ModRefTable& ModRefAfter, bool hasLoop) {
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000283 ModRefTable ModRefCurrent;
284 ModRefTable::ModRefMap& mapCurrent = ModRefCurrent.modRefMap;
285 ModRefTable::ModRefMap& mapAfter = ModRefAfter.modRefMap;
286
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000287 // 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:
289 //
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
296 //
297 ModRefInfoBuilder builder(*funcGraph, *funcModRef, ModRefCurrent);
Chris Lattnerfe8d8802003-08-31 19:46:48 +0000298 for (std::vector<BasicBlock*>::iterator BI = S.begin(), BE = S.end();
299 BI != BE; ++BI)
Chris Lattner55b2eb32003-08-31 20:01:57 +0000300 // Note: BBs in the SCC<> created by scc_iterator are in postorder.
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000301 for (BasicBlock::reverse_iterator II=(*BI)->rbegin(), IE=(*BI)->rend();
302 II != IE; ++II)
303 builder.visit(*II);
304
305 /// for every def D in DefSetCurrent
306 ///
307 for (ModRefTable::ref_iterator II=ModRefCurrent.defsBegin(),
308 IE=ModRefCurrent.defsEnd(); II != IE; ++II)
309 {
310 /// // NOTE: D comes after itself iff S contains a loop
311 /// if (HasLoop(S))
312 /// Add output-dep: D -> D2
313 if (hasLoop)
314 funcDepGraph->AddSimpleDependence(**II, **II, OutputDependence);
315
316 /// for every def D2 *after* D in DefSetCurrent
317 /// // NOTE: D2 comes before D in execution order
318 /// if (D2 & D)
319 /// Add output-dep: D2 -> D
320 /// if (HasLoop(S))
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()))
325 {
326 funcDepGraph->AddSimpleDependence(**JI, **II, OutputDependence);
327 if (hasLoop)
328 funcDepGraph->AddSimpleDependence(**II, **JI, OutputDependence);
329 }
330
331 /// for every use U in UseSetCurrent that was seen *before* D
332 /// // NOTE: U comes after D in execution order
333 /// if (U & D)
334 /// if (U != D || HasLoop(S))
335 /// Add true-dep: U -> D
336 /// if (HasLoop(S))
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()))
343 {
344 if (*II != *JI || hasLoop)
345 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
346 if (hasLoop)
347 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
348 }
349
350 /// for every use U in UseSetCurrent that was seen *after* D
351 /// // NOTE: U comes before D in execution order
352 /// if (U & D)
353 /// if (U != D || HasLoop(S))
354 /// Add anti-dep: U -> D
355 /// if (HasLoop(S))
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()))
360 {
361 if (*II != *JI || hasLoop)
362 funcDepGraph->AddSimpleDependence(**JI, **II, AntiDependence);
363 if (hasLoop)
364 funcDepGraph->AddSimpleDependence(**II, **JI, TrueDependence);
365 }
366
367 /// for every def Dnext in DefSetPrev
368 /// // NOTE: Dnext comes after D in execution order
369 /// if (Dnext & D)
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);
376
377 /// for every use Unext in UseSetAfter
378 /// // NOTE: Unext comes after D in execution order
379 /// if (Unext & D)
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);
386 }
387
388 ///
389 /// for every use U in UseSetCurrent
390 /// for every def Dnext in DefSetAfter
391 /// // NOTE: Dnext comes after U in execution order
392 /// if (Dnext & D)
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);
401
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);
406}
407
408
409/// Debugging support methods
410///
411void MemoryDepAnalysis::print(std::ostream &O) const
412{
413 // TEMPORARY LOOP
414 for (hash_map<Function*, DependenceGraph*>::const_iterator
415 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
416 {
417 Function* func = I->first;
418 DependenceGraph* depGraph = I->second;
419
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);
424
425 }
426}
427
428
429///
430/// Run the pass on a function
431///
Chris Lattner0c0023b2003-08-31 19:29:52 +0000432bool MemoryDepAnalysis::runOnFunction(Function &F) {
433 assert(!F.isExternal());
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000434
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.
438 //
Chris Lattner0c0023b2003-08-31 19:29:52 +0000439 funcModRef = &getAnalysis<IPModRef>().getFunctionModRefInfo(F);
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000440 funcGraph = &funcModRef->getFuncGraph();
441
442 // TEMPORARY: ptr to depGraph (later just becomes "this").
Chris Lattner0c0023b2003-08-31 19:29:52 +0000443 assert(!funcMap.count(&F) && "Analyzing function twice?");
444 funcDepGraph = funcMap[&F] = new DependenceGraph();
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000445
446 ModRefTable ModRefAfter;
447
Chris Lattner55b2eb32003-08-31 20:01:57 +0000448 for (scc_iterator<Function*> I = scc_begin(&F), E = scc_end(&F); I != E; ++I)
Chris Lattner9f2a06e2003-08-31 19:51:38 +0000449 ProcessSCC(*I, ModRefAfter, I.hasLoop());
Vikram S. Adve96b21c12002-12-08 13:26:29 +0000450
451 return true;
452}
453
454
455//-------------------------------------------------------------------------
456// TEMPORARY FUNCTIONS TO MAKE THIS A MODULE PASS ---
457// These functions will go away once this class becomes a FunctionPass.
458//
459
460// Driver function to compute dependence graphs for every function.
461// This is temporary and will go away once this is a FunctionPass.
462//
463bool MemoryDepAnalysis::run(Module& M)
464{
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
468 return true;
469}
470
471// Release all the dependence graphs in the map.
472void MemoryDepAnalysis::releaseMemory()
473{
474 for (hash_map<Function*, DependenceGraph*>::const_iterator
475 I = funcMap.begin(), E = funcMap.end(); I != E; ++I)
476 delete I->second;
477 funcMap.clear();
478
479 // Clear pointers because the pass constructor will not be invoked again.
480 funcDepGraph = NULL;
481 funcGraph = NULL;
482 funcModRef = NULL;
483}
484
485MemoryDepAnalysis::~MemoryDepAnalysis()
486{
487 releaseMemory();
488}
489
490//----END TEMPORARY FUNCTIONS----------------------------------------------
491
492
493void MemoryDepAnalysis::dump() const
494{
495 this->print(std::cerr);
496}
497
498static RegisterAnalysis<MemoryDepAnalysis>
499Z("memdep", "Memory Dependence Analysis");
500