blob: 4c6f264b3bb88f1f0d4b9ce43a895792e0bc681c [file] [log] [blame]
Andrew Lenharth93e59f62005-11-28 00:58:09 +00001//===- RSProfiling.cpp - Various profiling using random sampling ----------===//
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// These passes implement a random sampling based profiling. Different methods
11// of choosing when to sample are supported, as well as different types of
12// profiling. This is done as two passes. The first is a sequence of profiling
Andrew Lenharth517caef2005-11-28 18:00:38 +000013// passes which insert profiling into the program, and remember what they
14// inserted.
15//
Andrew Lenharth93e59f62005-11-28 00:58:09 +000016// The second stage duplicates all instructions in a function, ignoring the
17// profiling code, then connects the two versions togeather at the entry and at
18// backedges. At each connection point a choice is made as to whether to jump
19// to the profiled code (take a sample) or execute the unprofiled code.
20//
21// It is highly recommeneded that after this pass one runs mem2reg and adce
22// (instcombine load-vn gdce dse also are good to run afterwards)
23//
24// This design is intended to make the profiling passes independent of the RS
25// framework, but any profiling pass that implements the RSProfiling interface
26// is compatible with the rs framework (and thus can be sampled)
27//
28// TODO: obviously the block and function profiling are almost identical to the
29// existing ones, so they can be unified (esp since these passes are valid
30// without the rs framework).
31// TODO: Fix choice code so that frequency is not hard coded
32//
33//===----------------------------------------------------------------------===//
34
35#include "llvm/Pass.h"
Andrew Lenharth93e59f62005-11-28 00:58:09 +000036#include "llvm/Module.h"
Andrew Lenharth93e59f62005-11-28 00:58:09 +000037#include "llvm/Instructions.h"
38#include "llvm/Constants.h"
39#include "llvm/DerivedTypes.h"
40#include "llvm/Transforms/Scalar.h"
41#include "llvm/Transforms/Utils/BasicBlockUtils.h"
42#include "llvm/ADT/Statistic.h"
43#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Transforms/Instrumentation.h"
Andrew Lenharth517caef2005-11-28 18:00:38 +000046//#include "ProfilingUtils.h"
Andrew Lenharth93e59f62005-11-28 00:58:09 +000047#include "RSProfiling.h"
Andrew Lenharth93e59f62005-11-28 00:58:09 +000048#include <set>
49#include <map>
50#include <queue>
51#include <list>
Andrew Lenharth93e59f62005-11-28 00:58:09 +000052using namespace llvm;
53
54namespace {
55 Statistic<> NumBackEdges("bedge", "Number of BackEdges");
56
57 enum RandomMeth {
58 GBV, GBVO, HOSTCC
59 };
60
61 cl::opt<RandomMeth> RandomMethod("profile-randomness",
62 cl::desc("How to randomly choose to profile:"),
63 cl::values(
64 clEnumValN(GBV, "global", "global counter"),
Andrew Lenharth517caef2005-11-28 18:00:38 +000065 clEnumValN(GBVO, "ra_global",
66 "register allocated global counter"),
Andrew Lenharth93e59f62005-11-28 00:58:09 +000067 clEnumValN(HOSTCC, "rdcc", "cycle counter"),
68 clEnumValEnd));
69
Andrew Lenharthd2511922005-11-28 18:10:59 +000070 /// NullProfilerRS - The basic profiler that does nothing. It is the default
71 /// profiler and thus terminates RSProfiler chains. It is useful for
72 /// measuring framework overhead
Andrew Lenharth93e59f62005-11-28 00:58:09 +000073 class NullProfilerRS : public RSProfilers {
74 public:
75 bool isProfiling(Value* v) {
76 return false;
77 }
78 bool runOnModule(Module &M) {
79 return false;
80 }
81 void getAnalysisUsage(AnalysisUsage &AU) const {
82 AU.setPreservesAll();
83 }
84 };
85
86 static RegisterAnalysisGroup<RSProfilers> A("Profiling passes");
Chris Lattnerc2d3d312006-08-27 22:42:52 +000087 static RegisterPass<NullProfilerRS> NP("insert-null-profiling-rs",
Andrew Lenharth517caef2005-11-28 18:00:38 +000088 "Measure profiling framework overhead");
Chris Lattner97c9f202006-08-28 00:42:29 +000089 static RegisterAnalysisGroup<RSProfilers, true> NPT(NP);
Andrew Lenharth93e59f62005-11-28 00:58:09 +000090
Andrew Lenharthd2511922005-11-28 18:10:59 +000091 /// Chooser - Something that chooses when to make a sample of the profiled code
Andrew Lenharth93e59f62005-11-28 00:58:09 +000092 class Chooser {
93 public:
Andrew Lenharthd2511922005-11-28 18:10:59 +000094 /// ProcessChoicePoint - is called for each basic block inserted to choose
95 /// between normal and sample code
Andrew Lenharth93e59f62005-11-28 00:58:09 +000096 virtual void ProcessChoicePoint(BasicBlock*) = 0;
Andrew Lenharthd2511922005-11-28 18:10:59 +000097 /// PrepFunction - is called once per function before other work is done.
98 /// This gives the opertunity to insert new allocas and such.
Andrew Lenharth93e59f62005-11-28 00:58:09 +000099 virtual void PrepFunction(Function*) = 0;
100 virtual ~Chooser() {}
101 };
102
103 //Things that implement sampling policies
Andrew Lenharthd2511922005-11-28 18:10:59 +0000104 //A global value that is read-mod-stored to choose when to sample.
105 //A sample is taken when the global counter hits 0
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000106 class GlobalRandomCounter : public Chooser {
107 GlobalVariable* Counter;
108 Value* ResetValue;
109 const Type* T;
110 public:
111 GlobalRandomCounter(Module& M, const Type* t, uint64_t resetval);
112 virtual ~GlobalRandomCounter();
113 virtual void PrepFunction(Function* F);
114 virtual void ProcessChoicePoint(BasicBlock* bb);
115 };
116
Andrew Lenharthd2511922005-11-28 18:10:59 +0000117 //Same is GRC, but allow register allocation of the global counter
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000118 class GlobalRandomCounterOpt : public Chooser {
119 GlobalVariable* Counter;
120 Value* ResetValue;
121 AllocaInst* AI;
122 const Type* T;
123 public:
124 GlobalRandomCounterOpt(Module& M, const Type* t, uint64_t resetval);
125 virtual ~GlobalRandomCounterOpt();
126 virtual void PrepFunction(Function* F);
127 virtual void ProcessChoicePoint(BasicBlock* bb);
128 };
129
Andrew Lenharthd2511922005-11-28 18:10:59 +0000130 //Use the cycle counter intrinsic as a source of pseudo randomness when
131 //deciding when to sample.
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000132 class CycleCounter : public Chooser {
133 uint64_t rm;
134 Function* F;
135 public:
136 CycleCounter(Module& m, uint64_t resetmask);
137 virtual ~CycleCounter();
138 virtual void PrepFunction(Function* F);
139 virtual void ProcessChoicePoint(BasicBlock* bb);
140 };
141
Andrew Lenharthd2511922005-11-28 18:10:59 +0000142 /// ProfilerRS - Insert the random sampling framework
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000143 struct ProfilerRS : public FunctionPass {
144 std::map<Value*, Value*> TransCache;
145 std::set<BasicBlock*> ChoicePoints;
146 Chooser* c;
147
Andrew Lenharthd2511922005-11-28 18:10:59 +0000148 //Translate and duplicate values for the new profile free version of stuff
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000149 Value* Translate(Value* v);
Andrew Lenharthd2511922005-11-28 18:10:59 +0000150 //Duplicate an entire function (with out profiling)
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000151 void Duplicate(Function& F, RSProfilers& LI);
Andrew Lenharthd2511922005-11-28 18:10:59 +0000152 //Called once for each backedge, handle the insertion of choice points and
153 //the interconection of the two versions of the code
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000154 void ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F);
155 bool runOnFunction(Function& F);
156 bool doInitialization(Module &M);
157 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
158 };
159
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000160 RegisterPass<ProfilerRS> X("insert-rs-profiling-framework",
161 "Insert random sampling instrumentation framework");
Chris Lattneraa2372562006-05-24 17:04:05 +0000162}
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000163
164//Local utilities
165static void ReplacePhiPred(BasicBlock* btarget,
166 BasicBlock* bold, BasicBlock* bnew);
167
168static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc);
169
170template<class T>
171static void recBackEdge(BasicBlock* bb, T& BackEdges,
172 std::map<BasicBlock*, int>& color,
173 std::map<BasicBlock*, int>& depth,
174 std::map<BasicBlock*, int>& finish,
175 int& time);
176
177//find the back edges and where they go to
178template<class T>
179static void getBackEdges(Function& F, T& BackEdges);
180
181
182///////////////////////////////////////
183// Methods of choosing when to profile
184///////////////////////////////////////
185
186GlobalRandomCounter::GlobalRandomCounter(Module& M, const Type* t,
187 uint64_t resetval) : T(t) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000188 ConstantInt* Init = ConstantInt::get(T, resetval);
189 ResetValue = Init;
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000190 Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000191 Init, "RandomSteeringCounter", &M);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000192}
193
194GlobalRandomCounter::~GlobalRandomCounter() {}
195
196void GlobalRandomCounter::PrepFunction(Function* F) {}
197
198void GlobalRandomCounter::ProcessChoicePoint(BasicBlock* bb) {
199 BranchInst* t = cast<BranchInst>(bb->getTerminator());
200
201 //decrement counter
202 LoadInst* l = new LoadInst(Counter, "counter", t);
203
Andrew Lenharth517caef2005-11-28 18:00:38 +0000204 SetCondInst* s = new SetCondInst(Instruction::SetEQ, l,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000205 ConstantInt::get(T, 0),
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000206 "countercc", t);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000207 Value* nv = BinaryOperator::createSub(l, ConstantInt::get(T, 1),
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000208 "counternew", t);
209 new StoreInst(nv, Counter, t);
210 t->setCondition(s);
211
212 //reset counter
213 BasicBlock* oldnext = t->getSuccessor(0);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000214 BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(),
215 oldnext);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000216 TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
217 t->setSuccessor(0, resetblock);
218 new StoreInst(ResetValue, Counter, t2);
219 ReplacePhiPred(oldnext, bb, resetblock);
220}
221
222GlobalRandomCounterOpt::GlobalRandomCounterOpt(Module& M, const Type* t,
223 uint64_t resetval)
224 : AI(0), T(t) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000225 ConstantInt* Init = ConstantInt::get(T, resetval);
226 ResetValue = Init;
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000227 Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000228 Init, "RandomSteeringCounter", &M);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000229}
230
231GlobalRandomCounterOpt::~GlobalRandomCounterOpt() {}
232
233void GlobalRandomCounterOpt::PrepFunction(Function* F) {
234 //make a local temporary to cache the global
235 BasicBlock& bb = F->getEntryBlock();
236 AI = new AllocaInst(T, 0, "localcounter", bb.begin());
237 LoadInst* l = new LoadInst(Counter, "counterload", AI->getNext());
238 new StoreInst(l, AI, l->getNext());
239
Andrew Lenharthd2511922005-11-28 18:10:59 +0000240 //modify all functions and return values to restore the local variable to/from
241 //the global variable
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000242 for(Function::iterator fib = F->begin(), fie = F->end();
243 fib != fie; ++fib)
244 for(BasicBlock::iterator bib = fib->begin(), bie = fib->end();
245 bib != bie; ++bib)
246 if (isa<CallInst>(&*bib)) {
247 LoadInst* l = new LoadInst(AI, "counter", bib);
248 new StoreInst(l, Counter, bib);
249 l = new LoadInst(Counter, "counter", bib->getNext());
250 new StoreInst(l, AI, l->getNext());
251 } else if (isa<InvokeInst>(&*bib)) {
252 LoadInst* l = new LoadInst(AI, "counter", bib);
253 new StoreInst(l, Counter, bib);
254
255 BasicBlock* bb = cast<InvokeInst>(&*bib)->getNormalDest();
256 Instruction* i = bb->begin();
257 while (isa<PHINode>(i)) i = i->getNext();
258 l = new LoadInst(Counter, "counter", i);
259
260 bb = cast<InvokeInst>(&*bib)->getUnwindDest();
261 i = bb->begin();
262 while (isa<PHINode>(i)) i = i->getNext();
263 l = new LoadInst(Counter, "counter", i);
264 new StoreInst(l, AI, l->getNext());
265 } else if (isa<UnwindInst>(&*bib) || isa<ReturnInst>(&*bib)) {
266 LoadInst* l = new LoadInst(AI, "counter", bib);
267 new StoreInst(l, Counter, bib);
268 }
269}
270
271void GlobalRandomCounterOpt::ProcessChoicePoint(BasicBlock* bb) {
272 BranchInst* t = cast<BranchInst>(bb->getTerminator());
273
274 //decrement counter
275 LoadInst* l = new LoadInst(AI, "counter", t);
276
Andrew Lenharth517caef2005-11-28 18:00:38 +0000277 SetCondInst* s = new SetCondInst(Instruction::SetEQ, l,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000278 ConstantInt::get(T, 0),
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000279 "countercc", t);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000280 Value* nv = BinaryOperator::createSub(l, ConstantInt::get(T, 1),
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000281 "counternew", t);
282 new StoreInst(nv, AI, t);
283 t->setCondition(s);
284
285 //reset counter
286 BasicBlock* oldnext = t->getSuccessor(0);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000287 BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(),
288 oldnext);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000289 TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
290 t->setSuccessor(0, resetblock);
291 new StoreInst(ResetValue, AI, t2);
292 ReplacePhiPred(oldnext, bb, resetblock);
293}
294
295
296CycleCounter::CycleCounter(Module& m, uint64_t resetmask) : rm(resetmask) {
297 F = m.getOrInsertFunction("llvm.readcyclecounter", Type::ULongTy, NULL);
298}
299
300CycleCounter::~CycleCounter() {}
301
302void CycleCounter::PrepFunction(Function* F) {}
303
304void CycleCounter::ProcessChoicePoint(BasicBlock* bb) {
305 BranchInst* t = cast<BranchInst>(bb->getTerminator());
306
307 CallInst* c = new CallInst(F, "rdcc", t);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000308 BinaryOperator* b =
Reid Spencere0fc4df2006-10-20 07:07:24 +0000309 BinaryOperator::createAnd(c, ConstantInt::get(Type::ULongTy, rm),
Andrew Lenharth517caef2005-11-28 18:00:38 +0000310 "mrdcc", t);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000311
Andrew Lenharth517caef2005-11-28 18:00:38 +0000312 SetCondInst* s = new SetCondInst(Instruction::SetEQ, b,
Reid Spencere0fc4df2006-10-20 07:07:24 +0000313 ConstantInt::get(Type::ULongTy, 0),
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000314 "mrdccc", t);
315 t->setCondition(s);
316}
317
318///////////////////////////////////////
319// Profiling:
320///////////////////////////////////////
Andrew Lenharth517caef2005-11-28 18:00:38 +0000321bool RSProfilers_std::isProfiling(Value* v) {
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000322 if (profcode.find(v) != profcode.end())
323 return true;
324 //else
325 RSProfilers& LI = getAnalysis<RSProfilers>();
326 return LI.isProfiling(v);
327}
328
Andrew Lenharth517caef2005-11-28 18:00:38 +0000329void RSProfilers_std::IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000330 GlobalValue *CounterArray) {
331 // Insert the increment after any alloca or PHI instructions...
332 BasicBlock::iterator InsertPos = BB->begin();
333 while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
334 ++InsertPos;
335
336 // Create the getelementptr constant expression
337 std::vector<Constant*> Indices(2);
338 Indices[0] = Constant::getNullValue(Type::IntTy);
Reid Spencere0fc4df2006-10-20 07:07:24 +0000339 Indices[1] = ConstantInt::get(Type::IntTy, CounterNum);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000340 Constant *ElementPtr = ConstantExpr::getGetElementPtr(CounterArray, Indices);
341
342 // Load, increment and store the value back.
343 Value *OldVal = new LoadInst(ElementPtr, "OldCounter", InsertPos);
344 profcode.insert(OldVal);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000345 Value *NewVal = BinaryOperator::createAdd(OldVal,
346 ConstantInt::get(Type::UIntTy, 1),
347 "NewCounter", InsertPos);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000348 profcode.insert(NewVal);
349 profcode.insert(new StoreInst(NewVal, ElementPtr, InsertPos));
350}
351
Andrew Lenharth517caef2005-11-28 18:00:38 +0000352void RSProfilers_std::getAnalysisUsage(AnalysisUsage &AU) const {
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000353 //grab any outstanding profiler, or get the null one
354 AU.addRequired<RSProfilers>();
355}
356
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000357///////////////////////////////////////
358// RS Framework
359///////////////////////////////////////
360
361Value* ProfilerRS::Translate(Value* v) {
362 if(TransCache[v])
363 return TransCache[v];
364
365 if (BasicBlock* bb = dyn_cast<BasicBlock>(v)) {
366 if (bb == &bb->getParent()->getEntryBlock())
367 TransCache[bb] = bb; //don't translate entry block
368 else
Andrew Lenharth517caef2005-11-28 18:00:38 +0000369 TransCache[bb] = new BasicBlock("dup_" + bb->getName(), bb->getParent(),
370 NULL);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000371 return TransCache[bb];
372 } else if (Instruction* i = dyn_cast<Instruction>(v)) {
373 //we have already translated this
374 //do not translate entry block allocas
375 if(&i->getParent()->getParent()->getEntryBlock() == i->getParent()) {
376 TransCache[i] = i;
377 return i;
378 } else {
379 //translate this
380 Instruction* i2 = i->clone();
381 if (i->hasName())
382 i2->setName("dup_" + i->getName());
383 TransCache[i] = i2;
384 //NumNewInst++;
385 for (unsigned x = 0; x < i2->getNumOperands(); ++x)
386 i2->setOperand(x, Translate(i2->getOperand(x)));
387 return i2;
388 }
389 } else if (isa<Function>(v) || isa<Constant>(v) || isa<Argument>(v)) {
390 TransCache[v] = v;
391 return v;
392 }
393 assert(0 && "Value not handled");
Jeff Cohen7ff44ec2005-11-28 06:45:57 +0000394 return 0;
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000395}
396
397void ProfilerRS::Duplicate(Function& F, RSProfilers& LI)
398{
399 //perform a breadth first search, building up a duplicate of the code
400 std::queue<BasicBlock*> worklist;
401 std::set<BasicBlock*> seen;
402
403 //This loop ensures proper BB order, to help performance
404 for (Function::iterator fib = F.begin(), fie = F.end(); fib != fie; ++fib)
405 worklist.push(fib);
406 while (!worklist.empty()) {
407 Translate(worklist.front());
408 worklist.pop();
409 }
410
411 //remember than reg2mem created a new entry block we don't want to duplicate
412 worklist.push(F.getEntryBlock().getTerminator()->getSuccessor(0));
413 seen.insert(&F.getEntryBlock());
414
415 while (!worklist.empty()) {
416 BasicBlock* bb = worklist.front();
417 worklist.pop();
418 if(seen.find(bb) == seen.end()) {
419 BasicBlock* bbtarget = cast<BasicBlock>(Translate(bb));
420 BasicBlock::InstListType& instlist = bbtarget->getInstList();
421 for (BasicBlock::iterator iib = bb->begin(), iie = bb->end();
422 iib != iie; ++iib) {
423 //NumOldInst++;
424 if (!LI.isProfiling(&*iib)) {
425 Instruction* i = cast<Instruction>(Translate(iib));
426 instlist.insert(bbtarget->end(), i);
427 }
428 }
429 //updated search state;
430 seen.insert(bb);
431 TerminatorInst* ti = bb->getTerminator();
432 for (unsigned x = 0; x < ti->getNumSuccessors(); ++x) {
433 BasicBlock* bbs = ti->getSuccessor(x);
434 if (seen.find(bbs) == seen.end()) {
435 worklist.push(bbs);
436 }
437 }
438 }
439 }
440}
441
442void ProfilerRS::ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F) {
443 //given a backedge from B -> A, and translations A' and B',
444 //a: insert C and C'
445 //b: add branches in C to A and A' and in C' to A and A'
446 //c: mod terminators@B, replace A with C
447 //d: mod terminators@B', replace A' with C'
448 //e: mod phis@A for pred B to be pred C
449 // if multiple entries, simplify to one
450 //f: mod phis@A' for pred B' to be pred C'
451 // if multiple entries, simplify to one
452 //g: for all phis@A with pred C using x
453 // add in edge from C' using x'
454 // add in edge from C using x in A'
455
456 //a:
457 BasicBlock* bbC = new BasicBlock("choice", &F, src->getNext() );
458 //ChoicePoints.insert(bbC);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000459 BasicBlock* bbCp =
460 new BasicBlock("choice", &F, cast<BasicBlock>(Translate(src))->getNext() );
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000461 ChoicePoints.insert(bbCp);
462
463 //b:
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000464 new BranchInst(cast<BasicBlock>(Translate(dst)), bbC);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000465 new BranchInst(dst, cast<BasicBlock>(Translate(dst)),
466 ConstantBool::get(true), bbCp);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000467 //c:
468 {
469 TerminatorInst* iB = src->getTerminator();
470 for (unsigned x = 0; x < iB->getNumSuccessors(); ++x)
471 if (iB->getSuccessor(x) == dst)
472 iB->setSuccessor(x, bbC);
473 }
474 //d:
475 {
476 TerminatorInst* iBp = cast<TerminatorInst>(Translate(src->getTerminator()));
477 for (unsigned x = 0; x < iBp->getNumSuccessors(); ++x)
478 if (iBp->getSuccessor(x) == cast<BasicBlock>(Translate(dst)))
479 iBp->setSuccessor(x, bbCp);
480 }
481 //e:
482 ReplacePhiPred(dst, src, bbC);
483 //src could be a switch, in which case we are replacing several edges with one
484 //thus collapse those edges int the Phi
485 CollapsePhi(dst, bbC);
486 //f:
Andrew Lenharth517caef2005-11-28 18:00:38 +0000487 ReplacePhiPred(cast<BasicBlock>(Translate(dst)),
488 cast<BasicBlock>(Translate(src)),bbCp);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000489 CollapsePhi(cast<BasicBlock>(Translate(dst)), bbCp);
490 //g:
491 for(BasicBlock::iterator ib = dst->begin(), ie = dst->end(); ib != ie;
492 ++ib)
493 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
494 for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
495 if(bbC == phi->getIncomingBlock(x)) {
496 phi->addIncoming(Translate(phi->getIncomingValue(x)), bbCp);
Andrew Lenharth517caef2005-11-28 18:00:38 +0000497 cast<PHINode>(Translate(phi))->addIncoming(phi->getIncomingValue(x),
498 bbC);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000499 }
500 phi->removeIncomingValue(bbC);
501 }
502}
503
504bool ProfilerRS::runOnFunction(Function& F) {
505 if (!F.isExternal()) {
506 std::set<std::pair<BasicBlock*, BasicBlock*> > BackEdges;
507 RSProfilers& LI = getAnalysis<RSProfilers>();
508
509 getBackEdges(F, BackEdges);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000510 Duplicate(F, LI);
511 //assume that stuff worked. now connect the duplicated basic blocks
512 //with the originals in such a way as to preserve ssa. yuk!
Andrew Lenharth517caef2005-11-28 18:00:38 +0000513 for (std::set<std::pair<BasicBlock*, BasicBlock*> >::iterator
514 ib = BackEdges.begin(), ie = BackEdges.end(); ib != ie; ++ib)
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000515 ProcessBackEdge(ib->first, ib->second, F);
516
Andrew Lenharth517caef2005-11-28 18:00:38 +0000517 //oh, and add the edge from the reg2mem created entry node to the
518 //duplicated second node
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000519 TerminatorInst* T = F.getEntryBlock().getTerminator();
520 ReplaceInstWithInst(T, new BranchInst(T->getSuccessor(0),
Andrew Lenharth517caef2005-11-28 18:00:38 +0000521 cast<BasicBlock>(Translate(T->getSuccessor(0))),
522 ConstantBool::get(true)));
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000523
524 //do whatever is needed now that the function is duplicated
525 c->PrepFunction(&F);
526
527 //add entry node to choice points
528 ChoicePoints.insert(&F.getEntryBlock());
529
Andrew Lenharth517caef2005-11-28 18:00:38 +0000530 for (std::set<BasicBlock*>::iterator
531 ii = ChoicePoints.begin(), ie = ChoicePoints.end(); ii != ie; ++ii)
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000532 c->ProcessChoicePoint(*ii);
533
534 ChoicePoints.clear();
535 TransCache.clear();
536
537 return true;
538 }
539 return false;
540}
541
542bool ProfilerRS::doInitialization(Module &M) {
543 switch (RandomMethod) {
544 case GBV:
545 c = new GlobalRandomCounter(M, Type::UIntTy, (1 << 14) - 1);
546 break;
547 case GBVO:
548 c = new GlobalRandomCounterOpt(M, Type::UIntTy, (1 << 14) - 1);
549 break;
550 case HOSTCC:
551 c = new CycleCounter(M, (1 << 14) - 1);
552 break;
553 };
554 return true;
555}
556
557void ProfilerRS::getAnalysisUsage(AnalysisUsage &AU) const {
558 AU.addRequired<RSProfilers>();
559 AU.addRequiredID(DemoteRegisterToMemoryID);
560}
561
562///////////////////////////////////////
563// Utilities:
564///////////////////////////////////////
565static void ReplacePhiPred(BasicBlock* btarget,
566 BasicBlock* bold, BasicBlock* bnew) {
567 for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
568 ib != ie; ++ib)
569 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
570 for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
571 if(bold == phi->getIncomingBlock(x))
572 phi->setIncomingBlock(x, bnew);
573 }
574}
575
576static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc) {
577 for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
578 ib != ie; ++ib)
579 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000580 std::map<BasicBlock*, Value*> counter;
581 for(unsigned i = 0; i < phi->getNumIncomingValues(); ) {
582 if (counter[phi->getIncomingBlock(i)]) {
Andrew Lenharth517caef2005-11-28 18:00:38 +0000583 assert(phi->getIncomingValue(i) == counter[phi->getIncomingBlock(i)]);
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000584 phi->removeIncomingValue(i, false);
585 } else {
586 counter[phi->getIncomingBlock(i)] = phi->getIncomingValue(i);
587 ++i;
588 }
589 }
590 }
591}
592
593template<class T>
594static void recBackEdge(BasicBlock* bb, T& BackEdges,
595 std::map<BasicBlock*, int>& color,
596 std::map<BasicBlock*, int>& depth,
597 std::map<BasicBlock*, int>& finish,
598 int& time)
599{
600 color[bb] = 1;
601 ++time;
602 depth[bb] = time;
603 TerminatorInst* t= bb->getTerminator();
604 for(unsigned i = 0; i < t->getNumSuccessors(); ++i) {
605 BasicBlock* bbnew = t->getSuccessor(i);
606 if (color[bbnew] == 0)
607 recBackEdge(bbnew, BackEdges, color, depth, finish, time);
608 else if (color[bbnew] == 1) {
609 BackEdges.insert(std::make_pair(bb, bbnew));
610 //NumBackEdges++;
611 }
612 }
613 color[bb] = 2;
614 ++time;
615 finish[bb] = time;
616}
617
618
619
620//find the back edges and where they go to
621template<class T>
622static void getBackEdges(Function& F, T& BackEdges) {
623 std::map<BasicBlock*, int> color;
624 std::map<BasicBlock*, int> depth;
625 std::map<BasicBlock*, int> finish;
626 int time = 0;
627 recBackEdge(&F.getEntryBlock(), BackEdges, color, depth, finish, time);
Bill Wendlinga7459ca2006-11-26 09:17:06 +0000628 DOUT << F.getName() << " " << BackEdges.size() << "\n";
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000629}
630
631
632//Creation functions
Andrew Lenharth93e59f62005-11-28 00:58:09 +0000633ModulePass* llvm::createNullProfilerRSPass() {
634 return new NullProfilerRS();
635}
636
637FunctionPass* llvm::createRSProfilingPass() {
638 return new ProfilerRS();
639}