1 //===- RSProfiling.cpp - Various profiling using random sampling ----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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
13 // passes which insert profiling into the program, and remember what they
16 // 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.
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)
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)
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
33 //===----------------------------------------------------------------------===//
35 #include "llvm/Pass.h"
36 #include "llvm/Module.h"
37 #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"
46 //#include "ProfilingUtils.h"
47 #include "RSProfiling.h"
58 Statistic<> NumBackEdges("bedge", "Number of BackEdges");
64 cl::opt<RandomMeth> RandomMethod("profile-randomness",
65 cl::desc("How to randomly choose to profile:"),
67 clEnumValN(GBV, "global", "global counter"),
68 clEnumValN(GBVO, "ra_global",
69 "register allocated global counter"),
70 clEnumValN(HOSTCC, "rdcc", "cycle counter"),
73 /// NullProfilerRS - The basic profiler that does nothing. It is the default
74 /// profiler and thus terminates RSProfiler chains. It is useful for
75 /// measuring framework overhead
76 class NullProfilerRS : public RSProfilers {
78 bool isProfiling(Value* v) {
81 bool runOnModule(Module &M) {
84 void getAnalysisUsage(AnalysisUsage &AU) const {
89 static RegisterAnalysisGroup<RSProfilers> A("Profiling passes");
90 static RegisterPass<NullProfilerRS> NP("insert-null-profiling-rs",
91 "Measure profiling framework overhead");
92 static RegisterAnalysisGroup<RSProfilers, true> NPT(NP);
94 /// Chooser - Something that chooses when to make a sample of the profiled code
97 /// ProcessChoicePoint - is called for each basic block inserted to choose
98 /// between normal and sample code
99 virtual void ProcessChoicePoint(BasicBlock*) = 0;
100 /// PrepFunction - is called once per function before other work is done.
101 /// This gives the opertunity to insert new allocas and such.
102 virtual void PrepFunction(Function*) = 0;
103 virtual ~Chooser() {}
106 //Things that implement sampling policies
107 //A global value that is read-mod-stored to choose when to sample.
108 //A sample is taken when the global counter hits 0
109 class GlobalRandomCounter : public Chooser {
110 GlobalVariable* Counter;
114 GlobalRandomCounter(Module& M, const Type* t, uint64_t resetval);
115 virtual ~GlobalRandomCounter();
116 virtual void PrepFunction(Function* F);
117 virtual void ProcessChoicePoint(BasicBlock* bb);
120 //Same is GRC, but allow register allocation of the global counter
121 class GlobalRandomCounterOpt : public Chooser {
122 GlobalVariable* Counter;
127 GlobalRandomCounterOpt(Module& M, const Type* t, uint64_t resetval);
128 virtual ~GlobalRandomCounterOpt();
129 virtual void PrepFunction(Function* F);
130 virtual void ProcessChoicePoint(BasicBlock* bb);
133 //Use the cycle counter intrinsic as a source of pseudo randomness when
134 //deciding when to sample.
135 class CycleCounter : public Chooser {
139 CycleCounter(Module& m, uint64_t resetmask);
140 virtual ~CycleCounter();
141 virtual void PrepFunction(Function* F);
142 virtual void ProcessChoicePoint(BasicBlock* bb);
145 /// ProfilerRS - Insert the random sampling framework
146 struct ProfilerRS : public FunctionPass {
147 std::map<Value*, Value*> TransCache;
148 std::set<BasicBlock*> ChoicePoints;
151 //Translate and duplicate values for the new profile free version of stuff
152 Value* Translate(Value* v);
153 //Duplicate an entire function (with out profiling)
154 void Duplicate(Function& F, RSProfilers& LI);
155 //Called once for each backedge, handle the insertion of choice points and
156 //the interconection of the two versions of the code
157 void ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F);
158 bool runOnFunction(Function& F);
159 bool doInitialization(Module &M);
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
163 RegisterPass<ProfilerRS> X("insert-rs-profiling-framework",
164 "Insert random sampling instrumentation framework");
168 static void ReplacePhiPred(BasicBlock* btarget,
169 BasicBlock* bold, BasicBlock* bnew);
171 static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc);
174 static void recBackEdge(BasicBlock* bb, T& BackEdges,
175 std::map<BasicBlock*, int>& color,
176 std::map<BasicBlock*, int>& depth,
177 std::map<BasicBlock*, int>& finish,
180 //find the back edges and where they go to
182 static void getBackEdges(Function& F, T& BackEdges);
185 ///////////////////////////////////////
186 // Methods of choosing when to profile
187 ///////////////////////////////////////
189 GlobalRandomCounter::GlobalRandomCounter(Module& M, const Type* t,
190 uint64_t resetval) : T(t) {
191 ConstantInt* Init = ConstantInt::get(T, resetval);
193 Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
194 Init, "RandomSteeringCounter", &M);
197 GlobalRandomCounter::~GlobalRandomCounter() {}
199 void GlobalRandomCounter::PrepFunction(Function* F) {}
201 void GlobalRandomCounter::ProcessChoicePoint(BasicBlock* bb) {
202 BranchInst* t = cast<BranchInst>(bb->getTerminator());
205 LoadInst* l = new LoadInst(Counter, "counter", t);
207 SetCondInst* s = new SetCondInst(Instruction::SetEQ, l,
208 ConstantInt::get(T, 0),
210 Value* nv = BinaryOperator::createSub(l, ConstantInt::get(T, 1),
212 new StoreInst(nv, Counter, t);
216 BasicBlock* oldnext = t->getSuccessor(0);
217 BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(),
219 TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
220 t->setSuccessor(0, resetblock);
221 new StoreInst(ResetValue, Counter, t2);
222 ReplacePhiPred(oldnext, bb, resetblock);
225 GlobalRandomCounterOpt::GlobalRandomCounterOpt(Module& M, const Type* t,
228 ConstantInt* Init = ConstantInt::get(T, resetval);
230 Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
231 Init, "RandomSteeringCounter", &M);
234 GlobalRandomCounterOpt::~GlobalRandomCounterOpt() {}
236 void GlobalRandomCounterOpt::PrepFunction(Function* F) {
237 //make a local temporary to cache the global
238 BasicBlock& bb = F->getEntryBlock();
239 AI = new AllocaInst(T, 0, "localcounter", bb.begin());
240 LoadInst* l = new LoadInst(Counter, "counterload", AI->getNext());
241 new StoreInst(l, AI, l->getNext());
243 //modify all functions and return values to restore the local variable to/from
244 //the global variable
245 for(Function::iterator fib = F->begin(), fie = F->end();
247 for(BasicBlock::iterator bib = fib->begin(), bie = fib->end();
249 if (isa<CallInst>(&*bib)) {
250 LoadInst* l = new LoadInst(AI, "counter", bib);
251 new StoreInst(l, Counter, bib);
252 l = new LoadInst(Counter, "counter", bib->getNext());
253 new StoreInst(l, AI, l->getNext());
254 } else if (isa<InvokeInst>(&*bib)) {
255 LoadInst* l = new LoadInst(AI, "counter", bib);
256 new StoreInst(l, Counter, bib);
258 BasicBlock* bb = cast<InvokeInst>(&*bib)->getNormalDest();
259 Instruction* i = bb->begin();
260 while (isa<PHINode>(i)) i = i->getNext();
261 l = new LoadInst(Counter, "counter", i);
263 bb = cast<InvokeInst>(&*bib)->getUnwindDest();
265 while (isa<PHINode>(i)) i = i->getNext();
266 l = new LoadInst(Counter, "counter", i);
267 new StoreInst(l, AI, l->getNext());
268 } else if (isa<UnwindInst>(&*bib) || isa<ReturnInst>(&*bib)) {
269 LoadInst* l = new LoadInst(AI, "counter", bib);
270 new StoreInst(l, Counter, bib);
274 void GlobalRandomCounterOpt::ProcessChoicePoint(BasicBlock* bb) {
275 BranchInst* t = cast<BranchInst>(bb->getTerminator());
278 LoadInst* l = new LoadInst(AI, "counter", t);
280 SetCondInst* s = new SetCondInst(Instruction::SetEQ, l,
281 ConstantInt::get(T, 0),
283 Value* nv = BinaryOperator::createSub(l, ConstantInt::get(T, 1),
285 new StoreInst(nv, AI, t);
289 BasicBlock* oldnext = t->getSuccessor(0);
290 BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(),
292 TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
293 t->setSuccessor(0, resetblock);
294 new StoreInst(ResetValue, AI, t2);
295 ReplacePhiPred(oldnext, bb, resetblock);
299 CycleCounter::CycleCounter(Module& m, uint64_t resetmask) : rm(resetmask) {
300 F = m.getOrInsertFunction("llvm.readcyclecounter", Type::ULongTy, NULL);
303 CycleCounter::~CycleCounter() {}
305 void CycleCounter::PrepFunction(Function* F) {}
307 void CycleCounter::ProcessChoicePoint(BasicBlock* bb) {
308 BranchInst* t = cast<BranchInst>(bb->getTerminator());
310 CallInst* c = new CallInst(F, "rdcc", t);
312 BinaryOperator::createAnd(c, ConstantInt::get(Type::ULongTy, rm),
315 SetCondInst* s = new SetCondInst(Instruction::SetEQ, b,
316 ConstantInt::get(Type::ULongTy, 0),
321 ///////////////////////////////////////
323 ///////////////////////////////////////
324 bool RSProfilers_std::isProfiling(Value* v) {
325 if (profcode.find(v) != profcode.end())
328 RSProfilers& LI = getAnalysis<RSProfilers>();
329 return LI.isProfiling(v);
332 void RSProfilers_std::IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
333 GlobalValue *CounterArray) {
334 // Insert the increment after any alloca or PHI instructions...
335 BasicBlock::iterator InsertPos = BB->begin();
336 while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
339 // Create the getelementptr constant expression
340 std::vector<Constant*> Indices(2);
341 Indices[0] = Constant::getNullValue(Type::IntTy);
342 Indices[1] = ConstantInt::get(Type::IntTy, CounterNum);
343 Constant *ElementPtr = ConstantExpr::getGetElementPtr(CounterArray, Indices);
345 // Load, increment and store the value back.
346 Value *OldVal = new LoadInst(ElementPtr, "OldCounter", InsertPos);
347 profcode.insert(OldVal);
348 Value *NewVal = BinaryOperator::createAdd(OldVal,
349 ConstantInt::get(Type::UIntTy, 1),
350 "NewCounter", InsertPos);
351 profcode.insert(NewVal);
352 profcode.insert(new StoreInst(NewVal, ElementPtr, InsertPos));
355 void RSProfilers_std::getAnalysisUsage(AnalysisUsage &AU) const {
356 //grab any outstanding profiler, or get the null one
357 AU.addRequired<RSProfilers>();
360 ///////////////////////////////////////
362 ///////////////////////////////////////
364 Value* ProfilerRS::Translate(Value* v) {
366 return TransCache[v];
368 if (BasicBlock* bb = dyn_cast<BasicBlock>(v)) {
369 if (bb == &bb->getParent()->getEntryBlock())
370 TransCache[bb] = bb; //don't translate entry block
372 TransCache[bb] = new BasicBlock("dup_" + bb->getName(), bb->getParent(),
374 return TransCache[bb];
375 } else if (Instruction* i = dyn_cast<Instruction>(v)) {
376 //we have already translated this
377 //do not translate entry block allocas
378 if(&i->getParent()->getParent()->getEntryBlock() == i->getParent()) {
383 Instruction* i2 = i->clone();
385 i2->setName("dup_" + i->getName());
388 for (unsigned x = 0; x < i2->getNumOperands(); ++x)
389 i2->setOperand(x, Translate(i2->getOperand(x)));
392 } else if (isa<Function>(v) || isa<Constant>(v) || isa<Argument>(v)) {
396 assert(0 && "Value not handled");
400 void ProfilerRS::Duplicate(Function& F, RSProfilers& LI)
402 //perform a breadth first search, building up a duplicate of the code
403 std::queue<BasicBlock*> worklist;
404 std::set<BasicBlock*> seen;
406 //This loop ensures proper BB order, to help performance
407 for (Function::iterator fib = F.begin(), fie = F.end(); fib != fie; ++fib)
409 while (!worklist.empty()) {
410 Translate(worklist.front());
414 //remember than reg2mem created a new entry block we don't want to duplicate
415 worklist.push(F.getEntryBlock().getTerminator()->getSuccessor(0));
416 seen.insert(&F.getEntryBlock());
418 while (!worklist.empty()) {
419 BasicBlock* bb = worklist.front();
421 if(seen.find(bb) == seen.end()) {
422 BasicBlock* bbtarget = cast<BasicBlock>(Translate(bb));
423 BasicBlock::InstListType& instlist = bbtarget->getInstList();
424 for (BasicBlock::iterator iib = bb->begin(), iie = bb->end();
427 if (!LI.isProfiling(&*iib)) {
428 Instruction* i = cast<Instruction>(Translate(iib));
429 instlist.insert(bbtarget->end(), i);
432 //updated search state;
434 TerminatorInst* ti = bb->getTerminator();
435 for (unsigned x = 0; x < ti->getNumSuccessors(); ++x) {
436 BasicBlock* bbs = ti->getSuccessor(x);
437 if (seen.find(bbs) == seen.end()) {
445 void ProfilerRS::ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F) {
446 //given a backedge from B -> A, and translations A' and B',
448 //b: add branches in C to A and A' and in C' to A and A'
449 //c: mod terminators@B, replace A with C
450 //d: mod terminators@B', replace A' with C'
451 //e: mod phis@A for pred B to be pred C
452 // if multiple entries, simplify to one
453 //f: mod phis@A' for pred B' to be pred C'
454 // if multiple entries, simplify to one
455 //g: for all phis@A with pred C using x
456 // add in edge from C' using x'
457 // add in edge from C using x in A'
460 BasicBlock* bbC = new BasicBlock("choice", &F, src->getNext() );
461 //ChoicePoints.insert(bbC);
463 new BasicBlock("choice", &F, cast<BasicBlock>(Translate(src))->getNext() );
464 ChoicePoints.insert(bbCp);
467 new BranchInst(cast<BasicBlock>(Translate(dst)), bbC);
468 new BranchInst(dst, cast<BasicBlock>(Translate(dst)),
469 ConstantBool::get(true), bbCp);
472 TerminatorInst* iB = src->getTerminator();
473 for (unsigned x = 0; x < iB->getNumSuccessors(); ++x)
474 if (iB->getSuccessor(x) == dst)
475 iB->setSuccessor(x, bbC);
479 TerminatorInst* iBp = cast<TerminatorInst>(Translate(src->getTerminator()));
480 for (unsigned x = 0; x < iBp->getNumSuccessors(); ++x)
481 if (iBp->getSuccessor(x) == cast<BasicBlock>(Translate(dst)))
482 iBp->setSuccessor(x, bbCp);
485 ReplacePhiPred(dst, src, bbC);
486 //src could be a switch, in which case we are replacing several edges with one
487 //thus collapse those edges int the Phi
488 CollapsePhi(dst, bbC);
490 ReplacePhiPred(cast<BasicBlock>(Translate(dst)),
491 cast<BasicBlock>(Translate(src)),bbCp);
492 CollapsePhi(cast<BasicBlock>(Translate(dst)), bbCp);
494 for(BasicBlock::iterator ib = dst->begin(), ie = dst->end(); ib != ie;
496 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
497 for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
498 if(bbC == phi->getIncomingBlock(x)) {
499 phi->addIncoming(Translate(phi->getIncomingValue(x)), bbCp);
500 cast<PHINode>(Translate(phi))->addIncoming(phi->getIncomingValue(x),
503 phi->removeIncomingValue(bbC);
507 bool ProfilerRS::runOnFunction(Function& F) {
508 if (!F.isExternal()) {
509 std::set<std::pair<BasicBlock*, BasicBlock*> > BackEdges;
510 RSProfilers& LI = getAnalysis<RSProfilers>();
512 getBackEdges(F, BackEdges);
514 //assume that stuff worked. now connect the duplicated basic blocks
515 //with the originals in such a way as to preserve ssa. yuk!
516 for (std::set<std::pair<BasicBlock*, BasicBlock*> >::iterator
517 ib = BackEdges.begin(), ie = BackEdges.end(); ib != ie; ++ib)
518 ProcessBackEdge(ib->first, ib->second, F);
520 //oh, and add the edge from the reg2mem created entry node to the
521 //duplicated second node
522 TerminatorInst* T = F.getEntryBlock().getTerminator();
523 ReplaceInstWithInst(T, new BranchInst(T->getSuccessor(0),
524 cast<BasicBlock>(Translate(T->getSuccessor(0))),
525 ConstantBool::get(true)));
527 //do whatever is needed now that the function is duplicated
530 //add entry node to choice points
531 ChoicePoints.insert(&F.getEntryBlock());
533 for (std::set<BasicBlock*>::iterator
534 ii = ChoicePoints.begin(), ie = ChoicePoints.end(); ii != ie; ++ii)
535 c->ProcessChoicePoint(*ii);
537 ChoicePoints.clear();
545 bool ProfilerRS::doInitialization(Module &M) {
546 switch (RandomMethod) {
548 c = new GlobalRandomCounter(M, Type::UIntTy, (1 << 14) - 1);
551 c = new GlobalRandomCounterOpt(M, Type::UIntTy, (1 << 14) - 1);
554 c = new CycleCounter(M, (1 << 14) - 1);
560 void ProfilerRS::getAnalysisUsage(AnalysisUsage &AU) const {
561 AU.addRequired<RSProfilers>();
562 AU.addRequiredID(DemoteRegisterToMemoryID);
565 ///////////////////////////////////////
567 ///////////////////////////////////////
568 static void ReplacePhiPred(BasicBlock* btarget,
569 BasicBlock* bold, BasicBlock* bnew) {
570 for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
572 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
573 for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
574 if(bold == phi->getIncomingBlock(x))
575 phi->setIncomingBlock(x, bnew);
579 static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc) {
580 for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
582 if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
583 unsigned total = phi->getNumIncomingValues();
584 std::map<BasicBlock*, Value*> counter;
585 for(unsigned i = 0; i < phi->getNumIncomingValues(); ) {
586 if (counter[phi->getIncomingBlock(i)]) {
587 assert(phi->getIncomingValue(i) == counter[phi->getIncomingBlock(i)]);
588 phi->removeIncomingValue(i, false);
590 counter[phi->getIncomingBlock(i)] = phi->getIncomingValue(i);
598 static void recBackEdge(BasicBlock* bb, T& BackEdges,
599 std::map<BasicBlock*, int>& color,
600 std::map<BasicBlock*, int>& depth,
601 std::map<BasicBlock*, int>& finish,
607 TerminatorInst* t= bb->getTerminator();
608 for(unsigned i = 0; i < t->getNumSuccessors(); ++i) {
609 BasicBlock* bbnew = t->getSuccessor(i);
610 if (color[bbnew] == 0)
611 recBackEdge(bbnew, BackEdges, color, depth, finish, time);
612 else if (color[bbnew] == 1) {
613 BackEdges.insert(std::make_pair(bb, bbnew));
624 //find the back edges and where they go to
626 static void getBackEdges(Function& F, T& BackEdges) {
627 std::map<BasicBlock*, int> color;
628 std::map<BasicBlock*, int> depth;
629 std::map<BasicBlock*, int> finish;
631 recBackEdge(&F.getEntryBlock(), BackEdges, color, depth, finish, time);
632 DEBUG(std::cerr << F.getName() << " " << BackEdges.size() << "\n");
637 ModulePass* llvm::createNullProfilerRSPass() {
638 return new NullProfilerRS();
641 FunctionPass* llvm::createRSProfilingPass() {
642 return new ProfilerRS();