Fix VC++ warning.
[oota-llvm.git] / lib / Transforms / Instrumentation / RSProfiling.cpp
1 //===- 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
13 // passes which insert profiling into the program, and remember what they inserted.
14 // The second stage duplicates all instructions in a function, ignoring the 
15 // profiling code, then connects the two versions togeather at the entry and at
16 // backedges.  At each connection point a choice is made as to whether to jump
17 // to the profiled code (take a sample) or execute the unprofiled code.
18 //
19 // It is highly recommeneded that after this pass one runs mem2reg and adce
20 // (instcombine load-vn gdce dse also are good to run afterwards)
21 //
22 // This design is intended to make the profiling passes independent of the RS
23 // framework, but any profiling pass that implements the RSProfiling interface
24 // is compatible with the rs framework (and thus can be sampled)
25 //
26 // TODO: obviously the block and function profiling are almost identical to the
27 // existing ones, so they can be unified (esp since these passes are valid
28 // without the rs framework).
29 // TODO: Fix choice code so that frequency is not hard coded
30 //
31 //===----------------------------------------------------------------------===//
32
33 #include "llvm/Pass.h"
34 #include "llvm/Function.h"
35 #include "llvm/Module.h"
36 #include "llvm/BasicBlock.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"
48
49 #include <set>
50 #include <map>
51 #include <queue>
52 #include <list>
53 #include <iostream>
54
55 using namespace llvm;
56
57 namespace {
58   Statistic<> NumBackEdges("bedge", "Number of BackEdges");
59
60   enum RandomMeth {
61     GBV, GBVO, HOSTCC
62   };
63
64   cl::opt<RandomMeth> RandomMethod("profile-randomness",
65       cl::desc("How to randomly choose to profile:"),
66       cl::values(
67                  clEnumValN(GBV, "global", "global counter"),
68                  clEnumValN(GBVO, "ra_global", "register allocated global counter"),
69                  clEnumValN(HOSTCC, "rdcc", "cycle counter"),
70                  clEnumValEnd));
71   
72
73   class FunctionProfilerRS : public RSProfilers {
74     bool runOnModule(Module &M);
75   };
76
77   class BlockProfilerRS : public RSProfilers {
78     bool runOnModule(Module &M);
79   };
80
81   class NullProfilerRS : public RSProfilers {
82   public:
83     bool isProfiling(Value* v) {
84       return false;
85     }
86     bool runOnModule(Module &M) {
87       return false;
88     }
89     void getAnalysisUsage(AnalysisUsage &AU) const {
90       AU.setPreservesAll();
91     }
92   };
93
94   static RegisterAnalysisGroup<RSProfilers> A("Profiling passes");
95   static RegisterOpt<NullProfilerRS> NP("insert-null-profiling-rs",
96                                           "Measure profiling framework overhead");
97   static RegisterAnalysisGroup<RSProfilers, NullProfilerRS, true> NPT;
98   static RegisterOpt<BlockProfilerRS> BBP("insert-block-profiling-rs",
99                                           "Add block count instrumentation");
100   static RegisterAnalysisGroup<RSProfilers, BlockProfilerRS> BBPT;
101   static RegisterOpt<FunctionProfilerRS> FP("insert-function-profiling-rs",
102                                           "Add function count instrumentation");
103   static RegisterAnalysisGroup<RSProfilers, FunctionProfilerRS> FPT;
104
105
106   //Something that chooses how to sample
107   class Chooser {
108   public:
109     virtual void ProcessChoicePoint(BasicBlock*) = 0;
110     virtual void PrepFunction(Function*) = 0;
111     virtual ~Chooser() {}
112   };
113
114   //Things that implement sampling policies
115   class GlobalRandomCounter : public Chooser {
116     GlobalVariable* Counter;
117     Value* ResetValue;
118     const Type* T;
119   public:
120     GlobalRandomCounter(Module& M, const Type* t, uint64_t resetval);
121     virtual ~GlobalRandomCounter();
122     virtual void PrepFunction(Function* F);
123     virtual void ProcessChoicePoint(BasicBlock* bb);
124   };
125
126   class GlobalRandomCounterOpt : public Chooser {
127     GlobalVariable* Counter;
128     Value* ResetValue;
129     AllocaInst* AI;
130     const Type* T;
131   public:
132     GlobalRandomCounterOpt(Module& M, const Type* t, uint64_t resetval);
133     virtual ~GlobalRandomCounterOpt();
134     virtual void PrepFunction(Function* F);
135     virtual void ProcessChoicePoint(BasicBlock* bb);
136   };
137
138   class CycleCounter : public Chooser {
139     uint64_t rm;
140     Function* F;
141   public:
142     CycleCounter(Module& m, uint64_t resetmask);
143     virtual ~CycleCounter();
144     virtual void PrepFunction(Function* F);
145     virtual void ProcessChoicePoint(BasicBlock* bb);
146   };
147
148
149   struct ProfilerRS : public FunctionPass {
150     std::map<Value*, Value*> TransCache;
151     std::set<BasicBlock*> ChoicePoints;
152     Chooser* c;
153
154     Value* Translate(Value* v);
155     void Duplicate(Function& F, RSProfilers& LI);
156     void ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F);
157     bool runOnFunction(Function& F);
158     bool doInitialization(Module &M);
159     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
160   };
161
162   RegisterOpt<ProfilerRS> X("insert-rs-profiling-framework",
163                                 "Insert random sampling instrumentation  framework");
164 };
165
166 //Local utilities
167 static void ReplacePhiPred(BasicBlock* btarget, 
168                            BasicBlock* bold, BasicBlock* bnew);
169
170 static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc);
171
172 template<class T>
173 static void recBackEdge(BasicBlock* bb, T& BackEdges, 
174                         std::map<BasicBlock*, int>& color,
175                         std::map<BasicBlock*, int>& depth,
176                         std::map<BasicBlock*, int>& finish,
177                         int& time);
178
179 //find the back edges and where they go to
180 template<class T>
181 static void getBackEdges(Function& F, T& BackEdges);
182
183
184 ///////////////////////////////////////
185 // Methods of choosing when to profile
186 ///////////////////////////////////////
187   
188 GlobalRandomCounter::GlobalRandomCounter(Module& M, const Type* t, 
189                                          uint64_t resetval) : T(t) {
190   Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
191                                ConstantUInt::get(T, resetval),
192                                "RandomSteeringCounter", &M);
193   ResetValue = ConstantUInt::get(T, resetval);
194 }
195
196 GlobalRandomCounter::~GlobalRandomCounter() {}
197
198 void GlobalRandomCounter::PrepFunction(Function* F) {}
199
200 void GlobalRandomCounter::ProcessChoicePoint(BasicBlock* bb) {
201   BranchInst* t = cast<BranchInst>(bb->getTerminator());
202   
203   //decrement counter
204   LoadInst* l = new LoadInst(Counter, "counter", t);
205   
206   SetCondInst* s = new SetCondInst(Instruction::SetEQ, l, ConstantUInt::get(T, 0), 
207                                    "countercc", t);
208   Value* nv = BinaryOperator::create(Instruction::Sub, l,
209                                      ConstantInt::get(T, 1),
210                                      "counternew", t);
211   new StoreInst(nv, Counter, t);
212   t->setCondition(s);
213   
214   //reset counter
215   BasicBlock* oldnext = t->getSuccessor(0);
216   BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(), oldnext);
217   TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
218   t->setSuccessor(0, resetblock);
219   new StoreInst(ResetValue, Counter, t2);
220   ReplacePhiPred(oldnext, bb, resetblock);
221 }
222
223 GlobalRandomCounterOpt::GlobalRandomCounterOpt(Module& M, const Type* t, 
224                                                uint64_t resetval) 
225   : AI(0), T(t) {
226   Counter = new GlobalVariable(T, false, GlobalValue::InternalLinkage,
227                                ConstantUInt::get(T, resetval),
228                                "RandomSteeringCounter", &M);
229   ResetValue = ConstantUInt::get(T, resetval);
230 }
231
232 GlobalRandomCounterOpt::~GlobalRandomCounterOpt() {}
233
234 void GlobalRandomCounterOpt::PrepFunction(Function* F) {
235   //make a local temporary to cache the global
236   BasicBlock& bb = F->getEntryBlock();
237   AI = new AllocaInst(T, 0, "localcounter", bb.begin());
238   LoadInst* l = new LoadInst(Counter, "counterload", AI->getNext());
239   new StoreInst(l, AI, l->getNext());
240   
241   //modify all functions and return values
242   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
271 void GlobalRandomCounterOpt::ProcessChoicePoint(BasicBlock* bb) {
272   BranchInst* t = cast<BranchInst>(bb->getTerminator());
273   
274   //decrement counter
275   LoadInst* l = new LoadInst(AI, "counter", t);
276   
277   SetCondInst* s = new SetCondInst(Instruction::SetEQ, l, ConstantUInt::get(T, 0), 
278                                    "countercc", t);
279   Value* nv = BinaryOperator::create(Instruction::Sub, l,
280                                      ConstantInt::get(T, 1),
281                                      "counternew", t);
282   new StoreInst(nv, AI, t);
283   t->setCondition(s);
284   
285   //reset counter
286   BasicBlock* oldnext = t->getSuccessor(0);
287   BasicBlock* resetblock = new BasicBlock("reset", oldnext->getParent(), oldnext);
288   TerminatorInst* t2 = new BranchInst(oldnext, resetblock);
289   t->setSuccessor(0, resetblock);
290   new StoreInst(ResetValue, AI, t2);
291   ReplacePhiPred(oldnext, bb, resetblock);
292 }
293
294
295 CycleCounter::CycleCounter(Module& m, uint64_t resetmask) : rm(resetmask) {
296   F = m.getOrInsertFunction("llvm.readcyclecounter", Type::ULongTy, NULL);
297 }
298
299 CycleCounter::~CycleCounter() {}
300
301 void CycleCounter::PrepFunction(Function* F) {}
302
303 void CycleCounter::ProcessChoicePoint(BasicBlock* bb) {
304   BranchInst* t = cast<BranchInst>(bb->getTerminator());
305   
306   CallInst* c = new CallInst(F, "rdcc", t);
307   BinaryOperator* b = BinaryOperator::create(Instruction::And, c, ConstantUInt::get(Type::ULongTy, rm), "mrdcc", t);
308   
309   SetCondInst* s = new SetCondInst(Instruction::SetEQ, b, ConstantUInt::get(Type::ULongTy, 0), 
310                                    "mrdccc", t);
311   t->setCondition(s);
312 }
313
314 ///////////////////////////////////////
315 // Profiling:
316 ///////////////////////////////////////
317 bool RSProfilers::isProfiling(Value* v) {
318   if (profcode.find(v) != profcode.end())
319     return true;
320   //else
321   RSProfilers& LI = getAnalysis<RSProfilers>();
322   return LI.isProfiling(v);
323 }
324
325 void RSProfilers::IncrementCounterInBlock(BasicBlock *BB, unsigned CounterNum,
326                                           GlobalValue *CounterArray) {
327   // Insert the increment after any alloca or PHI instructions...
328   BasicBlock::iterator InsertPos = BB->begin();
329   while (isa<AllocaInst>(InsertPos) || isa<PHINode>(InsertPos))
330     ++InsertPos;
331   
332   // Create the getelementptr constant expression
333   std::vector<Constant*> Indices(2);
334   Indices[0] = Constant::getNullValue(Type::IntTy);
335   Indices[1] = ConstantSInt::get(Type::IntTy, CounterNum);
336   Constant *ElementPtr = ConstantExpr::getGetElementPtr(CounterArray, Indices);
337   
338   // Load, increment and store the value back.
339   Value *OldVal = new LoadInst(ElementPtr, "OldCounter", InsertPos);
340   profcode.insert(OldVal);
341   Value *NewVal = BinaryOperator::create(Instruction::Add, OldVal,
342                                          ConstantInt::get(Type::UIntTy, 1),
343                                          "NewCounter", InsertPos);
344   profcode.insert(NewVal);
345   profcode.insert(new StoreInst(NewVal, ElementPtr, InsertPos));
346 }
347
348 void RSProfilers::getAnalysisUsage(AnalysisUsage &AU) const {
349   //grab any outstanding profiler, or get the null one
350   AU.addRequired<RSProfilers>();
351 }
352
353 bool FunctionProfilerRS::runOnModule(Module &M) {
354   Function *Main = M.getMainFunction();
355   if (Main == 0) {
356     std::cerr << "WARNING: cannot insert function profiling into a module"
357               << " with no main function!\n";
358     return false;  // No main, no instrumentation!
359   }
360   
361   unsigned NumFunctions = 0;
362   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
363     if (!I->isExternal())
364       ++NumFunctions;
365   
366   const Type *ATy = ArrayType::get(Type::UIntTy, NumFunctions);
367   GlobalVariable *Counters =
368     new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
369                        Constant::getNullValue(ATy), "FuncProfCounters", &M);
370   
371   // Instrument all of the functions...
372   unsigned i = 0;
373   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
374     if (!I->isExternal())
375       // Insert counter at the start of the function
376       IncrementCounterInBlock(I->begin(), i++, Counters);
377   
378   // Add the initialization call to main.
379   InsertProfilingInitCall(Main, "llvm_start_func_profiling", Counters);
380   return true;
381 }
382
383 bool BlockProfilerRS::runOnModule(Module &M) {
384   Function *Main = M.getMainFunction();
385   if (Main == 0) {
386     std::cerr << "WARNING: cannot insert block profiling into a module"
387               << " with no main function!\n";
388     return false;  // No main, no instrumentation!
389   }
390   
391   unsigned NumBlocks = 0;
392   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
393     NumBlocks += I->size();
394   
395   const Type *ATy = ArrayType::get(Type::UIntTy, NumBlocks);
396   GlobalVariable *Counters =
397     new GlobalVariable(ATy, false, GlobalValue::InternalLinkage,
398                        Constant::getNullValue(ATy), "BlockProfCounters", &M);
399   
400   // Instrument all of the blocks...
401   unsigned i = 0;
402   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
403     for (Function::iterator BB = I->begin(), E = I->end(); BB != E; ++BB)
404       // Insert counter at the start of the block
405       IncrementCounterInBlock(BB, i++, Counters);
406   
407   // Add the initialization call to main.
408   InsertProfilingInitCall(Main, "llvm_start_block_profiling", Counters);
409   return true;
410 }
411
412 ///////////////////////////////////////
413 // RS Framework
414 ///////////////////////////////////////
415
416 Value* ProfilerRS::Translate(Value* v) {
417   if(TransCache[v])
418     return TransCache[v];
419   
420   if (BasicBlock* bb = dyn_cast<BasicBlock>(v)) {
421     if (bb == &bb->getParent()->getEntryBlock())
422       TransCache[bb] = bb; //don't translate entry block
423     else
424       TransCache[bb] = new BasicBlock("dup_" + bb->getName(), bb->getParent(), NULL);
425     return TransCache[bb];
426   } else if (Instruction* i = dyn_cast<Instruction>(v)) {
427     //we have already translated this
428     //do not translate entry block allocas
429     if(&i->getParent()->getParent()->getEntryBlock() == i->getParent()) {
430       TransCache[i] = i;
431       return i;
432     } else {
433       //translate this
434       Instruction* i2 = i->clone();
435       if (i->hasName())
436         i2->setName("dup_" + i->getName());
437       TransCache[i] = i2;
438       //NumNewInst++;
439       for (unsigned x = 0; x < i2->getNumOperands(); ++x)
440         i2->setOperand(x, Translate(i2->getOperand(x)));
441       return i2;
442     }
443   } else if (isa<Function>(v) || isa<Constant>(v) || isa<Argument>(v)) {
444     TransCache[v] = v;
445     return v;
446   }
447   assert(0 && "Value not handled");
448   return 0;
449 }
450
451 void ProfilerRS::Duplicate(Function& F, RSProfilers& LI)
452 {
453   //perform a breadth first search, building up a duplicate of the code
454   std::queue<BasicBlock*> worklist;
455   std::set<BasicBlock*> seen;
456   
457   //This loop ensures proper BB order, to help performance
458   for (Function::iterator fib = F.begin(), fie = F.end(); fib != fie; ++fib)
459     worklist.push(fib);
460   while (!worklist.empty()) {
461     Translate(worklist.front());
462     worklist.pop();
463   }
464   
465   //remember than reg2mem created a new entry block we don't want to duplicate
466   worklist.push(F.getEntryBlock().getTerminator()->getSuccessor(0));
467   seen.insert(&F.getEntryBlock());
468   
469   while (!worklist.empty()) {
470     BasicBlock* bb = worklist.front();
471     worklist.pop();
472     if(seen.find(bb) == seen.end()) {
473       BasicBlock* bbtarget = cast<BasicBlock>(Translate(bb));
474       BasicBlock::InstListType& instlist = bbtarget->getInstList();
475       for (BasicBlock::iterator iib = bb->begin(), iie = bb->end(); 
476            iib != iie; ++iib) {
477         //NumOldInst++;
478         if (!LI.isProfiling(&*iib)) {
479           Instruction* i = cast<Instruction>(Translate(iib));
480           instlist.insert(bbtarget->end(), i);
481         }
482       }
483       //updated search state;
484       seen.insert(bb);
485       TerminatorInst* ti = bb->getTerminator();
486       for (unsigned x = 0; x < ti->getNumSuccessors(); ++x) {
487         BasicBlock* bbs = ti->getSuccessor(x);
488         if (seen.find(bbs) == seen.end()) {
489           worklist.push(bbs);
490         }
491       }
492     }
493   }
494 }
495
496 void ProfilerRS::ProcessBackEdge(BasicBlock* src, BasicBlock* dst, Function& F) {
497   //given a backedge from B -> A, and translations A' and B',
498   //a: insert C and C'
499   //b: add branches in C to A and A' and in C' to A and A'
500   //c: mod terminators@B, replace A with C
501   //d: mod terminators@B', replace A' with C'
502   //e: mod phis@A for pred B to be pred C
503   //       if multiple entries, simplify to one
504   //f: mod phis@A' for pred B' to be pred C'
505   //       if multiple entries, simplify to one
506   //g: for all phis@A with pred C using x
507   //       add in edge from C' using x'
508   //       add in edge from C using x in A'
509   
510   //a:
511   BasicBlock* bbC = new BasicBlock("choice", &F, src->getNext() );
512   //ChoicePoints.insert(bbC);
513   BasicBlock* bbCp = new BasicBlock("choice", &F, cast<BasicBlock>(Translate(src))->getNext() );
514   ChoicePoints.insert(bbCp);
515   
516   //b:
517   //new BranchInst(dst, cast<BasicBlock>(Translate(dst)), ConstantBool::get(true), bbC);
518   new BranchInst(cast<BasicBlock>(Translate(dst)), bbC);
519   new BranchInst(dst, cast<BasicBlock>(Translate(dst)), ConstantBool::get(true), bbCp);
520   //c:
521   {
522     TerminatorInst* iB = src->getTerminator();
523     for (unsigned x = 0; x < iB->getNumSuccessors(); ++x)
524       if (iB->getSuccessor(x) == dst)
525         iB->setSuccessor(x, bbC);
526   }
527   //d:
528   {
529     TerminatorInst* iBp = cast<TerminatorInst>(Translate(src->getTerminator()));
530     for (unsigned x = 0; x < iBp->getNumSuccessors(); ++x)
531       if (iBp->getSuccessor(x) == cast<BasicBlock>(Translate(dst)))
532         iBp->setSuccessor(x, bbCp);
533   }
534   //e:
535   ReplacePhiPred(dst, src, bbC);
536   //src could be a switch, in which case we are replacing several edges with one
537   //thus collapse those edges int the Phi
538   CollapsePhi(dst, bbC);
539   //f:
540   ReplacePhiPred(cast<BasicBlock>(Translate(dst)),cast<BasicBlock>(Translate(src)),bbCp);
541   CollapsePhi(cast<BasicBlock>(Translate(dst)), bbCp);
542   //g:
543   for(BasicBlock::iterator ib = dst->begin(), ie = dst->end(); ib != ie;
544       ++ib)
545     if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
546       for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
547         if(bbC == phi->getIncomingBlock(x)) {
548           phi->addIncoming(Translate(phi->getIncomingValue(x)), bbCp);
549           cast<PHINode>(Translate(phi))->addIncoming(phi->getIncomingValue(x), bbC);
550         }
551       phi->removeIncomingValue(bbC);
552     }
553 }
554
555 bool ProfilerRS::runOnFunction(Function& F) {
556   if (!F.isExternal()) {
557     std::set<std::pair<BasicBlock*, BasicBlock*> > BackEdges;
558     RSProfilers& LI = getAnalysis<RSProfilers>();
559     
560     getBackEdges(F, BackEdges);
561     DEBUG(
562           for (std::set<std::pair<BasicBlock*, BasicBlock*> >::iterator ii = BackEdges.begin();
563                ii != BackEdges.end(); ++ii)
564             std::cerr << ii->first->getName() << " -> " << ii->second->getName() << "\n";
565           );
566     Duplicate(F, LI);
567     //assume that stuff worked.  now connect the duplicated basic blocks 
568     //with the originals in such a way as to preserve ssa.  yuk!
569     for (std::set<std::pair<BasicBlock*, BasicBlock*> >::iterator ib = BackEdges.begin(),
570            ie = BackEdges.end(); ib != ie; ++ib)
571       ProcessBackEdge(ib->first, ib->second, F);
572     
573     //oh, and add the edge from the reg2mem created entry node to the duplicated second node
574     TerminatorInst* T = F.getEntryBlock().getTerminator();
575     ReplaceInstWithInst(T, new BranchInst(T->getSuccessor(0),
576                                           cast<BasicBlock>(Translate(T->getSuccessor(0))),
577                                           ConstantBool::get(true)));
578     
579     //do whatever is needed now that the function is duplicated
580     c->PrepFunction(&F);
581     
582     //add entry node to choice points
583     ChoicePoints.insert(&F.getEntryBlock());
584     
585     for (std::set<BasicBlock*>::iterator ii = ChoicePoints.begin(), ie = ChoicePoints.end();
586          ii != ie; ++ii)
587       c->ProcessChoicePoint(*ii);
588     
589     ChoicePoints.clear();
590     TransCache.clear();
591     
592     return true;
593   }
594   return false;
595 }
596
597 bool ProfilerRS::doInitialization(Module &M) {
598   switch (RandomMethod) {
599   case GBV:
600     c = new GlobalRandomCounter(M, Type::UIntTy, (1 << 14) - 1);
601     break;
602   case GBVO:
603     c = new GlobalRandomCounterOpt(M, Type::UIntTy, (1 << 14) - 1);
604     break;
605   case HOSTCC:
606     c = new CycleCounter(M, (1 << 14) - 1);
607     break;
608   };
609   return true;
610 }
611
612 void ProfilerRS::getAnalysisUsage(AnalysisUsage &AU) const {
613   AU.addRequired<RSProfilers>();
614   AU.addRequiredID(DemoteRegisterToMemoryID);
615 }
616
617 ///////////////////////////////////////
618 // Utilities:
619 ///////////////////////////////////////
620 static void ReplacePhiPred(BasicBlock* btarget, 
621                            BasicBlock* bold, BasicBlock* bnew) {
622   for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
623       ib != ie; ++ib)
624     if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
625       for(unsigned x = 0; x < phi->getNumIncomingValues(); ++x)
626         if(bold == phi->getIncomingBlock(x))
627           phi->setIncomingBlock(x, bnew);
628     }
629 }
630
631 static void CollapsePhi(BasicBlock* btarget, BasicBlock* bsrc) {
632   for(BasicBlock::iterator ib = btarget->begin(), ie = btarget->end();
633       ib != ie; ++ib)
634     if (PHINode* phi = dyn_cast<PHINode>(&*ib)) {
635       unsigned total = phi->getNumIncomingValues();
636       std::map<BasicBlock*, Value*> counter;
637       for(unsigned i = 0; i < phi->getNumIncomingValues(); ) {
638         if (counter[phi->getIncomingBlock(i)]) {
639           assert (phi->getIncomingValue(i) == counter[phi->getIncomingBlock(i)]);
640           phi->removeIncomingValue(i, false);
641         } else {
642           counter[phi->getIncomingBlock(i)] = phi->getIncomingValue(i);
643           ++i;
644         }
645       }
646     } 
647 }
648
649 template<class T>
650 static void recBackEdge(BasicBlock* bb, T& BackEdges, 
651                         std::map<BasicBlock*, int>& color,
652                         std::map<BasicBlock*, int>& depth,
653                         std::map<BasicBlock*, int>& finish,
654                         int& time)
655 {
656   color[bb] = 1;
657   ++time;
658   depth[bb] = time;
659   TerminatorInst* t= bb->getTerminator();
660   for(unsigned i = 0; i < t->getNumSuccessors(); ++i) {
661     BasicBlock* bbnew = t->getSuccessor(i);
662     if (color[bbnew] == 0)
663       recBackEdge(bbnew, BackEdges, color, depth, finish, time);
664     else if (color[bbnew] == 1) {
665       BackEdges.insert(std::make_pair(bb, bbnew));
666       //NumBackEdges++;
667     }
668   }
669   color[bb] = 2;
670   ++time;
671   finish[bb] = time;
672 }
673
674
675
676 //find the back edges and where they go to
677 template<class T>
678 static void getBackEdges(Function& F, T& BackEdges) {
679   std::map<BasicBlock*, int> color;
680   std::map<BasicBlock*, int> depth;
681   std::map<BasicBlock*, int> finish;
682   int time = 0;
683   recBackEdge(&F.getEntryBlock(), BackEdges, color, depth, finish, time);
684   DEBUG(std::cerr << F.getName() << " " << BackEdges.size() << "\n");
685 }
686
687
688 //Creation functions
689 ModulePass* llvm::createBlockProfilerRSPass() {
690   return new BlockProfilerRS();
691 }
692
693 ModulePass* llvm::createFunctionProfilerRSPass() {
694   return new FunctionProfilerRS();
695 }
696
697 ModulePass* llvm::createNullProfilerRSPass() {
698   return new NullProfilerRS();
699 }
700
701 FunctionPass* llvm::createRSProfilingPass() {
702   return new ProfilerRS();
703 }