Update GCOVLines to provide interfaces to write line table and calculate complete...
[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 and a single filename, representing lines that belong
162   // to the block.
163   class GCOVLines : public GCOVRecord {
164    public:
165     void addLine(uint32_t Line) {
166       Lines.push_back(Line);
167     }
168
169     uint32_t length() {
170       // Here 2 = 1 for string lenght + 1 for '0' id#.
171       return lengthOfGCOVString(Filename) + 2 + Lines.size();
172     }
173
174     void writeOut() {
175       write(0);
176       writeGCOVString(Filename);
177       for (int i = 0, e = Lines.size(); i != e; ++i)
178         write(Lines[i]);
179     }
180    private:
181     friend class GCOVBlock;
182
183     GCOVLines(StringRef F, raw_ostream *os) 
184       : Filename(F) {
185       this->os = os;
186     }
187
188     StringRef 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(StringRef 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         I->second->writeOut();
222       write(0);
223       write(0);
224     }
225
226     ~GCOVBlock() {
227       DeleteContainerSeconds(LinesByFile);
228     }
229
230    private:
231     friend class GCOVFunction;
232
233     GCOVBlock(uint32_t Number, raw_ostream *os)
234         : Number(Number) {
235       this->os = os;
236     }
237
238     uint32_t Number;
239     StringMap<GCOVLines *> LinesByFile;
240     SmallVector<GCOVBlock *, 4> OutEdges;
241   };
242
243   // A function has a unique identifier, a checksum (we leave as zero) and a
244   // set of blocks and a map of edges between blocks. This is the only GCOV
245   // object users can construct, the blocks and lines will be rooted here.
246   class GCOVFunction : public GCOVRecord {
247    public:
248     GCOVFunction(DISubprogram SP, raw_ostream *os, bool Use402Format) {
249       this->os = os;
250
251       Function *F = SP.getFunction();
252       uint32_t i = 0;
253       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
254         Blocks[BB] = new GCOVBlock(i++, os);
255       }
256       ReturnBlock = new GCOVBlock(i++, os);
257
258       writeBytes(FunctionTag, 4);
259       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(SP.getName()) +
260           1 + lengthOfGCOVString(SP.getFilename()) + 1;
261       if (!Use402Format)
262         ++BlockLen; // For second checksum.
263       write(BlockLen);
264       uint32_t Ident = reinterpret_cast<intptr_t>((MDNode*)SP);
265       write(Ident);
266       write(0);  // checksum #1
267       if (!Use402Format)
268         write(0);  // checksum #2
269       writeGCOVString(SP.getName());
270       writeGCOVString(SP.getFilename());
271       write(SP.getLineNumber());
272     }
273
274     ~GCOVFunction() {
275       DeleteContainerSeconds(Blocks);
276       delete ReturnBlock;
277     }
278
279     GCOVBlock &getBlock(BasicBlock *BB) {
280       return *Blocks[BB];
281     }
282
283     GCOVBlock &getReturnBlock() {
284       return *ReturnBlock;
285     }
286
287     void writeOut() {
288       // Emit count of blocks.
289       writeBytes(BlockTag, 4);
290       write(Blocks.size() + 1);
291       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
292         write(0);  // No flags on our blocks.
293       }
294
295       // Emit edges between blocks.
296       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
297                E = Blocks.end(); I != E; ++I) {
298         GCOVBlock &Block = *I->second;
299         if (Block.OutEdges.empty()) continue;
300
301         writeBytes(EdgeTag, 4);
302         write(Block.OutEdges.size() * 2 + 1);
303         write(Block.Number);
304         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
305           write(Block.OutEdges[i]->Number);
306           write(0);  // no flags
307         }
308       }
309
310       // Emit lines for each block.
311       for (DenseMap<BasicBlock *, GCOVBlock *>::iterator I = Blocks.begin(),
312                E = Blocks.end(); I != E; ++I) {
313         I->second->writeOut();
314       }
315     }
316
317    private:
318     DenseMap<BasicBlock *, GCOVBlock *> Blocks;
319     GCOVBlock *ReturnBlock;
320   };
321 }
322
323 std::string GCOVProfiler::mangleName(DICompileUnit CU, std::string NewStem) {
324   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
325     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
326       MDNode *N = GCov->getOperand(i);
327       if (N->getNumOperands() != 2) continue;
328       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
329       MDNode *CompileUnit = dyn_cast<MDNode>(N->getOperand(1));
330       if (!GCovFile || !CompileUnit) continue;
331       if (CompileUnit == CU) {
332         SmallString<128> Filename = GCovFile->getString();
333         sys::path::replace_extension(Filename, NewStem);
334         return Filename.str();
335       }
336     }
337   }
338
339   SmallString<128> Filename = CU.getFilename();
340   sys::path::replace_extension(Filename, NewStem);
341   return sys::path::filename(Filename.str());
342 }
343
344 bool GCOVProfiler::runOnModule(Module &M) {
345   this->M = &M;
346   Ctx = &M.getContext();
347
348   if (EmitNotes) emitGCNO();
349   if (EmitData) return emitProfileArcs();
350   return false;
351 }
352
353 void GCOVProfiler::emitGCNO() {
354   DenseMap<const MDNode *, raw_fd_ostream *> GcnoFiles;
355   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
356   if (CU_Nodes) {
357     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
358       // Each compile unit gets its own .gcno file. This means that whether we run
359       // this pass over the original .o's as they're produced, or run it after
360       // LTO, we'll generate the same .gcno files.
361       
362       DICompileUnit CU(CU_Nodes->getOperand(i));
363       raw_fd_ostream *&out = GcnoFiles[CU];
364       std::string ErrorInfo;
365       out = new raw_fd_ostream(mangleName(CU, "gcno").c_str(), ErrorInfo,
366                                raw_fd_ostream::F_Binary);
367       if (!Use402Format)
368         out->write("oncg*404MVLL", 12);
369       else
370         out->write("oncg*204MVLL", 12);
371   
372       DIArray SPs = CU.getSubprograms();
373       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
374         DISubprogram SP(SPs.getElement(i));
375         if (!SP.Verify()) continue;
376         raw_fd_ostream *&os = GcnoFiles[CU];
377         
378         Function *F = SP.getFunction();
379         if (!F) continue;
380         GCOVFunction Func(SP, os, Use402Format);
381         
382         for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
383           GCOVBlock &Block = Func.getBlock(BB);
384           TerminatorInst *TI = BB->getTerminator();
385           if (int successors = TI->getNumSuccessors()) {
386             for (int i = 0; i != successors; ++i) {
387               Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
388             }
389           } else if (isa<ReturnInst>(TI)) {
390             Block.addEdge(Func.getReturnBlock());
391           }
392           
393           uint32_t Line = 0;
394           for (BasicBlock::iterator I = BB->begin(), IE = BB->end(); I != IE; ++I) {
395             const DebugLoc &Loc = I->getDebugLoc();
396             if (Loc.isUnknown()) continue;
397             if (Line == Loc.getLine()) continue;
398             Line = Loc.getLine();
399             if (SP != getDISubprogram(Loc.getScope(*Ctx))) continue;
400             
401             GCOVLines &Lines = Block.getFile(SP.getFilename());
402             Lines.addLine(Loc.getLine());
403           }
404         }
405         Func.writeOut();
406       }
407     }
408   }
409
410   for (DenseMap<const MDNode *, raw_fd_ostream *>::iterator
411            I = GcnoFiles.begin(), E = GcnoFiles.end(); I != E; ++I) {
412     raw_fd_ostream *&out = I->second;
413     out->write("\0\0\0\0\0\0\0\0", 8);  // EOF
414     out->close();
415     delete out;
416   }
417 }
418
419 bool GCOVProfiler::emitProfileArcs() {
420   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
421   if (!CU_Nodes) return false;
422
423   bool Result = false;  
424   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
425     DICompileUnit CU(CU_Nodes->getOperand(i));
426     DIArray SPs = CU.getSubprograms();
427     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
428     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
429       DISubprogram SP(SPs.getElement(i));
430       if (!SP.Verify()) continue;
431       Function *F = SP.getFunction();
432       if (!F) continue;
433       if (!Result) Result = true;
434       unsigned Edges = 0;
435       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
436         TerminatorInst *TI = BB->getTerminator();
437         if (isa<ReturnInst>(TI))
438           ++Edges;
439         else
440           Edges += TI->getNumSuccessors();
441       }
442       
443       ArrayType *CounterTy =
444         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
445       GlobalVariable *Counters =
446         new GlobalVariable(*M, CounterTy, false,
447                            GlobalValue::InternalLinkage,
448                            Constant::getNullValue(CounterTy),
449                            "__llvm_gcov_ctr", 0, false, 0);
450       CountersBySP.push_back(std::make_pair(Counters, (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, Idx);
478             Value *Count = Builder.CreateLoad(Counter);
479             Count = Builder.CreateAdd(Count,
480                                       ConstantInt::get(Type::getInt64Ty(*Ctx),1));
481             Builder.CreateStore(Count, Counter);
482           } else {
483             ComplexEdgePreds.insert(BB);
484             for (int i = 0; i != Successors; ++i)
485               ComplexEdgeSuccs.insert(TI->getSuccessor(i));
486           }
487           Edge += Successors;
488         }
489       }
490       
491       if (!ComplexEdgePreds.empty()) {
492         GlobalVariable *EdgeTable =
493           buildEdgeLookupTable(F, Counters,
494                                ComplexEdgePreds, ComplexEdgeSuccs);
495         GlobalVariable *EdgeState = getEdgeStateValue();
496         
497         Type *Int32Ty = Type::getInt32Ty(*Ctx);
498         for (int i = 0, e = ComplexEdgePreds.size(); i != e; ++i) {
499           IRBuilder<> Builder(ComplexEdgePreds[i+1]->getTerminator());
500           Builder.CreateStore(ConstantInt::get(Int32Ty, i), EdgeState);
501         }
502         for (int i = 0, e = ComplexEdgeSuccs.size(); i != e; ++i) {
503           // call runtime to perform increment
504           BasicBlock::iterator InsertPt =
505             ComplexEdgeSuccs[i+1]->getFirstInsertionPt();
506           IRBuilder<> Builder(InsertPt);
507           Value *CounterPtrArray =
508             Builder.CreateConstInBoundsGEP2_64(EdgeTable, 0,
509                                                i * ComplexEdgePreds.size());
510           Builder.CreateCall2(getIncrementIndirectCounterFunc(),
511                               EdgeState, CounterPtrArray);
512           // clear the predecessor number
513           Builder.CreateStore(ConstantInt::get(Int32Ty, 0xffffffff), EdgeState);
514         }
515       }
516     }
517     insertCounterWriteout(CountersBySP);
518   }
519   return Result;
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   Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
535   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   ArrayRef<Constant*> V(&EdgeTable[0], Succs.size() * Preds.size());
561   GlobalVariable *EdgeTableGV =
562       new GlobalVariable(
563           *M, EdgeTableTy, true, GlobalValue::InternalLinkage,
564           ConstantArray::get(EdgeTableTy, V),
565           "__llvm_gcda_edge_table");
566   EdgeTableGV->setUnnamedAddr(true);
567   return EdgeTableGV;
568 }
569
570 Constant *GCOVProfiler::getStartFileFunc() {
571   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
572                                               Type::getInt8PtrTy(*Ctx), false);
573   return M->getOrInsertFunction("llvm_gcda_start_file", FTy);
574 }
575
576 Constant *GCOVProfiler::getIncrementIndirectCounterFunc() {
577   Type *Args[] = {
578     Type::getInt32PtrTy(*Ctx),                  // uint32_t *predecessor
579     Type::getInt64PtrTy(*Ctx)->getPointerTo(),  // uint64_t **state_table_row
580   };
581   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
582                                               Args, false);
583   return M->getOrInsertFunction("llvm_gcda_increment_indirect_counter", FTy);
584 }
585
586 Constant *GCOVProfiler::getEmitFunctionFunc() {
587   Type *Args[2] = {
588     Type::getInt32Ty(*Ctx),    // uint32_t ident
589     Type::getInt8PtrTy(*Ctx),  // const char *function_name
590   };
591   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
592                                               Args, false);
593   return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
594 }
595
596 Constant *GCOVProfiler::getEmitArcsFunc() {
597   Type *Args[] = {
598     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
599     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
600   };
601   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx),
602                                               Args, false);
603   return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy);
604 }
605
606 Constant *GCOVProfiler::getEndFileFunc() {
607   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
608   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
609 }
610
611 GlobalVariable *GCOVProfiler::getEdgeStateValue() {
612   GlobalVariable *GV = M->getGlobalVariable("__llvm_gcov_global_state_pred");
613   if (!GV) {
614     GV = new GlobalVariable(*M, Type::getInt32Ty(*Ctx), false,
615                             GlobalValue::InternalLinkage,
616                             ConstantInt::get(Type::getInt32Ty(*Ctx),
617                                              0xffffffff),
618                             "__llvm_gcov_global_state_pred");
619     GV->setUnnamedAddr(true);
620   }
621   return GV;
622 }
623
624 void GCOVProfiler::insertCounterWriteout(
625     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> &CountersBySP) {
626   FunctionType *WriteoutFTy =
627       FunctionType::get(Type::getVoidTy(*Ctx), false);
628   Function *WriteoutF = Function::Create(WriteoutFTy,
629                                          GlobalValue::InternalLinkage,
630                                          "__llvm_gcov_writeout", M);
631   WriteoutF->setUnnamedAddr(true);
632   BasicBlock *BB = BasicBlock::Create(*Ctx, "", WriteoutF);
633   IRBuilder<> Builder(BB);
634
635   Constant *StartFile = getStartFileFunc();
636   Constant *EmitFunction = getEmitFunctionFunc();
637   Constant *EmitArcs = getEmitArcsFunc();
638   Constant *EndFile = getEndFileFunc();
639
640   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
641   if (CU_Nodes) {
642     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
643       DICompileUnit compile_unit(CU_Nodes->getOperand(i));
644       std::string FilenameGcda = mangleName(compile_unit, "gcda");
645       Builder.CreateCall(StartFile,
646                          Builder.CreateGlobalStringPtr(FilenameGcda));
647       for (SmallVector<std::pair<GlobalVariable *, MDNode *>, 8>::iterator
648              I = CountersBySP.begin(), E = CountersBySP.end();
649            I != E; ++I) {
650         DISubprogram SP(I->second);
651         intptr_t ident = reinterpret_cast<intptr_t>(I->second);
652         Builder.CreateCall2(EmitFunction,
653                             ConstantInt::get(Type::getInt32Ty(*Ctx), ident),
654                             Builder.CreateGlobalStringPtr(SP.getName()));
655         
656         GlobalVariable *GV = I->first;
657         unsigned Arcs =
658           cast<ArrayType>(GV->getType()->getElementType())->getNumElements();
659         Builder.CreateCall2(EmitArcs,
660                             ConstantInt::get(Type::getInt32Ty(*Ctx), Arcs),
661                             Builder.CreateConstGEP2_64(GV, 0, 0));
662       }
663       Builder.CreateCall(EndFile);
664     }
665   }
666   Builder.CreateRetVoid();
667
668   InsertProfilingShutdownCall(WriteoutF, M);
669 }