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