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