1 //===- Parallelize.cpp - Auto parallelization using DS Graphs -------------===//
3 // This file implements a pass that automatically parallelizes a program,
4 // using the Cilk multi-threaded runtime system to execute parallel code.
6 // The pass uses the Program Dependence Graph (class PDGIterator) to
7 // identify parallelizable function calls, i.e., calls whose instances
8 // can be executed in parallel with instances of other function calls.
9 // (In the future, this should also execute different instances of the same
10 // function call in parallel, but that requires parallelizing across
13 // The output of the pass is LLVM code with:
14 // (1) all parallelizable functions renamed to flag them as parallelizable;
15 // (2) calls to a sync() function introduced at synchronization points.
16 // The CWriter recognizes these functions and inserts the appropriate Cilk
17 // keywords when writing out C code. This C code must be compiled with cilk2c.
19 // Current algorithmic limitations:
20 // -- no array dependence analysis
21 // -- no parallelization for function calls in different loop iterations
22 // (except in unlikely trivial cases)
24 // Limitations of using Cilk:
25 // -- No parallelism within a function body, e.g., in a loop;
26 // -- Simplistic synchronization model requiring all parallel threads
27 // created within a function to block at a sync().
28 // -- Excessive overhead at "spawned" function calls, which has no benefit
29 // once all threads are busy (especially common when the degree of
30 // parallelism is low).
32 //===----------------------------------------------------------------------===//
34 #include "llvm/Transforms/Utils/DemoteRegToStack.h"
35 #include "llvm/Analysis/PgmDependenceGraph.h"
36 #include "llvm/Analysis/Dominators.h"
37 #include "llvm/Analysis/DataStructure.h"
38 #include "llvm/Analysis/DSGraph.h"
39 #include "llvm/Module.h"
40 #include "llvm/Instructions.h"
41 #include "llvm/iTerminators.h"
42 #include "llvm/DerivedTypes.h"
43 #include "llvm/Support/InstVisitor.h"
44 #include "llvm/Support/Cilkifier.h"
45 #include "Support/Statistic.h"
46 #include "Support/STLExtras.h"
47 #include "Support/hash_set"
48 #include "Support/hash_map"
55 void AddToDomSet(vector<BasicBlock*>& domSet, BasicBlock* bb,
56 const DominatorTree& domTree)
58 DominatorTreeBase::Node* bbNode = domTree.getNode(bb);
59 const std::vector<Node*>& domKids = bbNode.getChildren();
60 domSet.insert(domSet.end(), domKids.begin(), domKids.end());
61 for (unsigned i = 0; i < domKids.size(); ++i)
62 AddToDomSet(domSet, domKids[i]->getNode(), domTree);
65 bool CheckDominance(Function& func,
66 const CallInst& callInst1,
67 const CallInst& callInst2)
69 if (callInst1 == callInst2) // makes sense if this is in a loop but
70 return false; // we're not handling loops yet
72 // Check first if one call dominates the other
73 DominatorSet& domSet = getAnalysis<DominatorSet>(func);
74 if (domSet.dominates(callInst2, callInst1))
75 { // swap callInst1 and callInst2
76 const CallInst& tmp = callInst2; callInst2 = callInst1; callInst1 = tmp;
78 else if (! domSet.dominates(callInst1, callInst2))
79 return false; // neither dominates the other:
82 if (! AreIndependent(func, callInst1, callInst2))
89 //----------------------------------------------------------------------------
92 // Code generation pass that transforms code to identify where Cilk keywords
93 // should be inserted. This relies on dis -c to print out the keywords.
94 //----------------------------------------------------------------------------
97 class Cilkifier: public InstVisitor<Cilkifier>
99 Function* DummySyncFunc;
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;
105 // Input data for the transformation.
106 const hash_set<Function*>* cilkFunctions; // Set of parallel functions
107 PgmDependenceGraph* depGraph;
109 void DFSVisitInstr (Instruction* I,
111 hash_set<const Instruction*>& depsOfRoot);
114 /*ctor*/ Cilkifier (Module& M);
116 // Transform a single function including its name, its call sites, and syncs
118 void TransformFunc (Function* F,
119 const hash_set<Function*>& cilkFunctions,
120 PgmDependenceGraph& _depGraph);
122 // The visitor function that does most of the hard work, via DFSVisitInstr
124 void visitCallInst(CallInst& CI);
128 Cilkifier::Cilkifier(Module& M)
130 // create the dummy Sync function and add it to the Module
131 DummySyncFunc = new Function(FunctionType::get( Type::VoidTy,
132 std::vector<const Type*>(),
134 GlobalValue::ExternalLinkage, DummySyncFuncName,
138 void Cilkifier::TransformFunc(Function* F,
139 const hash_set<Function*>& _cilkFunctions,
140 PgmDependenceGraph& _depGraph)
142 // Memoize the information for this function
143 cilkFunctions = &_cilkFunctions;
144 depGraph = &_depGraph;
146 // Add the marker suffix to the Function name
147 // This should automatically mark all calls to the function also!
148 F->setName(F->getName() + CilkSuffix);
150 // Insert sync operations for each separate spawn
153 // Now traverse the CFG in rPostorder and eliminate redundant syncs, i.e.,
154 // two consecutive sync's on a straight-line path with no intervening spawn.
159 void Cilkifier::DFSVisitInstr(Instruction* I,
161 hash_set<const Instruction*>& depsOfRoot)
163 assert(stmtsVisited.find(I) == stmtsVisited.end());
164 stmtsVisited.insert(I);
166 // If there is a dependence from root to I, insert Sync and return
167 if (depsOfRoot.find(I) != depsOfRoot.end())
168 { // Insert a sync before I and stop searching along this path.
169 // If I is a Phi instruction, the dependence can only be an SSA dep.
170 // and we need to insert the sync in the predecessor on the appropriate
173 if (PHINode* phiI = dyn_cast<PHINode>(I))
174 { // check all operands of the Phi and insert before each one
175 for (unsigned i = 0, N = phiI->getNumIncomingValues(); i < N; ++i)
176 if (phiI->getIncomingValue(i) == root)
177 syncI = new CallInst(DummySyncFunc, std::vector<Value*>(), "",
178 phiI->getIncomingBlock(i)->getTerminator());
181 syncI = new CallInst(DummySyncFunc, std::vector<Value*>(), "", I);
183 // Remember the sync for each spawn to eliminate rendundant ones later
184 spawnToSyncsMap[cast<CallInst>(root)].insert(syncI);
189 // else visit unvisited successors
190 if (BranchInst* brI = dyn_cast<BranchInst>(I))
191 { // visit first instruction in each successor BB
192 for (unsigned i = 0, N = brI->getNumSuccessors(); i < N; ++i)
193 if (stmtsVisited.find(&brI->getSuccessor(i)->front())
194 == stmtsVisited.end())
195 DFSVisitInstr(&brI->getSuccessor(i)->front(), root, depsOfRoot);
198 if (Instruction* nextI = I->getNext())
199 if (stmtsVisited.find(nextI) == stmtsVisited.end())
200 DFSVisitInstr(nextI, root, depsOfRoot);
204 void Cilkifier::visitCallInst(CallInst& CI)
206 assert(CI.getCalledFunction() != 0 && "Only direct calls can be spawned.");
207 if (cilkFunctions->find(CI.getCalledFunction()) == cilkFunctions->end())
208 return; // not a spawn
210 // Find all the outgoing memory dependences.
211 hash_set<const Instruction*> depsOfRoot;
212 for (PgmDependenceGraph::iterator DI =
213 depGraph->outDepBegin(CI, MemoryDeps); ! DI.fini(); ++DI)
214 depsOfRoot.insert(&DI->getSink()->getInstr());
216 // Now find all outgoing SSA dependences to the eventual non-Phi users of
217 // the call value (i.e., direct users that are not phis, and for any
218 // user that is a Phi, direct non-Phi users of that Phi, and recursively).
219 std::vector<const PHINode*> phiUsers;
220 hash_set<const PHINode*> phisSeen; // ensures we don't visit a phi twice
221 for (Value::use_iterator UI=CI.use_begin(), UE=CI.use_end(); UI != UE; ++UI)
222 if (const PHINode* phiUser = dyn_cast<PHINode>(*UI))
224 if (phisSeen.find(phiUser) == phisSeen.end())
226 phiUsers.push_back(phiUser);
227 phisSeen.insert(phiUser);
231 depsOfRoot.insert(cast<Instruction>(*UI));
233 // Now we've found the non-Phi users and immediate phi users.
234 // Recursively walk the phi users and add their non-phi users.
235 for (const PHINode* phiUser; !phiUsers.empty(); phiUsers.pop_back())
237 phiUser = phiUsers.back();
238 for (Value::use_const_iterator UI=phiUser->use_begin(),
239 UE=phiUser->use_end(); UI != UE; ++UI)
240 if (const PHINode* pn = dyn_cast<PHINode>(*UI))
242 if (phisSeen.find(pn) == phisSeen.end())
244 phiUsers.push_back(pn);
249 depsOfRoot.insert(cast<Instruction>(*UI));
252 // Walk paths of the CFG starting at the call instruction and insert
253 // one sync before the first dependence on each path, if any.
254 if (! depsOfRoot.empty())
256 stmtsVisited.clear(); // start a new DFS for this CallInst
257 assert(CI.getNext() && "Call instruction cannot be a terminator!");
258 DFSVisitInstr(CI.getNext(), &CI, depsOfRoot);
261 // Now, eliminate all users of the SSA value of the CallInst, i.e.,
262 // if the call instruction returns a value, delete the return value
263 // register and replace it by a stack slot.
264 if (CI.getType() != Type::VoidTy)
265 DemoteRegToStack(CI);
269 //----------------------------------------------------------------------------
270 // class FindParallelCalls
272 // Find all CallInst instructions that have at least one other CallInst
273 // that is independent. These are the instructions that can produce
274 // useful parallelism.
275 //----------------------------------------------------------------------------
277 class FindParallelCalls : public InstVisitor<FindParallelCalls> {
278 typedef hash_set<CallInst*> DependentsSet;
279 typedef DependentsSet::iterator Dependents_iterator;
280 typedef DependentsSet::const_iterator Dependents_const_iterator;
282 PgmDependenceGraph& depGraph; // dependence graph for the function
283 hash_set<Instruction*> stmtsVisited; // flags for DFS walk of depGraph
284 hash_map<CallInst*, bool > completed; // flags marking if a CI is done
285 hash_map<CallInst*, DependentsSet> dependents; // dependent CIs for each CI
287 void VisitOutEdges(Instruction* I,
289 DependentsSet& depsOfRoot);
291 FindParallelCalls(const FindParallelCalls &); // DO NOT IMPLEMENT
292 void operator=(const FindParallelCalls&); // DO NOT IMPLEMENT
294 std::vector<CallInst*> parallelCalls;
297 /*ctor*/ FindParallelCalls (Function& F, PgmDependenceGraph& DG);
298 void visitCallInst (CallInst& CI);
302 FindParallelCalls::FindParallelCalls(Function& F,
303 PgmDependenceGraph& DG)
306 // Find all CallInsts reachable from each CallInst using a recursive DFS
309 // Now we've found all CallInsts reachable from each CallInst.
310 // Find those CallInsts that are parallel with at least one other CallInst
311 // by counting total inEdges and outEdges.
313 unsigned long totalNumCalls = completed.size();
315 if (totalNumCalls == 1)
316 { // Check first for the special case of a single call instruction not
317 // in any loop. It is not parallel, even if it has no dependences
318 // (this is why it is a special case).
321 // THIS CASE IS NOT HANDLED RIGHT NOW, I.E., THERE IS NO
322 // PARALLELISM FOR CALLS IN DIFFERENT ITERATIONS OF A LOOP.
327 hash_map<CallInst*, unsigned long> numDeps;
328 for (hash_map<CallInst*, DependentsSet>::iterator II = dependents.begin(),
329 IE = dependents.end(); II != IE; ++II)
331 CallInst* fromCI = II->first;
332 numDeps[fromCI] += II->second.size();
333 for (Dependents_iterator DI = II->second.begin(), DE = II->second.end();
335 numDeps[*DI]++; // *DI can be reached from II->first
338 for (hash_map<CallInst*, DependentsSet>::iterator
339 II = dependents.begin(), IE = dependents.end(); II != IE; ++II)
341 // FIXME: Remove "- 1" when considering parallelism in loops
342 if (numDeps[II->first] < totalNumCalls - 1)
343 parallelCalls.push_back(II->first);
347 void FindParallelCalls::VisitOutEdges(Instruction* I,
349 DependentsSet& depsOfRoot)
351 assert(stmtsVisited.find(I) == stmtsVisited.end() && "Stmt visited twice?");
352 stmtsVisited.insert(I);
354 if (CallInst* CI = dyn_cast<CallInst>(I))
356 // FIXME: Ignoring parallelism in a loop. Here we're actually *ignoring*
357 // a self-dependence in order to get the count comparison right above.
358 // When we include loop parallelism, self-dependences should be included.
362 { // CallInst root has a path to CallInst I and any calls reachable from I
363 depsOfRoot.insert(CI);
365 { // We have already visited I so we know all nodes it can reach!
366 DependentsSet& depsOfI = dependents[CI];
367 depsOfRoot.insert(depsOfI.begin(), depsOfI.end());
372 // If we reach here, we need to visit all children of I
373 for (PgmDependenceGraph::iterator DI = depGraph.outDepBegin(*I);
376 Instruction* sink = &DI->getSink()->getInstr();
377 if (stmtsVisited.find(sink) == stmtsVisited.end())
378 VisitOutEdges(sink, root, depsOfRoot);
383 void FindParallelCalls::visitCallInst(CallInst& CI)
387 stmtsVisited.clear(); // clear flags to do a fresh DFS
389 // Visit all children of CI using a recursive walk through dep graph
390 DependentsSet& depsOfRoot = dependents[&CI];
391 for (PgmDependenceGraph::iterator DI = depGraph.outDepBegin(CI);
394 Instruction* sink = &DI->getSink()->getInstr();
395 if (stmtsVisited.find(sink) == stmtsVisited.end())
396 VisitOutEdges(sink, &CI, depsOfRoot);
399 completed[&CI] = true;
403 //----------------------------------------------------------------------------
406 // (1) Find candidate parallel functions: any function F s.t.
407 // there is a call C1 to the function F that is followed or preceded
408 // by at least one other call C2 that is independent of this one
409 // (i.e., there is no dependence path from C1 to C2 or C2 to C1)
410 // (2) Label such a function F as a cilk function.
411 // (3) Convert every call to F to a spawn
412 // (4) For every function X, insert sync statements so that
413 // every spawn is postdominated by a sync before any statements
414 // with a data dependence to/from the call site for the spawn
416 //----------------------------------------------------------------------------
419 class Parallelize: public Pass
422 /// Driver functions to transform a program
426 /// getAnalysisUsage - Modifies extensively so preserve nothing.
427 /// Uses the DependenceGraph and the Top-down DS Graph (only to find
428 /// all functions called via an indirect call).
430 void getAnalysisUsage(AnalysisUsage &AU) const {
431 AU.addRequired<TDDataStructures>();
432 AU.addRequired<MemoryDepAnalysis>(); // force this not to be released
433 AU.addRequired<PgmDependenceGraph>(); // because it is needed by this
437 RegisterOpt<Parallelize> X("parallel", "Parallelize program using Cilk");
441 static Function* FindMain(Module& M)
443 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
444 if (FI->getName() == std::string("main"))
450 bool Parallelize::run(Module& M)
452 hash_set<Function*> parallelFunctions;
453 hash_set<Function*> safeParallelFunctions;
454 hash_set<const GlobalValue*> indirectlyCalled;
456 // If there is no main (i.e., for an incomplete program), we can do nothing.
457 // If there is a main, mark main as a parallel function.
459 Function* mainFunc = FindMain(M);
463 // (1) Find candidate parallel functions and mark them as Cilk functions
465 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
466 if (! FI->isExternal())
469 DSGraph& tdg = getAnalysis<TDDataStructures>().getDSGraph(*F);
471 // All the hard analysis work gets done here!
473 FindParallelCalls finder(*F,
474 getAnalysis<PgmDependenceGraph>().getGraph(*F));
475 /* getAnalysis<MemoryDepAnalysis>().getGraph(*F)); */
477 // Now we know which call instructions are useful to parallelize.
478 // Remember those callee functions.
480 for (std::vector<CallInst*>::iterator
481 CII = finder.parallelCalls.begin(),
482 CIE = finder.parallelCalls.end(); CII != CIE; ++CII)
484 // Check if this is a direct call...
485 if ((*CII)->getCalledFunction() != NULL)
486 { // direct call: if this is to a non-external function,
487 // mark it as a parallelizable function
488 if (! (*CII)->getCalledFunction()->isExternal())
489 parallelFunctions.insert((*CII)->getCalledFunction());
492 { // Indirect call: mark all potential callees as bad
493 std::vector<GlobalValue*> callees =
494 tdg.getNodeForValue((*CII)->getCalledValue())
495 .getNode()->getGlobals();
496 indirectlyCalled.insert(callees.begin(), callees.end());
501 // Remove all indirectly called functions from the list of Cilk functions.
503 for (hash_set<Function*>::iterator PFI = parallelFunctions.begin(),
504 PFE = parallelFunctions.end(); PFI != PFE; ++PFI)
505 if (indirectlyCalled.count(*PFI) == 0)
506 safeParallelFunctions.insert(*PFI);
508 #undef CAN_USE_BIND1ST_ON_REFERENCE_TYPE_ARGS
509 #ifdef CAN_USE_BIND1ST_ON_REFERENCE_TYPE_ARGS
510 // Use this undecipherable STLese because erase invalidates iterators.
511 // Otherwise we have to copy sets as above.
512 hash_set<Function*>::iterator extrasBegin =
513 std::remove_if(parallelFunctions.begin(), parallelFunctions.end(),
514 compose1(std::bind2nd(std::greater<int>(), 0),
515 bind_obj(&indirectlyCalled,
516 &hash_set<const GlobalValue*>::count)));
517 parallelFunctions.erase(extrasBegin, parallelFunctions.end());
520 // If there are no parallel functions, we can just give up.
521 if (safeParallelFunctions.empty())
524 // Add main as a parallel function since Cilk requires this.
525 safeParallelFunctions.insert(mainFunc);
527 // (2,3) Transform each Cilk function and all its calls simply by
528 // adding a unique suffix to the function name.
529 // This should identify both functions and calls to such functions
530 // to the code generator.
531 // (4) Also, insert calls to sync at appropriate points.
533 Cilkifier cilkifier(M);
534 for (hash_set<Function*>::iterator CFI = safeParallelFunctions.begin(),
535 CFE = safeParallelFunctions.end(); CFI != CFE; ++CFI)
537 cilkifier.TransformFunc(*CFI, safeParallelFunctions,
538 getAnalysis<PgmDependenceGraph>().getGraph(**CFI));
539 /* getAnalysis<MemoryDepAnalysis>().getGraph(**CFI)); */