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