fd39b6b12a5e0786f135435df65c25883ca515d7
[oota-llvm.git] / lib / Analysis / DataStructure / Parallelize.cpp
1 //===- Parallelize.cpp - Auto parallelization using DS Graphs -------------===//
2 // 
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 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a pass that automatically parallelizes a program,
11 // using the Cilk multi-threaded runtime system to execute parallel code.
12 // 
13 // The pass uses the Program Dependence Graph (class PDGIterator) to
14 // identify parallelizable function calls, i.e., calls whose instances
15 // can be executed in parallel with instances of other function calls.
16 // (In the future, this should also execute different instances of the same
17 // function call in parallel, but that requires parallelizing across
18 // loop iterations.)
19 //
20 // The output of the pass is LLVM code with:
21 // (1) all parallelizable functions renamed to flag them as parallelizable;
22 // (2) calls to a sync() function introduced at synchronization points.
23 // The CWriter recognizes these functions and inserts the appropriate Cilk
24 // keywords when writing out C code.  This C code must be compiled with cilk2c.
25 // 
26 // Current algorithmic limitations:
27 // -- no array dependence analysis
28 // -- no parallelization for function calls in different loop iterations
29 //    (except in unlikely trivial cases)
30 //
31 // Limitations of using Cilk:
32 // -- No parallelism within a function body, e.g., in a loop;
33 // -- Simplistic synchronization model requiring all parallel threads 
34 //    created within a function to block at a sync().
35 // -- Excessive overhead at "spawned" function calls, which has no benefit
36 //    once all threads are busy (especially common when the degree of
37 //    parallelism is low).
38 //
39 //===----------------------------------------------------------------------===//
40
41 #include "llvm/Transforms/Utils/DemoteRegToStack.h"
42 #include "llvm/Analysis/PgmDependenceGraph.h"
43 #include "llvm/Analysis/DataStructure.h"
44 #include "llvm/Analysis/DSGraph.h"
45 #include "llvm/Module.h"
46 #include "llvm/Instructions.h"
47 #include "llvm/DerivedTypes.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "Support/Statistic.h"
50 #include "Support/STLExtras.h"
51 #include "Support/hash_set"
52 #include "Support/hash_map"
53 #include <functional>
54 #include <algorithm>
55
56 namespace llvm {
57
58 //---------------------------------------------------------------------------- 
59 // Global constants used in marking Cilk functions and function calls.
60 //---------------------------------------------------------------------------- 
61
62 static const char * const CilkSuffix = ".llvm2cilk";
63 static const char * const DummySyncFuncName = "__sync.llvm2cilk";
64
65 //---------------------------------------------------------------------------- 
66 // Routines to identify Cilk functions, calls to Cilk functions, and syncs.
67 //---------------------------------------------------------------------------- 
68
69 static bool isCilk(const Function& F) {
70   return (F.getName().rfind(CilkSuffix) ==
71           F.getName().size() - std::strlen(CilkSuffix));
72 }
73
74 static bool isCilkMain(const Function& F) {
75   return F.getName() == "main" + std::string(CilkSuffix);
76 }
77
78
79 static bool isCilk(const CallInst& CI) {
80   return CI.getCalledFunction() && isCilk(*CI.getCalledFunction());
81 }
82
83 static bool isSync(const CallInst& CI) { 
84   return CI.getCalledFunction() &&
85          CI.getCalledFunction()->getName() == DummySyncFuncName;
86 }
87
88
89 //---------------------------------------------------------------------------- 
90 // class Cilkifier
91 //
92 // Code generation pass that transforms code to identify where Cilk keywords
93 // should be inserted.  This relies on `llvm-dis -c' to print out the keywords.
94 //---------------------------------------------------------------------------- 
95
96
97 class Cilkifier: public InstVisitor<Cilkifier>
98 {
99   Function* DummySyncFunc;
100
101   // Data used when transforming each function.
102   hash_set<const Instruction*>  stmtsVisited;    // Flags for recursive DFS
103   hash_map<const CallInst*, hash_set<CallInst*> > spawnToSyncsMap;
104
105   // Input data for the transformation.
106   const hash_set<Function*>*    cilkFunctions;   // Set of parallel functions
107   PgmDependenceGraph*           depGraph;
108
109   void          DFSVisitInstr   (Instruction* I,
110                                  Instruction* root,
111                                  hash_set<const Instruction*>& depsOfRoot);
112
113 public:
114   /*ctor*/      Cilkifier       (Module& M);
115
116   // Transform a single function including its name, its call sites, and syncs
117   // 
118   void          TransformFunc   (Function* F,
119                                  const hash_set<Function*>& cilkFunctions,
120                                  PgmDependenceGraph&  _depGraph);
121
122   // The visitor function that does most of the hard work, via DFSVisitInstr
123   // 
124   void visitCallInst(CallInst& CI);
125 };
126
127
128 Cilkifier::Cilkifier(Module& M)
129 {
130   // create the dummy Sync function and add it to the Module
131   DummySyncFunc = M.getOrInsertFunction(DummySyncFuncName, Type::VoidTy, 0);
132 }
133
134 void Cilkifier::TransformFunc(Function* F,
135                               const hash_set<Function*>& _cilkFunctions,
136                               PgmDependenceGraph& _depGraph)
137 {
138   // Memoize the information for this function
139   cilkFunctions = &_cilkFunctions;
140   depGraph = &_depGraph;
141
142   // Add the marker suffix to the Function name
143   // This should automatically mark all calls to the function also!
144   F->setName(F->getName() + CilkSuffix);
145
146   // Insert sync operations for each separate spawn
147   visit(*F);
148
149   // Now traverse the CFG in rPostorder and eliminate redundant syncs, i.e.,
150   // two consecutive sync's on a straight-line path with no intervening spawn.
151   
152 }
153
154
155 void Cilkifier::DFSVisitInstr(Instruction* I,
156                               Instruction* root,
157                               hash_set<const Instruction*>& depsOfRoot)
158 {
159   assert(stmtsVisited.find(I) == stmtsVisited.end());
160   stmtsVisited.insert(I);
161
162   // If there is a dependence from root to I, insert Sync and return
163   if (depsOfRoot.find(I) != depsOfRoot.end())
164     { // Insert a sync before I and stop searching along this path.
165       // If I is a Phi instruction, the dependence can only be an SSA dep.
166       // and we need to insert the sync in the predecessor on the appropriate
167       // incoming edge!
168       CallInst* syncI = 0;
169       if (PHINode* phiI = dyn_cast<PHINode>(I))
170         { // check all operands of the Phi and insert before each one
171           for (unsigned i = 0, N = phiI->getNumIncomingValues(); i < N; ++i)
172             if (phiI->getIncomingValue(i) == root)
173               syncI = new CallInst(DummySyncFunc, std::vector<Value*>(), "",
174                                    phiI->getIncomingBlock(i)->getTerminator());
175         }
176       else
177         syncI = new CallInst(DummySyncFunc, std::vector<Value*>(), "", I);
178
179       // Remember the sync for each spawn to eliminate redundant ones later
180       spawnToSyncsMap[cast<CallInst>(root)].insert(syncI);
181
182       return;
183     }
184
185   // else visit unvisited successors
186   if (BranchInst* brI = dyn_cast<BranchInst>(I))
187     { // visit first instruction in each successor BB
188       for (unsigned i = 0, N = brI->getNumSuccessors(); i < N; ++i)
189         if (stmtsVisited.find(&brI->getSuccessor(i)->front())
190             == stmtsVisited.end())
191           DFSVisitInstr(&brI->getSuccessor(i)->front(), root, depsOfRoot);
192     }
193   else
194     if (Instruction* nextI = I->getNext())
195       if (stmtsVisited.find(nextI) == stmtsVisited.end())
196         DFSVisitInstr(nextI, root, depsOfRoot);
197 }
198
199
200 void Cilkifier::visitCallInst(CallInst& CI)
201 {
202   assert(CI.getCalledFunction() != 0 && "Only direct calls can be spawned.");
203   if (cilkFunctions->find(CI.getCalledFunction()) == cilkFunctions->end())
204     return;                             // not a spawn
205
206   // Find all the outgoing memory dependences.
207   hash_set<const Instruction*> depsOfRoot;
208   for (PgmDependenceGraph::iterator DI =
209          depGraph->outDepBegin(CI, MemoryDeps); ! DI.fini(); ++DI)
210     depsOfRoot.insert(&DI->getSink()->getInstr());
211
212   // Now find all outgoing SSA dependences to the eventual non-Phi users of
213   // the call value (i.e., direct users that are not phis, and for any
214   // user that is a Phi, direct non-Phi users of that Phi, and recursively).
215   std::vector<const PHINode*> phiUsers;
216   hash_set<const PHINode*> phisSeen;    // ensures we don't visit a phi twice
217   for (Value::use_iterator UI=CI.use_begin(), UE=CI.use_end(); UI != UE; ++UI)
218     if (const PHINode* phiUser = dyn_cast<PHINode>(*UI))
219       {
220         if (phisSeen.find(phiUser) == phisSeen.end())
221           {
222             phiUsers.push_back(phiUser);
223             phisSeen.insert(phiUser);
224           }
225       }
226     else
227       depsOfRoot.insert(cast<Instruction>(*UI));
228
229   // Now we've found the non-Phi users and immediate phi users.
230   // Recursively walk the phi users and add their non-phi users.
231   for (const PHINode* phiUser; !phiUsers.empty(); phiUsers.pop_back())
232     {
233       phiUser = phiUsers.back();
234       for (Value::use_const_iterator UI=phiUser->use_begin(),
235              UE=phiUser->use_end(); UI != UE; ++UI)
236         if (const PHINode* pn = dyn_cast<PHINode>(*UI))
237           {
238             if (phisSeen.find(pn) == phisSeen.end())
239               {
240                 phiUsers.push_back(pn);
241                 phisSeen.insert(pn);
242               }
243           }
244         else
245           depsOfRoot.insert(cast<Instruction>(*UI));
246     }
247
248   // Walk paths of the CFG starting at the call instruction and insert
249   // one sync before the first dependence on each path, if any.
250   if (! depsOfRoot.empty())
251     {
252       stmtsVisited.clear();             // start a new DFS for this CallInst
253       assert(CI.getNext() && "Call instruction cannot be a terminator!");
254       DFSVisitInstr(CI.getNext(), &CI, depsOfRoot);
255     }
256
257   // Now, eliminate all users of the SSA value of the CallInst, i.e., 
258   // if the call instruction returns a value, delete the return value
259   // register and replace it by a stack slot.
260   if (CI.getType() != Type::VoidTy)
261     DemoteRegToStack(CI);
262 }
263
264
265 //---------------------------------------------------------------------------- 
266 // class FindParallelCalls
267 //
268 // Find all CallInst instructions that have at least one other CallInst
269 // that is independent.  These are the instructions that can produce
270 // useful parallelism.
271 //---------------------------------------------------------------------------- 
272
273 class FindParallelCalls : public InstVisitor<FindParallelCalls> {
274   typedef hash_set<CallInst*>           DependentsSet;
275   typedef DependentsSet::iterator       Dependents_iterator;
276   typedef DependentsSet::const_iterator Dependents_const_iterator;
277
278   PgmDependenceGraph& depGraph;         // dependence graph for the function
279   hash_set<Instruction*> stmtsVisited;  // flags for DFS walk of depGraph
280   hash_map<CallInst*, bool > completed; // flags marking if a CI is done
281   hash_map<CallInst*, DependentsSet> dependents; // dependent CIs for each CI
282
283   void VisitOutEdges(Instruction*   I,
284                      CallInst*      root,
285                      DependentsSet& depsOfRoot);
286
287   FindParallelCalls(const FindParallelCalls &); // DO NOT IMPLEMENT
288   void operator=(const FindParallelCalls&);     // DO NOT IMPLEMENT
289 public:
290   std::vector<CallInst*> parallelCalls;
291
292 public:
293   /*ctor*/      FindParallelCalls       (Function& F, PgmDependenceGraph& DG);
294   void          visitCallInst           (CallInst& CI);
295 };
296
297
298 FindParallelCalls::FindParallelCalls(Function& F,
299                                      PgmDependenceGraph& DG)
300   : depGraph(DG)
301 {
302   // Find all CallInsts reachable from each CallInst using a recursive DFS
303   visit(F);
304
305   // Now we've found all CallInsts reachable from each CallInst.
306   // Find those CallInsts that are parallel with at least one other CallInst
307   // by counting total inEdges and outEdges.
308   // 
309   unsigned long totalNumCalls = completed.size();
310
311   if (totalNumCalls == 1)
312     { // Check first for the special case of a single call instruction not
313       // in any loop.  It is not parallel, even if it has no dependences
314       // (this is why it is a special case).
315       //
316       // FIXME:
317       // THIS CASE IS NOT HANDLED RIGHT NOW, I.E., THERE IS NO
318       // PARALLELISM FOR CALLS IN DIFFERENT ITERATIONS OF A LOOP.
319       // 
320       return;
321     }
322
323   hash_map<CallInst*, unsigned long> numDeps;
324   for (hash_map<CallInst*, DependentsSet>::iterator II = dependents.begin(),
325          IE = dependents.end(); II != IE; ++II)
326     {
327       CallInst* fromCI = II->first;
328       numDeps[fromCI] += II->second.size();
329       for (Dependents_iterator DI = II->second.begin(), DE = II->second.end();
330            DI != DE; ++DI)
331         numDeps[*DI]++;                 // *DI can be reached from II->first
332     }
333
334   for (hash_map<CallInst*, DependentsSet>::iterator
335          II = dependents.begin(), IE = dependents.end(); II != IE; ++II)
336
337     // FIXME: Remove "- 1" when considering parallelism in loops
338     if (numDeps[II->first] < totalNumCalls - 1)
339       parallelCalls.push_back(II->first);
340 }
341
342
343 void FindParallelCalls::VisitOutEdges(Instruction* I,
344                                       CallInst* root,
345                                       DependentsSet& depsOfRoot)
346 {
347   assert(stmtsVisited.find(I) == stmtsVisited.end() && "Stmt visited twice?");
348   stmtsVisited.insert(I);
349
350   if (CallInst* CI = dyn_cast<CallInst>(I))
351
352     // FIXME: Ignoring parallelism in a loop.  Here we're actually *ignoring*
353     // a self-dependence in order to get the count comparison right above.
354     // When we include loop parallelism, self-dependences should be included.
355     // 
356     if (CI != root)
357
358       { // CallInst root has a path to CallInst I and any calls reachable from I
359         depsOfRoot.insert(CI);
360         if (completed[CI])
361           { // We have already visited I so we know all nodes it can reach!
362             DependentsSet& depsOfI = dependents[CI];
363             depsOfRoot.insert(depsOfI.begin(), depsOfI.end());
364             return;
365           }
366       }
367
368   // If we reach here, we need to visit all children of I
369   for (PgmDependenceGraph::iterator DI = depGraph.outDepBegin(*I);
370        ! DI.fini(); ++DI)
371     {
372       Instruction* sink = &DI->getSink()->getInstr();
373       if (stmtsVisited.find(sink) == stmtsVisited.end())
374         VisitOutEdges(sink, root, depsOfRoot);
375     }
376 }
377
378
379 void FindParallelCalls::visitCallInst(CallInst& CI)
380 {
381   if (completed[&CI])
382     return;
383   stmtsVisited.clear();                      // clear flags to do a fresh DFS
384
385   // Visit all children of CI using a recursive walk through dep graph
386   DependentsSet& depsOfRoot = dependents[&CI];
387   for (PgmDependenceGraph::iterator DI = depGraph.outDepBegin(CI);
388        ! DI.fini(); ++DI)
389     {
390       Instruction* sink = &DI->getSink()->getInstr();
391       if (stmtsVisited.find(sink) == stmtsVisited.end())
392         VisitOutEdges(sink, &CI, depsOfRoot);
393     }
394
395   completed[&CI] = true;
396 }
397
398
399 //---------------------------------------------------------------------------- 
400 // class Parallelize
401 //
402 // (1) Find candidate parallel functions: any function F s.t.
403 //       there is a call C1 to the function F that is followed or preceded
404 //       by at least one other call C2 that is independent of this one
405 //       (i.e., there is no dependence path from C1 to C2 or C2 to C1)
406 // (2) Label such a function F as a cilk function.
407 // (3) Convert every call to F to a spawn
408 // (4) For every function X, insert sync statements so that
409 //        every spawn is postdominated by a sync before any statements
410 //        with a data dependence to/from the call site for the spawn
411 // 
412 //---------------------------------------------------------------------------- 
413
414 namespace {
415   class Parallelize: public Pass
416   {
417   public:
418     /// Driver functions to transform a program
419     ///
420     bool run(Module& M);
421
422     /// getAnalysisUsage - Modifies extensively so preserve nothing.
423     /// Uses the DependenceGraph and the Top-down DS Graph (only to find
424     /// all functions called via an indirect call).
425     ///
426     void getAnalysisUsage(AnalysisUsage &AU) const {
427       AU.addRequired<TDDataStructures>();
428       AU.addRequired<MemoryDepAnalysis>();  // force this not to be released
429       AU.addRequired<PgmDependenceGraph>(); // because it is needed by this
430     }
431   };
432
433   RegisterOpt<Parallelize> X("parallel", "Parallelize program using Cilk");
434 }
435
436
437 static Function* FindMain(Module& M)
438 {
439   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
440     if (FI->getName() == std::string("main"))
441       return FI;
442   return NULL;
443 }
444
445
446 bool Parallelize::run(Module& M)
447 {
448   hash_set<Function*> parallelFunctions;
449   hash_set<Function*> safeParallelFunctions;
450   hash_set<const GlobalValue*> indirectlyCalled;
451
452   // If there is no main (i.e., for an incomplete program), we can do nothing.
453   // If there is a main, mark main as a parallel function.
454   // 
455   Function* mainFunc = FindMain(M);
456   if (!mainFunc)
457     return false;
458
459   // (1) Find candidate parallel functions and mark them as Cilk functions
460   // 
461   for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
462     if (! FI->isExternal())
463       {
464         Function* F = FI;
465         DSGraph& tdg = getAnalysis<TDDataStructures>().getDSGraph(*F);
466
467         // All the hard analysis work gets done here!
468         // 
469         FindParallelCalls finder(*F,
470                                 getAnalysis<PgmDependenceGraph>().getGraph(*F));
471                         /* getAnalysis<MemoryDepAnalysis>().getGraph(*F)); */
472
473         // Now we know which call instructions are useful to parallelize.
474         // Remember those callee functions.
475         // 
476         for (std::vector<CallInst*>::iterator
477                CII = finder.parallelCalls.begin(),
478                CIE = finder.parallelCalls.end(); CII != CIE; ++CII)
479           {
480             // Check if this is a direct call...
481             if ((*CII)->getCalledFunction() != NULL)
482               { // direct call: if this is to a non-external function,
483                 // mark it as a parallelizable function
484                 if (! (*CII)->getCalledFunction()->isExternal())
485                   parallelFunctions.insert((*CII)->getCalledFunction());
486               }
487             else
488               { // Indirect call: mark all potential callees as bad
489                 std::vector<GlobalValue*> callees =
490                   tdg.getNodeForValue((*CII)->getCalledValue())
491                   .getNode()->getGlobals();
492                 indirectlyCalled.insert(callees.begin(), callees.end());
493               }
494           }
495       }
496
497   // Remove all indirectly called functions from the list of Cilk functions.
498   // 
499   for (hash_set<Function*>::iterator PFI = parallelFunctions.begin(),
500          PFE = parallelFunctions.end(); PFI != PFE; ++PFI)
501     if (indirectlyCalled.count(*PFI) == 0)
502       safeParallelFunctions.insert(*PFI);
503
504 #undef CAN_USE_BIND1ST_ON_REFERENCE_TYPE_ARGS
505 #ifdef CAN_USE_BIND1ST_ON_REFERENCE_TYPE_ARGS
506   // Use this indecipherable STLese because erase invalidates iterators.
507   // Otherwise we have to copy sets as above.
508   hash_set<Function*>::iterator extrasBegin = 
509     std::remove_if(parallelFunctions.begin(), parallelFunctions.end(),
510                    compose1(std::bind2nd(std::greater<int>(), 0),
511                             bind_obj(&indirectlyCalled,
512                                      &hash_set<const GlobalValue*>::count)));
513   parallelFunctions.erase(extrasBegin, parallelFunctions.end());
514 #endif
515
516   // If there are no parallel functions, we can just give up.
517   if (safeParallelFunctions.empty())
518     return false;
519
520   // Add main as a parallel function since Cilk requires this.
521   safeParallelFunctions.insert(mainFunc);
522
523   // (2,3) Transform each Cilk function and all its calls simply by
524   //     adding a unique suffix to the function name.
525   //     This should identify both functions and calls to such functions
526   //     to the code generator.
527   // (4) Also, insert calls to sync at appropriate points.
528   // 
529   Cilkifier cilkifier(M);
530   for (hash_set<Function*>::iterator CFI = safeParallelFunctions.begin(),
531          CFE = safeParallelFunctions.end(); CFI != CFE; ++CFI)
532     {
533       cilkifier.TransformFunc(*CFI, safeParallelFunctions,
534                              getAnalysis<PgmDependenceGraph>().getGraph(**CFI));
535       /* getAnalysis<MemoryDepAnalysis>().getGraph(**CFI)); */
536     }
537
538   return true;
539 }
540
541 } // End llvm namespace