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