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