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