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