The llvm_gcda_increment_indirect_counter function writes to the arguments that
[oota-llvm.git] / lib / Transforms / Instrumentation / GCOVProfiling.cpp
1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2 //
3 //                      The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass implements GCOV-style profiling. When this pass is run it emits
11 // "gcno" files next to the existing source, and instruments the code that runs
12 // to records the edges between blocks that run and emit a complementary "gcda"
13 // file on exit.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "insert-gcov-profiling"
18
19 #include "ProfilingUtils.h"
20 #include "llvm/Transforms/Instrumentation.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/DebugLoc.h"
28 #include "llvm/Support/InstIterator.h"
29 #include "llvm/Support/IRBuilder.h"
30 #include "llvm/Support/PathV2.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/ADT/UniqueVector.h"
37 #include <string>
38 #include <utility>
39 using namespace llvm;
40
41 namespace {
42   class GCOVProfiler : public ModulePass {
43   public:
44     static char ID;
45     GCOVProfiler()
46         : ModulePass(ID), EmitNotes(true), EmitData(true), Use402Format(false),
47           UseExtraChecksum(false) {
48       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
49     }
50     GCOVProfiler(bool EmitNotes, bool EmitData, bool use402Format = false,
51                  bool useExtraChecksum = false)
52         : ModulePass(ID), EmitNotes(EmitNotes), EmitData(EmitData),
53           Use402Format(use402Format), UseExtraChecksum(useExtraChecksum) {
54       assert((EmitNotes || EmitData) && "GCOVProfiler asked to do nothing?");
55       initializeGCOVProfilerPass(*PassRegistry::getPassRegistry());
56     }
57     virtual const char *getPassName() const {
58       return "GCOV Profiler";
59     }
60
61   private:
62     bool runOnModule(Module &M);
63
64     // Create the GCNO files for the Module based on DebugInfo.
65     void emitGCNO();
66
67     // Modify the program to track transitions along edges and call into the
68     // profiling runtime to emit .gcda files when run.
69     bool emitProfileArcs();
70
71     // Get pointers to the functions in the runtime library.
72     Constant *getStartFileFunc();
73     void incrementIndirectCounter(IRBuilder<> &Builder, BasicBlock *Exit,
74                                   GlobalVariable *EdgeState,
75                                   Value *CounterPtrArray);
76     Constant *getEmitFunctionFunc();
77     Constant *getEmitArcsFunc();
78     Constant *getEndFileFunc();
79
80     // Create or retrieve an i32 state value that is used to represent the
81     // pred block number for certain non-trivial edges.
82     GlobalVariable *getEdgeStateValue();
83
84     // Produce a table of pointers to counters, by predecessor and successor
85     // block number.
86     GlobalVariable *buildEdgeLookupTable(Function *F,
87                                          GlobalVariable *Counter,
88                                          const UniqueVector<BasicBlock *> &Preds,
89                                          const UniqueVector<BasicBlock *> &Succs);
90
91     // Add the function to write out all our counters to the global destructor
92     // list.
93     void insertCounterWriteout(SmallVector<std::pair<GlobalVariable *,
94                                                      MDNode *>, 8> &);
95
96     std::string mangleName(DICompileUnit CU, std::string NewStem);
97
98     bool EmitNotes;
99     bool EmitData;
100     bool Use402Format;
101     bool UseExtraChecksum;
102
103     Module *M;
104     LLVMContext *Ctx;
105   };
106 }
107
108 char GCOVProfiler::ID = 0;
109 INITIALIZE_PASS(GCOVProfiler, "insert-gcov-profiling",
110                 "Insert instrumentation for GCOV profiling", false, false)
111
112 ModulePass *llvm::createGCOVProfilerPass(bool EmitNotes, bool EmitData,
113                                          bool Use402Format,
114                                          bool UseExtraChecksum) {
115   return new GCOVProfiler(EmitNotes, EmitData, Use402Format, UseExtraChecksum);
116 }
117
118 namespace {
119   class GCOVRecord {
120    protected:
121     static const char *LinesTag;
122     static const char *FunctionTag;
123     static const char *BlockTag;
124     static const char *EdgeTag;
125
126     GCOVRecord() {}
127
128     void writeBytes(const char *Bytes, int Size) {
129       os->write(Bytes, Size);
130     }
131
132     void write(uint32_t i) {
133       writeBytes(reinterpret_cast<char*>(&i), 4);
134     }
135
136     // Returns the length measured in 4-byte blocks that will be used to
137     // represent this string in a GCOV file
138     unsigned lengthOfGCOVString(StringRef s) {
139       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
140       // padding out to the next 4-byte word. The length is measured in 4-byte
141       // words including padding, not bytes of actual string.
142       return (s.size() / 4) + 1;
143     }
144
145     void writeGCOVString(StringRef s) {
146       uint32_t Len = lengthOfGCOVString(s);
147       write(Len);
148       writeBytes(s.data(), s.size());
149
150       // Write 1 to 4 bytes of NUL padding.
151       assert((unsigned)(4 - (s.size() % 4)) > 0);
152       assert((unsigned)(4 - (s.size() % 4)) <= 4);
153       writeBytes("\0\0\0\0", 4 - (s.size() % 4));
154     }
155
156     raw_ostream *os;
157   };
158   const char *GCOVRecord::LinesTag = "\0\0\x45\x01";
159   const char *GCOVRecord::FunctionTag = "\0\0\0\1";
160   const char *GCOVRecord::BlockTag = "\0\0\x41\x01";
161   const char *GCOVRecord::EdgeTag = "\0\0\x43\x01";
162
163   class GCOVFunction;
164   class GCOVBlock;
165
166   // Constructed only by requesting it from a GCOVBlock, this object stores a
167   // list of line numbers and a single filename, representing lines that belong
168   // to the block.
169   class GCOVLines : public GCOVRecord {
170    public:
171     void addLine(uint32_t Line) {
172       Lines.push_back(Line);
173     }
174
175     uint32_t length() {
176       // Here 2 = 1 for string length + 1 for '0' id#.
177       return lengthOfGCOVString(Filename) + 2 + Lines.size();
178     }
179
180     void writeOut() {
181       write(0);
182       writeGCOVString(Filename);
183       for (int i = 0, e = Lines.size(); i != e; ++i)
184         write(Lines[i]);
185     }
186
187     GCOVLines(StringRef F, raw_ostream *os) 
188       : Filename(F) {
189       this->os = os;
190     }
191
192    private:
193     StringRef Filename;
194     SmallVector<uint32_t, 32> Lines;
195   };
196
197   // Represent a basic block in GCOV. Each block has a unique number in the
198   // function, number of lines belonging to each block, and a set of edges to
199   // other blocks.
200   class GCOVBlock : public GCOVRecord {
201    public:
202     GCOVLines &getFile(StringRef Filename) {
203       GCOVLines *&Lines = LinesByFile[Filename];
204       if (!Lines) {
205         Lines = new GCOVLines(Filename, os);
206       }
207       return *Lines;
208     }
209
210     void addEdge(GCOVBlock &Successor) {
211       OutEdges.push_back(&Successor);
212     }
213
214     void writeOut() {
215       uint32_t Len = 3;
216       for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
217                E = LinesByFile.end(); I != E; ++I) {
218         Len += I->second->length();
219       }
220
221       writeBytes(LinesTag, 4);
222       write(Len);
223       write(Number);
224       for (StringMap<GCOVLines *>::iterator I = LinesByFile.begin(),
225                E = LinesByFile.end(); I != E; ++I) 
226         I->second->writeOut();
227       write(0);
228       write(0);
229     }
230
231     ~GCOVBlock() {
232       DeleteContainerSeconds(LinesByFile);
233     }
234
235    private:
236     friend class GCOVFunction;
237
238     GCOVBlock(uint32_t Number, raw_ostream *os)
239         : Number(Number) {
240       this->os = os;
241     }
242
243     uint32_t Number;
244     StringMap<GCOVLines *> LinesByFile;
245     SmallVector<GCOVBlock *, 4> OutEdges;
246   };
247
248   // A function has a unique identifier, a checksum (we leave as zero) and a
249   // set of blocks and a map of edges between blocks. This is the only GCOV
250   // object users can construct, the blocks and lines will be rooted here.
251   class GCOVFunction : public GCOVRecord {
252    public:
253     GCOVFunction(DISubprogram SP, raw_ostream *os,
254                  bool Use402Format, bool UseExtraChecksum) {
255       this->os = os;
256
257       Function *F = SP.getFunction();
258       DEBUG(dbgs() << "Function: " << F->getName() << "\n");
259       uint32_t i = 0;
260       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
261         Blocks[BB] = new GCOVBlock(i++, os);
262       }
263       ReturnBlock = new GCOVBlock(i++, os);
264
265       writeBytes(FunctionTag, 4);
266       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
267           1 + lengthOfGCOVString(SP.getFilename()) + 1;
268       if (UseExtraChecksum)
269         ++BlockLen;
270       write(BlockLen);
271       uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
272       write(Ident);
273       write(0);  // lineno checksum
274       if (UseExtraChecksum)
275         write(0);  // cfg checksum
276       writeGCOVString(SP.getName());
277       writeGCOVString(SP.getFilename());
278       write(SP.getLineNumber());
279     }
280
281     ~GCOVFunction() {
282       DeleteContainerSeconds(Blocks);
283       delete ReturnBlock;
284     }
285
286     GCOVBlock &getBlock(BasicBlock *BB) {
287       return *Blocks[BB];
288     }
289
290     GCOVBlock &getReturnBlock() {
291       return *ReturnBlock;
292     }
293
294     void writeOut() {
295       // Emit count of blocks.
296       writeBytes(BlockTag, 4);
297       write(Blocks.size() + 1);
298       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
299         write(0);  // No flags on our blocks.
300       }
301       DEBUG(dbgs() << Blocks.size() << " blocks.\n");
302
303       // Emit edges between blocks.
304       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
305                E = Blocks.end(); I != E; ++I) {
306         GCOVBlock &Block = *I->second;
307         if (Block.OutEdges.empty()) continue;
308
309         writeBytes(EdgeTag, 4);
310         write(Block.OutEdges.size() * 2 + 1);
311         write(Block.Number);
312         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
313           DEBUG(dbgs() << Block.Number << " -> " << Block.OutEdges[i]->Number
314                        << "\n");
315           write(Block.OutEdges[i]->Number);
316           write(0);  // no flags
317         }
318       }
319
320       // Emit lines for each block.
321       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
322                E = Blocks.end(); I != E; ++I) {
323         I->second->writeOut();
324       }
325     }
326
327    private:
328     DenseMap<BasicBlock *, GCOVBlock *> Blocks;
329     GCOVBlock *ReturnBlock;
330   };
331 }
332
333 std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
334   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
335     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
336       MDNode *N = GCov->getOperand(i);
337       if (N->getNumOperands() != 2) continue;
338       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
339       MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
340       if (!GCovFile || !CompileUnit) continue;
341       if (CompileUnit == CU) {
342         SmallString<128> Filename = GCovFile->getString();
343         sys::path::replace_extension(Filename, NewStem);
344         return Filename.str();
345       }
346     }
347   }
348
349   SmallString<128> Filename = CU.getFilename();
350   sys::path::replace_extension(Filename, NewStem);
351   return sys::path::filename(Filename.str());
352 }
353
354 bool GCOVProfiler::runOnModule(Module &M) {
355   this->M = &M;
356   Ctx = &M.getContext();
357
358   if (EmitNotes) emitGCNO();
359   if (EmitData) return emitProfileArcs();
360   return false;
361 }
362
363 void GCOVProfiler::emitGCNO() {
364   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
365   if (!CU_Nodes) return;
366
367   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
368     // Each compile unit gets its own .gcno file. This means that whether we run
369     // this pass over the original .o's as they're produced, or run it after
370     // LTO, we'll generate the same .gcno files.
371
372     DICompileUnit CU(CU_Nodes->getOperand(i));
373     std::string ErrorInfo;
374     raw_fd_ostream out(mangleName(CU, "gcno").c_str(), ErrorInfo,
375                        raw_fd_ostream::F_Binary);
376     if (!Use402Format)
377       out.write("oncg*404MVLL", 12);
378     else
379       out.write("oncg*204MVLL", 12);
380
381     DIArray SPs = CU.getSubprograms();
382     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
383       DISubprogram SP(SPs.getElement(i));
384       if (!SP.Verify()) continue;
385
386       Function *F = SP.getFunction();
387       if (!F) continue;
388       GCOVFunction Func(SP, &out, Use402Format, UseExtraChecksum);
389
390       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
391         GCOVBlock &Block = Func.getBlock(BB);
392         TerminatorInst *TI = BB->getTerminator();
393         if (int successors = TI->getNumSuccessors()) {
394           for (int i = 0; i != successors; ++i) {
395             Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
396           }
397         } else if (isa<ReturnInst>(TI)) {
398           Block.addEdge(Func.getReturnBlock());
399         }
400
401         uint32_t Line = 0;
402         for (BasicBlock::iterator I = BB->begin(), IE = BB->end();
403              I != IE; ++I) {
404           const DebugLoc &Loc = I->getDebugLoc();
405           if (Loc.isUnknown()) continue;
406           if (Line == Loc.getLine()) continue;
407           Line = Loc.getLine();
408           if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
409
410           GCOVLines &Lines = Block.getFile(SP.getFilename());
411           Lines.addLine(Loc.getLine());
412         }
413       }
414       Func.writeOut();
415     }
416     out.write("\0\0\0\0\0\0\0\0", 8);  // EOF
417     out.close();
418   }
419 }
420
421 bool GCOVProfiler::emitProfileArcs() {
422   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
423   if (!CU_Nodes) return false;
424
425   bool Result = false;  
426   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
427     DICompileUnit CU(CU_Nodes->getOperand(i));
428     DIArray SPs = CU.getSubprograms();
429     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
430     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
431       DISubprogram SP(SPs.getElement(i));
432       if (!SP.Verify()) continue;
433       Function *F = SP.getFunction();
434       if (!F) continue;
435       if (!Result) Result = true;
436       unsigned Edges = 0;
437       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
438         TerminatorInst *TI = BB->getTerminator();
439         if (isa<ReturnInst>(TI))
440           ++Edges;
441         else
442           Edges += TI->getNumSuccessors();
443       }
444       
445       ArrayType *CounterTy =
446         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
447       GlobalVariable *Counters =
448         new GlobalVariable(*M, CounterTy, false,
449                            GlobalValue::InternalLinkage,
450                            Constant::getNullValue(CounterTy),
451                            "__llvm_gcov_ctr", 0, false, 0);
452       CountersBySP.push_back(std::make_pair(Counters, (MDNode*)SP));
453       
454       UniqueVector<BasicBlock *> ComplexEdgePreds;
455       UniqueVector<BasicBlock *> ComplexEdgeSuccs;
456       
457       unsigned Edge = 0;
458       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
459         TerminatorInst *TI = BB->getTerminator();
460         int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
461         if (Successors) {
462           IRBuilder<> Builder(TI);
463           
464           if (Successors == 1) {
465             Value *Counter = Builder.CreateConstInBoundsGEP2_64(Counters, 0,
466                                                                 Edge);
467             Value *Count = Builder.CreateLoad(Counter);
468             Count = Builder.CreateAdd(Count,
469                                       ConstantInt::get(Type::getInt64Ty(*Ctx),1));
470             Builder.CreateStore(Count, Counter);
471           } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
472             Value *Sel = Builder.CreateSelect(
473               BI->getCondition(),
474               ConstantInt::get(Type::getInt64Ty(*Ctx), Edge),
475               ConstantInt::get(Type::getInt64Ty(*Ctx), Edge + 1));
476             SmallVector<Value *, 2> Idx;
477             Idx.push_back(Constant::getNullValue(Type::getInt64Ty(*Ctx)));
478             Idx.push_back(Sel);
479             Value *Counter = Builder.CreateInBoundsGEP(Counters, Idx);
480             Value *Count = Builder.CreateLoad(Counter);
481             Count = Builder.CreateAdd(Count,
482                                       ConstantInt::get(Type::getInt64Ty(*Ctx),1));
483             Builder.CreateStore(Count, Counter);
484           } else {
485             ComplexEdgePreds.insert(BB);
486             for (int i = 0; i != Successors; ++i)
487               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
488           }
489           Edge += Successors;
490         }
491       }
492       
493       if (!ComplexEdgePreds.empty()) {
494         GlobalVariable *EdgeTable =
495           buildEdgeLookupTable(F, Counters,
496                                ComplexEdgePreds, ComplexEdgeSuccs);
497         GlobalVariable *EdgeState = getEdgeStateValue();
498         
499         Type *Int32Ty = Type::getInt32Ty(*Ctx);
500         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
501           IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
502           Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
503         }
504         for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
505           // call runtime to perform increment
506           BasicBlock *BB = ComplexEdgeSuccs[i+1];
507           BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
508           BasicBlock *Split = BB->splitBasicBlock(InsertPt);
509           InsertPt = BB->getFirstInsertionPt();
510           IRBuilder<> Builder(InsertPt);
511           Value *CounterPtrArray =
512             Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
513                                                i * ComplexEdgePreds.size());
514
515           // Build code to increment the counter.
516           incrementIndirectCounter(Builder, Split, EdgeState, CounterPtrArray);
517         }
518       }
519     }
520     insertCounterWriteout(CountersBySP);
521   }
522   return Result;
523 }
524
525 // All edges with successors that aren't branches are "complex", because it
526 // requires complex logic to pick which counter to update.
527 GlobalVariable *GCOVProfiler::buildEdgeLookupTable(
528     Function *F,
529     GlobalVariable *Counters,
530     const UniqueVector<BasicBlock *> &Preds,
531     const UniqueVector<BasicBlock *> &Succs) {
532   // TODO: support invoke, threads. We rely on the fact that nothing can modify
533   // the whole-Module pred edge# between the time we set it and the time we next
534   // read it. Threads and invoke make this untrue.
535
536   // emit [(succs * preds) x i64*], logically [succ x [pred x i64*]].
537   Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
538   ArrayType *EdgeTableTy = ArrayType::get(
539       Int64PtrTy, Succs.size() * Preds.size());
540
541   Constant **EdgeTable = new Constant*[Succs.size() * Preds.size()];
542   Constant *NullValue = Constant::getNullValue(Int64PtrTy);
543   for (int i = 0, ie = Succs.size() * Preds.size(); i != ie; ++i)
544     EdgeTable[i] = NullValue;
545
546   unsigned Edge = 0;
547   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
548     TerminatorInst *TI = BB->getTerminator();
549     int Successors = isa<ReturnInst>(TI) ? 1 : TI->getNumSuccessors();
550     if (Successors > 1 && !isa<BranchInst>(TI) && !isa<ReturnInst>(TI)) {
551       for (int i = 0; i != Successors; ++i) {
552         BasicBlock *Succ = TI->getSuccessor(i);
553         IRBuilder<> builder(Succ);
554         Value *Counter = builder.CreateConstInBoundsGEP2_64(Counters, 0,
555                                                             Edge + i);
556         EdgeTable[((Succs.idFor(Succ)-1) * Preds.size()) +
557                   (Preds.idFor(BB)-1)] = cast<Constant>(Counter);
558       }
559     }
560     Edge += Successors;
561   }
562
563   ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
564   GlobalVariable *EdgeTableGV =
565       new GlobalVariable(
566           *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
567           ConstantArray::get(EdgeTableTy, V),
568           "__llvm_gcda_edge_table");
569   EdgeTableGV->setUnnamedAddr(true);
570   return EdgeTableGV;
571 }
572
573 Constant *GCOVProfiler::getStartFileFunc() {
574   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
575                                               Type::getInt8PtrTy(*Ctx), false);
576   return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
577 }
578
579 /// incrementIndirectCounter - Emit code that increments the indirect
580 /// counter. The code is meant to copy the llvm_gcda_increment_indirect_counter
581 /// function, but because it's inlined into the function, we don't have to worry
582 /// about the runtime library possibly writing into a protected area.
583 void GCOVProfiler::incrementIndirectCounter(IRBuilder<> &Builder,
584                                             BasicBlock *Exit,
585                                             GlobalVariable *EdgeState,
586                                             Value *CounterPtrArray) {
587   Type *Int64Ty = Type::getInt64Ty(*Ctx);
588   ConstantInt *NegOne = ConstantInt::get(Type::getInt32Ty(*Ctx), 0xffffffff);
589
590   // Create exiting blocks.
591   BasicBlock *InsBB = Builder.GetInsertBlock();
592   Function *Fn = InsBB->getParent();
593   BasicBlock *PredNotNegOne = BasicBlock::Create(*Ctx, "", Fn, Exit);
594   BasicBlock *CounterEnd = BasicBlock::Create(*Ctx, "", Fn, Exit);
595
596   // uint32_t pred = *EdgeState;
597   // if (pred == 0xffffffff) return;
598   Value *Pred = Builder.CreateLoad(EdgeState, "predecessor");
599   Value *Cond = Builder.CreateICmpEQ(Pred, NegOne);
600   InsBB->getTerminator()->eraseFromParent();
601   BranchInst::Create(Exit, PredNotNegOne, Cond, InsBB);
602
603   Builder.SetInsertPoint(PredNotNegOne);
604
605   // uint64_t *counter = CounterPtrArray[pred];
606   // if (!counter) return;
607   Value *ZExtPred = Builder.CreateZExt(Pred, Int64Ty);
608   Value *GEP = Builder.CreateGEP(CounterPtrArray, ZExtPred);
609   Value *Counter = Builder.CreateLoad(GEP, "counter");
610   Cond = Builder.CreateICmpEQ(Counter,
611                               Constant::getNullValue(Type::getInt64PtrTy(*Ctx, 0)));
612   Builder.CreateCondBr(Cond, Exit, CounterEnd);
613
614   Builder.SetInsertPoint(CounterEnd);
615
616   // ++*counter;
617   Value *Add = Builder.CreateAdd(Builder.CreateLoad(Counter),
618                                  ConstantInt::get(Int64Ty, 1));
619   Builder.CreateStore(Add, Counter);
620   Builder.CreateBr(Exit);
621
622   // Clear the predecessor number
623   Builder.SetInsertPoint(Exit->getFirstInsertionPt());
624   Builder.CreateStore(NegOne, EdgeState);
625 }
626
627 Constant *GCOVProfiler::getEmitFunctionFunc() {
628   Type *Args[2] = {
629     Type::getInt32Ty(*Ctx),    // uint32_t ident
630     Type::getInt8PtrTy(*Ctx),  // const char *function_name
631   };
632   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
633   return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
634 }
635
636 Constant *GCOVProfiler::getEmitArcsFunc() {
637   Type *Args[] = {
638     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
639     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
640   };
641   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
642                                               Args, false);
643   return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
644 }
645
646 Constant *GCOVProfiler::getEndFileFunc() {
647   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
648   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
649 }
650
651 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
652   GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
653   if (!GV) {
654     GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
655                             GlobalValue::InternalLinkage,
656                             ConstantInt::get(Type::getInt32Ty(*Ctx),
657                                              0xffffffff),
658                             "__llvm_gcov_global_state_pred");
659     GV->setUnnamedAddr(true);
660   }
661   return GV;
662 }
663
664 void GCOVProfiler::insertCounterWriteout(
665     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> &CountersBySP) {
666   FunctionType *WriteoutFTy =
667       FunctionType::get(Type::getVoidTy(*Ctx), false);
668   Function *WriteoutF = Function::Create(WriteoutFTy,
669                                          GlobalValue::InternalLinkage,
670                                          "__llvm_gcov_writeout", M);
671   WriteoutF->setUnnamedAddr(true);
672   BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
673   IRBuilder<> Builder(BB);
674
675   Constant *StartFile = getStartFileFunc();
676   Constant *EmitFunction = getEmitFunctionFunc();
677   Constant *EmitArcs = getEmitArcsFunc();
678   Constant *EndFile = getEndFileFunc();
679
680   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
681   if (CU_Nodes) {
682     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
683       DICompileUnit compile_unit(CU_Nodes->getOperand(i));
684       std::string FilenameGcda = mangleName(compile_unit, "gcda");
685       Builder.CreateCall(StartFile,
686                          Builder.CreateGlobalStringPtr(FilenameGcda));
687       for (SmallVector<std::pair<GlobalVariable *, MDNode *>, 8>::iterator
688              I = CountersBySP.begin(), E = CountersBySP.end();
689            I != E; ++I) {
690         DISubprogram SP(I->second);
691         intptr_t ident = reinterpret_cast<intptr_t>(I->second);
692         Builder.CreateCall2(EmitFunction,
693                             ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
694                             Builder.CreateGlobalStringPtr(SP.getName()));
695         
696         GlobalVariable *GV = I->first;
697         unsigned Arcs =
698           cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
699         Builder.CreateCall2(EmitArcs,
700                             ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
701                             Builder.CreateConstGEP2_64(GV, 0, 0));
702       }
703       Builder.CreateCall(EndFile);
704     }
705   }
706   Builder.CreateRetVoid();
707
708   InsertProfilingShutdownCall(WriteoutF, M);
709 }