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