1 //===- GCOVProfiling.cpp - Insert edge counters for gcov profiling --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements GCOV-style profiling. When this pass is run it emits
10 // "gcno" files next to the existing source, and instruments the code that runs
11 // to records the edges between blocks that run and emit a complementary "gcda"
12 // file on exit.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/Hashing.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/Sequence.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/Analysis/EHPersonalities.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/IR/CFG.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/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Regex.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Transforms/Instrumentation.h"
42 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
43 #include "llvm/Transforms/Utils/ModuleUtils.h"
44 #include <algorithm>
45 #include <memory>
46 #include <string>
47 #include <utility>
48 using namespace llvm;
49 
50 #define DEBUG_TYPE "insert-gcov-profiling"
51 
52 static cl::opt<std::string> DefaultGCOVVersion("default-gcov-version",
53                                                cl::init("408*"), cl::Hidden,
54                                                cl::ValueRequired);
55 
56 GCOVOptions GCOVOptions::getDefault() {
57   GCOVOptions Options;
58   Options.EmitNotes = true;
59   Options.EmitData = true;
60   Options.NoRedZone = false;
61 
62   if (DefaultGCOVVersion.size() != 4) {
63     llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
64                              DefaultGCOVVersion);
65   }
66   memcpy(Options.Version, DefaultGCOVVersion.c_str(), 4);
67   return Options;
68 }
69 
70 namespace {
71 class GCOVFunction;
72 
73 class GCOVProfiler {
74 public:
75   GCOVProfiler() : GCOVProfiler(GCOVOptions::getDefault()) {}
76   GCOVProfiler(const GCOVOptions &Opts) : Options(Opts) {
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   }
85   bool
86   runOnModule(Module &M,
87               std::function<const TargetLibraryInfo &(Function &F)> GetTLI);
88 
89 private:
90   // Create the .gcno files for the Module based on DebugInfo.
91   void emitProfileNotes();
92 
93   // Modify the program to track transitions along edges and call into the
94   // profiling runtime to emit .gcda files when run.
95   bool emitProfileArcs();
96 
97   bool isFunctionInstrumented(const Function &F);
98   std::vector<Regex> createRegexesFromString(StringRef RegexesStr);
99   static bool doesFilenameMatchARegex(StringRef Filename,
100                                       std::vector<Regex> &Regexes);
101 
102   // Get pointers to the functions in the runtime library.
103   FunctionCallee getStartFileFunc(const TargetLibraryInfo *TLI);
104   FunctionCallee getEmitFunctionFunc(const TargetLibraryInfo *TLI);
105   FunctionCallee getEmitArcsFunc(const TargetLibraryInfo *TLI);
106   FunctionCallee getSummaryInfoFunc();
107   FunctionCallee getEndFileFunc();
108 
109   // Add the function to write out all our counters to the global destructor
110   // list.
111   Function *
112   insertCounterWriteout(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
113   Function *insertReset(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
114   Function *insertFlush(Function *ResetF);
115 
116   void AddFlushBeforeForkAndExec();
117 
118   enum class GCovFileType { GCNO, GCDA };
119   std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
120 
121   GCOVOptions Options;
122 
123   // Reversed, NUL-terminated copy of Options.Version.
124   char ReversedVersion[5];
125   // Checksum, produced by hash of EdgeDestinations
126   SmallVector<uint32_t, 4> FileChecksums;
127 
128   Module *M = nullptr;
129   std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
130   LLVMContext *Ctx = nullptr;
131   SmallVector<std::unique_ptr<GCOVFunction>, 16> Funcs;
132   std::vector<Regex> FilterRe;
133   std::vector<Regex> ExcludeRe;
134   StringMap<bool> InstrumentedFiles;
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   StringRef getPassName() const override { return "GCOV Profiler"; }
147 
148   bool runOnModule(Module &M) override {
149     return Profiler.runOnModule(M, [this](Function &F) -> TargetLibraryInfo & {
150       return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
151     });
152   }
153 
154   void getAnalysisUsage(AnalysisUsage &AU) const override {
155     AU.addRequired<TargetLibraryInfoWrapperPass>();
156   }
157 
158 private:
159   GCOVProfiler Profiler;
160 };
161 }
162 
163 char GCOVProfilerLegacyPass::ID = 0;
164 INITIALIZE_PASS_BEGIN(
165     GCOVProfilerLegacyPass, "insert-gcov-profiling",
166     "Insert instrumentation for GCOV profiling", false, false)
167 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
168 INITIALIZE_PASS_END(
169     GCOVProfilerLegacyPass, "insert-gcov-profiling",
170     "Insert instrumentation for GCOV profiling", false, false)
171 
172 ModulePass *llvm::createGCOVProfilerPass(const GCOVOptions &Options) {
173   return new GCOVProfilerLegacyPass(Options);
174 }
175 
176 static StringRef getFunctionName(const DISubprogram *SP) {
177   if (!SP->getLinkageName().empty())
178     return SP->getLinkageName();
179   return SP->getName();
180 }
181 
182 /// Extract a filename for a DISubprogram.
183 ///
184 /// Prefer relative paths in the coverage notes. Clang also may split
185 /// up absolute paths into a directory and filename component. When
186 /// the relative path doesn't exist, reconstruct the absolute path.
187 static SmallString<128> getFilename(const DISubprogram *SP) {
188   SmallString<128> Path;
189   StringRef RelPath = SP->getFilename();
190   if (sys::fs::exists(RelPath))
191     Path = RelPath;
192   else
193     sys::path::append(Path, SP->getDirectory(), SP->getFilename());
194   return Path;
195 }
196 
197 namespace {
198   class GCOVRecord {
199    protected:
200     static const char *const LinesTag;
201     static const char *const FunctionTag;
202     static const char *const BlockTag;
203     static const char *const EdgeTag;
204 
205     GCOVRecord() = default;
206 
207     void writeBytes(const char *Bytes, int Size) {
208       os->write(Bytes, Size);
209     }
210 
211     void write(uint32_t i) {
212       writeBytes(reinterpret_cast<char*>(&i), 4);
213     }
214 
215     // Returns the length measured in 4-byte blocks that will be used to
216     // represent this string in a GCOV file
217     static unsigned lengthOfGCOVString(StringRef s) {
218       // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
219       // padding out to the next 4-byte word. The length is measured in 4-byte
220       // words including padding, not bytes of actual string.
221       return (s.size() / 4) + 1;
222     }
223 
224     void writeGCOVString(StringRef s) {
225       uint32_t Len = lengthOfGCOVString(s);
226       write(Len);
227       writeBytes(s.data(), s.size());
228 
229       // Write 1 to 4 bytes of NUL padding.
230       assert((unsigned)(4 - (s.size() % 4)) > 0);
231       assert((unsigned)(4 - (s.size() % 4)) <= 4);
232       writeBytes("\0\0\0\0", 4 - (s.size() % 4));
233     }
234 
235     raw_ostream *os;
236   };
237   const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
238   const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
239   const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
240   const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
241 
242   class GCOVFunction;
243   class GCOVBlock;
244 
245   // Constructed only by requesting it from a GCOVBlock, this object stores a
246   // list of line numbers and a single filename, representing lines that belong
247   // to the block.
248   class GCOVLines : public GCOVRecord {
249    public:
250     void addLine(uint32_t Line) {
251       assert(Line != 0 && "Line zero is not a valid real line number.");
252       Lines.push_back(Line);
253     }
254 
255     uint32_t length() const {
256       // Here 2 = 1 for string length + 1 for '0' id#.
257       return lengthOfGCOVString(Filename) + 2 + Lines.size();
258     }
259 
260     void writeOut() {
261       write(0);
262       writeGCOVString(Filename);
263       for (int i = 0, e = Lines.size(); i != e; ++i)
264         write(Lines[i]);
265     }
266 
267     GCOVLines(StringRef F, raw_ostream *os) : Filename(std::string(F)) {
268       this->os = os;
269     }
270 
271    private:
272     std::string Filename;
273     SmallVector<uint32_t, 32> Lines;
274   };
275 
276 
277   // Represent a basic block in GCOV. Each block has a unique number in the
278   // function, number of lines belonging to each block, and a set of edges to
279   // other blocks.
280   class GCOVBlock : public GCOVRecord {
281    public:
282     GCOVLines &getFile(StringRef Filename) {
283       return LinesByFile.try_emplace(Filename, Filename, os).first->second;
284     }
285 
286     void addEdge(GCOVBlock &Successor) {
287       OutEdges.push_back(&Successor);
288     }
289 
290     void writeOut() {
291       uint32_t Len = 3;
292       SmallVector<StringMapEntry<GCOVLines> *, 32> SortedLinesByFile;
293       for (auto &I : LinesByFile) {
294         Len += I.second.length();
295         SortedLinesByFile.push_back(&I);
296       }
297 
298       writeBytes(LinesTag, 4);
299       write(Len);
300       write(Number);
301 
302       llvm::sort(SortedLinesByFile, [](StringMapEntry<GCOVLines> *LHS,
303                                        StringMapEntry<GCOVLines> *RHS) {
304         return LHS->getKey() < RHS->getKey();
305       });
306       for (auto &I : SortedLinesByFile)
307         I->getValue().writeOut();
308       write(0);
309       write(0);
310     }
311 
312     GCOVBlock(const GCOVBlock &RHS) : GCOVRecord(RHS), Number(RHS.Number) {
313       // Only allow copy before edges and lines have been added. After that,
314       // there are inter-block pointers (eg: edges) that won't take kindly to
315       // blocks being copied or moved around.
316       assert(LinesByFile.empty());
317       assert(OutEdges.empty());
318     }
319 
320    private:
321     friend class GCOVFunction;
322 
323     GCOVBlock(uint32_t Number, raw_ostream *os)
324         : Number(Number) {
325       this->os = os;
326     }
327 
328     uint32_t Number;
329     StringMap<GCOVLines> LinesByFile;
330     SmallVector<GCOVBlock *, 4> OutEdges;
331   };
332 
333   // A function has a unique identifier, a checksum (we leave as zero) and a
334   // set of blocks and a map of edges between blocks. This is the only GCOV
335   // object users can construct, the blocks and lines will be rooted here.
336   class GCOVFunction : public GCOVRecord {
337    public:
338      GCOVFunction(const DISubprogram *SP, Function *F, raw_ostream *os,
339                   uint32_t Ident, bool UseCfgChecksum, bool ExitBlockBeforeBody)
340          : SP(SP), Ident(Ident), UseCfgChecksum(UseCfgChecksum), CfgChecksum(0),
341            ReturnBlock(1, os) {
342       this->os = os;
343 
344       LLVM_DEBUG(dbgs() << "Function: " << getFunctionName(SP) << "\n");
345 
346       uint32_t i = 0;
347       for (auto &BB : *F) {
348         // Skip index 1 if it's assigned to the ReturnBlock.
349         if (i == 1 && ExitBlockBeforeBody)
350           ++i;
351         Blocks.insert(std::make_pair(&BB, GCOVBlock(i++, os)));
352       }
353       if (!ExitBlockBeforeBody)
354         ReturnBlock.Number = i;
355 
356       std::string FunctionNameAndLine;
357       raw_string_ostream FNLOS(FunctionNameAndLine);
358       FNLOS << getFunctionName(SP) << SP->getLine();
359       FNLOS.flush();
360       FuncChecksum = hash_value(FunctionNameAndLine);
361     }
362 
363     GCOVBlock &getBlock(BasicBlock *BB) {
364       return Blocks.find(BB)->second;
365     }
366 
367     GCOVBlock &getReturnBlock() {
368       return ReturnBlock;
369     }
370 
371     std::string getEdgeDestinations() {
372       std::string EdgeDestinations;
373       raw_string_ostream EDOS(EdgeDestinations);
374       Function *F = Blocks.begin()->first->getParent();
375       for (BasicBlock &I : *F) {
376         GCOVBlock &Block = getBlock(&I);
377         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i)
378           EDOS << Block.OutEdges[i]->Number;
379       }
380       return EdgeDestinations;
381     }
382 
383     uint32_t getFuncChecksum() const {
384       return FuncChecksum;
385     }
386 
387     void setCfgChecksum(uint32_t Checksum) {
388       CfgChecksum = Checksum;
389     }
390 
391     void writeOut() {
392       writeBytes(FunctionTag, 4);
393       SmallString<128> Filename = getFilename(SP);
394       uint32_t BlockLen = 1 + 1 + 1 + lengthOfGCOVString(getFunctionName(SP)) +
395                           1 + lengthOfGCOVString(Filename) + 1;
396       if (UseCfgChecksum)
397         ++BlockLen;
398       write(BlockLen);
399       write(Ident);
400       write(FuncChecksum);
401       if (UseCfgChecksum)
402         write(CfgChecksum);
403       writeGCOVString(getFunctionName(SP));
404       writeGCOVString(Filename);
405       write(SP->getLine());
406 
407       // Emit count of blocks.
408       writeBytes(BlockTag, 4);
409       write(Blocks.size() + 1);
410       for (int i = 0, e = Blocks.size() + 1; i != e; ++i) {
411         write(0);  // No flags on our blocks.
412       }
413       LLVM_DEBUG(dbgs() << Blocks.size() << " blocks.\n");
414 
415       // Emit edges between blocks.
416       if (Blocks.empty()) return;
417       Function *F = Blocks.begin()->first->getParent();
418       for (BasicBlock &I : *F) {
419         GCOVBlock &Block = getBlock(&I);
420         if (Block.OutEdges.empty()) continue;
421 
422         writeBytes(EdgeTag, 4);
423         write(Block.OutEdges.size() * 2 + 1);
424         write(Block.Number);
425         for (int i = 0, e = Block.OutEdges.size(); i != e; ++i) {
426           LLVM_DEBUG(dbgs() << Block.Number << " -> "
427                             << Block.OutEdges[i]->Number << "\n");
428           write(Block.OutEdges[i]->Number);
429           write(0);  // no flags
430         }
431       }
432 
433       // Emit lines for each block.
434       for (BasicBlock &I : *F)
435         getBlock(&I).writeOut();
436     }
437 
438    private:
439      const DISubprogram *SP;
440     uint32_t Ident;
441     uint32_t FuncChecksum;
442     bool UseCfgChecksum;
443     uint32_t CfgChecksum;
444     DenseMap<BasicBlock *, GCOVBlock> Blocks;
445     GCOVBlock ReturnBlock;
446   };
447 }
448 
449 // RegexesStr is a string containing differents regex separated by a semi-colon.
450 // For example "foo\..*$;bar\..*$".
451 std::vector<Regex> GCOVProfiler::createRegexesFromString(StringRef RegexesStr) {
452   std::vector<Regex> Regexes;
453   while (!RegexesStr.empty()) {
454     std::pair<StringRef, StringRef> HeadTail = RegexesStr.split(';');
455     if (!HeadTail.first.empty()) {
456       Regex Re(HeadTail.first);
457       std::string Err;
458       if (!Re.isValid(Err)) {
459         Ctx->emitError(Twine("Regex ") + HeadTail.first +
460                        " is not valid: " + Err);
461       }
462       Regexes.emplace_back(std::move(Re));
463     }
464     RegexesStr = HeadTail.second;
465   }
466   return Regexes;
467 }
468 
469 bool GCOVProfiler::doesFilenameMatchARegex(StringRef Filename,
470                                            std::vector<Regex> &Regexes) {
471   for (Regex &Re : Regexes) {
472     if (Re.match(Filename)) {
473       return true;
474     }
475   }
476   return false;
477 }
478 
479 bool GCOVProfiler::isFunctionInstrumented(const Function &F) {
480   if (FilterRe.empty() && ExcludeRe.empty()) {
481     return true;
482   }
483   SmallString<128> Filename = getFilename(F.getSubprogram());
484   auto It = InstrumentedFiles.find(Filename);
485   if (It != InstrumentedFiles.end()) {
486     return It->second;
487   }
488 
489   SmallString<256> RealPath;
490   StringRef RealFilename;
491 
492   // Path can be
493   // /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/*.h so for
494   // such a case we must get the real_path.
495   if (sys::fs::real_path(Filename, RealPath)) {
496     // real_path can fail with path like "foo.c".
497     RealFilename = Filename;
498   } else {
499     RealFilename = RealPath;
500   }
501 
502   bool ShouldInstrument;
503   if (FilterRe.empty()) {
504     ShouldInstrument = !doesFilenameMatchARegex(RealFilename, ExcludeRe);
505   } else if (ExcludeRe.empty()) {
506     ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe);
507   } else {
508     ShouldInstrument = doesFilenameMatchARegex(RealFilename, FilterRe) &&
509                        !doesFilenameMatchARegex(RealFilename, ExcludeRe);
510   }
511   InstrumentedFiles[Filename] = ShouldInstrument;
512   return ShouldInstrument;
513 }
514 
515 std::string GCOVProfiler::mangleName(const DICompileUnit *CU,
516                                      GCovFileType OutputType) {
517   bool Notes = OutputType == GCovFileType::GCNO;
518 
519   if (NamedMDNode *GCov = M->getNamedMetadata("llvm.gcov")) {
520     for (int i = 0, e = GCov->getNumOperands(); i != e; ++i) {
521       MDNode *N = GCov->getOperand(i);
522       bool ThreeElement = N->getNumOperands() == 3;
523       if (!ThreeElement && N->getNumOperands() != 2)
524         continue;
525       if (dyn_cast<MDNode>(N->getOperand(ThreeElement ? 2 : 1)) != CU)
526         continue;
527 
528       if (ThreeElement) {
529         // These nodes have no mangling to apply, it's stored mangled in the
530         // bitcode.
531         MDString *NotesFile = dyn_cast<MDString>(N->getOperand(0));
532         MDString *DataFile = dyn_cast<MDString>(N->getOperand(1));
533         if (!NotesFile || !DataFile)
534           continue;
535         return std::string(Notes ? NotesFile->getString()
536                                  : DataFile->getString());
537       }
538 
539       MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
540       if (!GCovFile)
541         continue;
542 
543       SmallString<128> Filename = GCovFile->getString();
544       sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
545       return std::string(Filename.str());
546     }
547   }
548 
549   SmallString<128> Filename = CU->getFilename();
550   sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
551   StringRef FName = sys::path::filename(Filename);
552   SmallString<128> CurPath;
553   if (sys::fs::current_path(CurPath))
554     return std::string(FName);
555   sys::path::append(CurPath, FName);
556   return std::string(CurPath.str());
557 }
558 
559 bool GCOVProfiler::runOnModule(
560     Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
561   this->M = &M;
562   this->GetTLI = std::move(GetTLI);
563   Ctx = &M.getContext();
564 
565   AddFlushBeforeForkAndExec();
566 
567   FilterRe = createRegexesFromString(Options.Filter);
568   ExcludeRe = createRegexesFromString(Options.Exclude);
569 
570   if (Options.EmitNotes) emitProfileNotes();
571   if (Options.EmitData) return emitProfileArcs();
572   return false;
573 }
574 
575 PreservedAnalyses GCOVProfilerPass::run(Module &M,
576                                         ModuleAnalysisManager &AM) {
577 
578   GCOVProfiler Profiler(GCOVOpts);
579   FunctionAnalysisManager &FAM =
580       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
581 
582   if (!Profiler.runOnModule(M, [&](Function &F) -> TargetLibraryInfo & {
583         return FAM.getResult<TargetLibraryAnalysis>(F);
584       }))
585     return PreservedAnalyses::all();
586 
587   return PreservedAnalyses::none();
588 }
589 
590 static bool functionHasLines(Function &F) {
591   // Check whether this function actually has any source lines. Not only
592   // do these waste space, they also can crash gcov.
593   for (auto &BB : F) {
594     for (auto &I : BB) {
595       // Debug intrinsic locations correspond to the location of the
596       // declaration, not necessarily any statements or expressions.
597       if (isa<DbgInfoIntrinsic>(&I)) continue;
598 
599       const DebugLoc &Loc = I.getDebugLoc();
600       if (!Loc)
601         continue;
602 
603       // Artificial lines such as calls to the global constructors.
604       if (Loc.getLine() == 0) continue;
605 
606       return true;
607     }
608   }
609   return false;
610 }
611 
612 static bool isUsingScopeBasedEH(Function &F) {
613   if (!F.hasPersonalityFn()) return false;
614 
615   EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
616   return isScopedEHPersonality(Personality);
617 }
618 
619 static bool shouldKeepInEntry(BasicBlock::iterator It) {
620 	if (isa<AllocaInst>(*It)) return true;
621 	if (isa<DbgInfoIntrinsic>(*It)) return true;
622 	if (auto *II = dyn_cast<IntrinsicInst>(It)) {
623 		if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
624 	}
625 
626 	return false;
627 }
628 
629 void GCOVProfiler::AddFlushBeforeForkAndExec() {
630   SmallVector<CallInst *, 2> Forks;
631   SmallVector<CallInst *, 2> Execs;
632   for (auto &F : M->functions()) {
633     auto *TLI = &GetTLI(F);
634     for (auto &I : instructions(F)) {
635       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
636         if (Function *Callee = CI->getCalledFunction()) {
637           LibFunc LF;
638           if (TLI->getLibFunc(*Callee, LF)) {
639             if (LF == LibFunc_fork) {
640 #if !defined(_WIN32)
641               Forks.push_back(CI);
642 #endif
643             } else if (LF == LibFunc_execl || LF == LibFunc_execle ||
644                        LF == LibFunc_execlp || LF == LibFunc_execv ||
645                        LF == LibFunc_execvp || LF == LibFunc_execve ||
646                        LF == LibFunc_execvpe || LF == LibFunc_execvP) {
647               Execs.push_back(CI);
648             }
649           }
650         }
651       }
652     }
653   }
654 
655   for (auto F : Forks) {
656     IRBuilder<> Builder(F);
657     BasicBlock *Parent = F->getParent();
658     auto NextInst = ++F->getIterator();
659 
660     // We've a fork so just reset the counters in the child process
661     FunctionType *FTy = FunctionType::get(Builder.getInt32Ty(), {}, false);
662     FunctionCallee GCOVFork = M->getOrInsertFunction("__gcov_fork", FTy);
663     F->setCalledFunction(GCOVFork);
664 
665     // We split just after the fork to have a counter for the lines after
666     // Anyway there's a bug:
667     // void foo() { fork(); }
668     // void bar() { foo(); blah(); }
669     // then "blah();" will be called 2 times but showed as 1
670     // because "blah()" belongs to the same block as "foo();"
671     Parent->splitBasicBlock(NextInst);
672 
673     // back() is a br instruction with a debug location
674     // equals to the one from NextAfterFork
675     // So to avoid to have two debug locs on two blocks just change it
676     DebugLoc Loc = F->getDebugLoc();
677     Parent->back().setDebugLoc(Loc);
678   }
679 
680   for (auto E : Execs) {
681     IRBuilder<> Builder(E);
682     BasicBlock *Parent = E->getParent();
683     auto NextInst = ++E->getIterator();
684 
685     // Since the process is replaced by a new one we need to write out gcdas
686     // No need to reset the counters since they'll be lost after the exec**
687     FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
688     FunctionCallee WriteoutF =
689         M->getOrInsertFunction("llvm_writeout_files", FTy);
690     Builder.CreateCall(WriteoutF);
691 
692     DebugLoc Loc = E->getDebugLoc();
693     Builder.SetInsertPoint(&*NextInst);
694     // If the exec** fails we must reset the counters since they've been
695     // dumped
696     FunctionCallee ResetF = M->getOrInsertFunction("llvm_reset_counters", FTy);
697     Builder.CreateCall(ResetF)->setDebugLoc(Loc);
698     Parent->splitBasicBlock(NextInst);
699     Parent->back().setDebugLoc(Loc);
700   }
701 }
702 
703 void GCOVProfiler::emitProfileNotes() {
704   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
705   if (!CU_Nodes) return;
706 
707   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
708     // Each compile unit gets its own .gcno file. This means that whether we run
709     // this pass over the original .o's as they're produced, or run it after
710     // LTO, we'll generate the same .gcno files.
711 
712     auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
713 
714     // Skip module skeleton (and module) CUs.
715     if (CU->getDWOId())
716       continue;
717 
718     std::error_code EC;
719     raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC,
720                        sys::fs::OF_None);
721     if (EC) {
722       Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
723                      EC.message());
724       continue;
725     }
726 
727     std::string EdgeDestinations;
728 
729     unsigned FunctionIdent = 0;
730     for (auto &F : M->functions()) {
731       DISubprogram *SP = F.getSubprogram();
732       if (!SP) continue;
733       if (!functionHasLines(F) || !isFunctionInstrumented(F))
734         continue;
735       // TODO: Functions using scope-based EH are currently not supported.
736       if (isUsingScopeBasedEH(F)) continue;
737 
738       // gcov expects every function to start with an entry block that has a
739       // single successor, so split the entry block to make sure of that.
740       BasicBlock &EntryBlock = F.getEntryBlock();
741       BasicBlock::iterator It = EntryBlock.begin();
742       while (shouldKeepInEntry(It))
743         ++It;
744       EntryBlock.splitBasicBlock(It);
745 
746       bool UseCfgChecksum = strncmp(Options.Version, "407", 3) >= 0;
747       bool ExitBlockBeforeBody = strncmp(Options.Version, "408", 3) >= 0;
748       Funcs.push_back(std::make_unique<GCOVFunction>(
749           SP, &F, &out, FunctionIdent++, UseCfgChecksum, ExitBlockBeforeBody));
750       GCOVFunction &Func = *Funcs.back();
751 
752       // Add the function line number to the lines of the entry block
753       // to have a counter for the function definition.
754       uint32_t Line = SP->getLine();
755       auto Filename = getFilename(SP);
756 
757       // Artificial functions such as global initializers
758       if (!SP->isArtificial())
759         Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
760 
761       for (auto &BB : F) {
762         GCOVBlock &Block = Func.getBlock(&BB);
763         Instruction *TI = BB.getTerminator();
764         if (int successors = TI->getNumSuccessors()) {
765           for (int i = 0; i != successors; ++i) {
766             Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
767           }
768         } else if (isa<ReturnInst>(TI)) {
769           Block.addEdge(Func.getReturnBlock());
770         }
771 
772         for (auto &I : BB) {
773           // Debug intrinsic locations correspond to the location of the
774           // declaration, not necessarily any statements or expressions.
775           if (isa<DbgInfoIntrinsic>(&I)) continue;
776 
777           const DebugLoc &Loc = I.getDebugLoc();
778           if (!Loc)
779             continue;
780 
781           // Artificial lines such as calls to the global constructors.
782           if (Loc.getLine() == 0 || Loc.isImplicitCode())
783             continue;
784 
785           if (Line == Loc.getLine()) continue;
786           Line = Loc.getLine();
787           if (SP != getDISubprogram(Loc.getScope()))
788             continue;
789 
790           GCOVLines &Lines = Block.getFile(Filename);
791           Lines.addLine(Loc.getLine());
792         }
793         Line = 0;
794       }
795       EdgeDestinations += Func.getEdgeDestinations();
796     }
797 
798     FileChecksums.push_back(hash_value(EdgeDestinations));
799     out.write("oncg", 4);
800     out.write(ReversedVersion, 4);
801     out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
802 
803     for (auto &Func : Funcs) {
804       Func->setCfgChecksum(FileChecksums.back());
805       Func->writeOut();
806     }
807 
808     out.write("\0\0\0\0\0\0\0\0", 8);  // EOF
809     out.close();
810   }
811 }
812 
813 bool GCOVProfiler::emitProfileArcs() {
814   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
815   if (!CU_Nodes) return false;
816 
817   bool Result = false;
818   for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
819     SmallVector<std::pair<GlobalVariable *, MDNode *>, 8> CountersBySP;
820     for (auto &F : M->functions()) {
821       DISubprogram *SP = F.getSubprogram();
822       if (!SP) continue;
823       if (!functionHasLines(F) || !isFunctionInstrumented(F))
824         continue;
825       // TODO: Functions using scope-based EH are currently not supported.
826       if (isUsingScopeBasedEH(F)) continue;
827       if (!Result) Result = true;
828 
829       DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
830       unsigned Edges = 0;
831       for (auto &BB : F) {
832         Instruction *TI = BB.getTerminator();
833         if (isa<ReturnInst>(TI)) {
834           EdgeToCounter[{&BB, nullptr}] = Edges++;
835         } else {
836           for (BasicBlock *Succ : successors(TI)) {
837             EdgeToCounter[{&BB, Succ}] = Edges++;
838           }
839         }
840       }
841 
842       ArrayType *CounterTy =
843         ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
844       GlobalVariable *Counters =
845         new GlobalVariable(*M, CounterTy, false,
846                            GlobalValue::InternalLinkage,
847                            Constant::getNullValue(CounterTy),
848                            "__llvm_gcov_ctr");
849       CountersBySP.push_back(std::make_pair(Counters, SP));
850 
851       // If a BB has several predecessors, use a PHINode to select
852       // the correct counter.
853       for (auto &BB : F) {
854         const unsigned EdgeCount =
855             std::distance(pred_begin(&BB), pred_end(&BB));
856         if (EdgeCount) {
857           // The phi node must be at the begin of the BB.
858           IRBuilder<> BuilderForPhi(&*BB.begin());
859           Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
860           PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
861           for (BasicBlock *Pred : predecessors(&BB)) {
862             auto It = EdgeToCounter.find({Pred, &BB});
863             assert(It != EdgeToCounter.end());
864             const unsigned Edge = It->second;
865             Value *EdgeCounter = BuilderForPhi.CreateConstInBoundsGEP2_64(
866                 Counters->getValueType(), Counters, 0, Edge);
867             Phi->addIncoming(EdgeCounter, Pred);
868           }
869 
870           // Skip phis, landingpads.
871           IRBuilder<> Builder(&*BB.getFirstInsertionPt());
872           Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Phi);
873           Count = Builder.CreateAdd(Count, Builder.getInt64(1));
874           Builder.CreateStore(Count, Phi);
875 
876           Instruction *TI = BB.getTerminator();
877           if (isa<ReturnInst>(TI)) {
878             auto It = EdgeToCounter.find({&BB, nullptr});
879             assert(It != EdgeToCounter.end());
880             const unsigned Edge = It->second;
881             Value *Counter = Builder.CreateConstInBoundsGEP2_64(
882                 Counters->getValueType(), Counters, 0, Edge);
883             Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Counter);
884             Count = Builder.CreateAdd(Count, Builder.getInt64(1));
885             Builder.CreateStore(Count, Counter);
886           }
887         }
888       }
889     }
890 
891     Function *WriteoutF = insertCounterWriteout(CountersBySP);
892     Function *ResetF = insertReset(CountersBySP);
893     Function *FlushF = insertFlush(ResetF);
894 
895     // Create a small bit of code that registers the "__llvm_gcov_writeout" to
896     // be executed at exit and the "__llvm_gcov_flush" function to be executed
897     // when "__gcov_flush" is called.
898     FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
899     Function *F = Function::Create(FTy, GlobalValue::InternalLinkage,
900                                    "__llvm_gcov_init", M);
901     F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
902     F->setLinkage(GlobalValue::InternalLinkage);
903     F->addFnAttr(Attribute::NoInline);
904     if (Options.NoRedZone)
905       F->addFnAttr(Attribute::NoRedZone);
906 
907     BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
908     IRBuilder<> Builder(BB);
909 
910     FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
911     Type *Params[] = {PointerType::get(FTy, 0), PointerType::get(FTy, 0),
912                       PointerType::get(FTy, 0)};
913     FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
914 
915     // Initialize the environment and register the local writeout, flush and
916     // reset functions.
917     FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
918     Builder.CreateCall(GCOVInit, {WriteoutF, FlushF, ResetF});
919     Builder.CreateRetVoid();
920 
921     appendToGlobalCtors(*M, F, 0);
922   }
923 
924   return Result;
925 }
926 
927 FunctionCallee GCOVProfiler::getStartFileFunc(const TargetLibraryInfo *TLI) {
928   Type *Args[] = {
929     Type::getInt8PtrTy(*Ctx),  // const char *orig_filename
930     Type::getInt8PtrTy(*Ctx),  // const char version[4]
931     Type::getInt32Ty(*Ctx),    // uint32_t checksum
932   };
933   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
934   AttributeList AL;
935   if (auto AK = TLI->getExtAttrForI32Param(false))
936     AL = AL.addParamAttribute(*Ctx, 2, AK);
937   FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL);
938   return Res;
939 }
940 
941 FunctionCallee GCOVProfiler::getEmitFunctionFunc(const TargetLibraryInfo *TLI) {
942   Type *Args[] = {
943     Type::getInt32Ty(*Ctx),    // uint32_t ident
944     Type::getInt32Ty(*Ctx),    // uint32_t func_checksum
945     Type::getInt32Ty(*Ctx),    // uint32_t cfg_checksum
946   };
947   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
948   AttributeList AL;
949   if (auto AK = TLI->getExtAttrForI32Param(false)) {
950     AL = AL.addParamAttribute(*Ctx, 0, AK);
951     AL = AL.addParamAttribute(*Ctx, 1, AK);
952     AL = AL.addParamAttribute(*Ctx, 2, AK);
953   }
954   return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
955 }
956 
957 FunctionCallee GCOVProfiler::getEmitArcsFunc(const TargetLibraryInfo *TLI) {
958   Type *Args[] = {
959     Type::getInt32Ty(*Ctx),     // uint32_t num_counters
960     Type::getInt64PtrTy(*Ctx),  // uint64_t *counters
961   };
962   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
963   AttributeList AL;
964   if (auto AK = TLI->getExtAttrForI32Param(false))
965     AL = AL.addParamAttribute(*Ctx, 0, AK);
966   return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL);
967 }
968 
969 FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
970   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
971   return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
972 }
973 
974 FunctionCallee GCOVProfiler::getEndFileFunc() {
975   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
976   return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
977 }
978 
979 Function *GCOVProfiler::insertCounterWriteout(
980     ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
981   FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
982   Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
983   if (!WriteoutF)
984     WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
985                                  "__llvm_gcov_writeout", M);
986   WriteoutF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
987   WriteoutF->addFnAttr(Attribute::NoInline);
988   if (Options.NoRedZone)
989     WriteoutF->addFnAttr(Attribute::NoRedZone);
990 
991   BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
992   IRBuilder<> Builder(BB);
993 
994   auto *TLI = &GetTLI(*WriteoutF);
995 
996   FunctionCallee StartFile = getStartFileFunc(TLI);
997   FunctionCallee EmitFunction = getEmitFunctionFunc(TLI);
998   FunctionCallee EmitArcs = getEmitArcsFunc(TLI);
999   FunctionCallee SummaryInfo = getSummaryInfoFunc();
1000   FunctionCallee EndFile = getEndFileFunc();
1001 
1002   NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
1003   if (!CUNodes) {
1004     Builder.CreateRetVoid();
1005     return WriteoutF;
1006   }
1007 
1008   // Collect the relevant data into a large constant data structure that we can
1009   // walk to write out everything.
1010   StructType *StartFileCallArgsTy = StructType::create(
1011       {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
1012   StructType *EmitFunctionCallArgsTy = StructType::create(
1013       {Builder.getInt32Ty(), Builder.getInt32Ty(), Builder.getInt32Ty()});
1014   StructType *EmitArcsCallArgsTy = StructType::create(
1015       {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
1016   StructType *FileInfoTy =
1017       StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
1018                           EmitFunctionCallArgsTy->getPointerTo(),
1019                           EmitArcsCallArgsTy->getPointerTo()});
1020 
1021   Constant *Zero32 = Builder.getInt32(0);
1022   // Build an explicit array of two zeros for use in ConstantExpr GEP building.
1023   Constant *TwoZero32s[] = {Zero32, Zero32};
1024 
1025   SmallVector<Constant *, 8> FileInfos;
1026   for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
1027     auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
1028 
1029     // Skip module skeleton (and module) CUs.
1030     if (CU->getDWOId())
1031       continue;
1032 
1033     std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
1034     uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
1035     auto *StartFileCallArgs = ConstantStruct::get(
1036         StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
1037                               Builder.CreateGlobalStringPtr(ReversedVersion),
1038                               Builder.getInt32(CfgChecksum)});
1039 
1040     SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
1041     SmallVector<Constant *, 8> EmitArcsCallArgsArray;
1042     for (int j : llvm::seq<int>(0, CountersBySP.size())) {
1043       uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
1044       EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
1045           EmitFunctionCallArgsTy,
1046           {Builder.getInt32(j),
1047            Builder.getInt32(FuncChecksum),
1048            Builder.getInt32(CfgChecksum)}));
1049 
1050       GlobalVariable *GV = CountersBySP[j].first;
1051       unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1052       EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1053           EmitArcsCallArgsTy,
1054           {Builder.getInt32(Arcs), ConstantExpr::getInBoundsGetElementPtr(
1055                                        GV->getValueType(), GV, TwoZero32s)}));
1056     }
1057     // Create global arrays for the two emit calls.
1058     int CountersSize = CountersBySP.size();
1059     assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1060            "Mismatched array size!");
1061     assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1062            "Mismatched array size!");
1063     auto *EmitFunctionCallArgsArrayTy =
1064         ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1065     auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1066         *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1067         GlobalValue::InternalLinkage,
1068         ConstantArray::get(EmitFunctionCallArgsArrayTy,
1069                            EmitFunctionCallArgsArray),
1070         Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1071     auto *EmitArcsCallArgsArrayTy =
1072         ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1073     EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1074         GlobalValue::UnnamedAddr::Global);
1075     auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1076         *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1077         GlobalValue::InternalLinkage,
1078         ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1079         Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1080     EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1081 
1082     FileInfos.push_back(ConstantStruct::get(
1083         FileInfoTy,
1084         {StartFileCallArgs, Builder.getInt32(CountersSize),
1085          ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1086                                                 EmitFunctionCallArgsArrayGV,
1087                                                 TwoZero32s),
1088          ConstantExpr::getInBoundsGetElementPtr(
1089              EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
1090   }
1091 
1092   // If we didn't find anything to actually emit, bail on out.
1093   if (FileInfos.empty()) {
1094     Builder.CreateRetVoid();
1095     return WriteoutF;
1096   }
1097 
1098   // To simplify code, we cap the number of file infos we write out to fit
1099   // easily in a 32-bit signed integer. This gives consistent behavior between
1100   // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1101   // operations on 32-bit systems. It also seems unreasonable to try to handle
1102   // more than 2 billion files.
1103   if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1104     FileInfos.resize(INT_MAX);
1105 
1106   // Create a global for the entire data structure so we can walk it more
1107   // easily.
1108   auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1109   auto *FileInfoArrayGV = new GlobalVariable(
1110       *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1111       ConstantArray::get(FileInfoArrayTy, FileInfos),
1112       "__llvm_internal_gcov_emit_file_info");
1113   FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1114 
1115   // Create the CFG for walking this data structure.
1116   auto *FileLoopHeader =
1117       BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1118   auto *CounterLoopHeader =
1119       BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1120   auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1121   auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1122 
1123   // We always have at least one file, so just branch to the header.
1124   Builder.CreateBr(FileLoopHeader);
1125 
1126   // The index into the files structure is our loop induction variable.
1127   Builder.SetInsertPoint(FileLoopHeader);
1128   PHINode *IV =
1129       Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1130   IV->addIncoming(Builder.getInt32(0), BB);
1131   auto *FileInfoPtr = Builder.CreateInBoundsGEP(
1132       FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV});
1133   auto *StartFileCallArgsPtr =
1134       Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0);
1135   auto *StartFileCall = Builder.CreateCall(
1136       StartFile,
1137       {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0),
1138                           Builder.CreateStructGEP(StartFileCallArgsTy,
1139                                                   StartFileCallArgsPtr, 0)),
1140        Builder.CreateLoad(StartFileCallArgsTy->getElementType(1),
1141                           Builder.CreateStructGEP(StartFileCallArgsTy,
1142                                                   StartFileCallArgsPtr, 1)),
1143        Builder.CreateLoad(StartFileCallArgsTy->getElementType(2),
1144                           Builder.CreateStructGEP(StartFileCallArgsTy,
1145                                                   StartFileCallArgsPtr, 2))});
1146   if (auto AK = TLI->getExtAttrForI32Param(false))
1147     StartFileCall->addParamAttr(2, AK);
1148   auto *NumCounters =
1149       Builder.CreateLoad(FileInfoTy->getElementType(1),
1150                          Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1));
1151   auto *EmitFunctionCallArgsArray =
1152       Builder.CreateLoad(FileInfoTy->getElementType(2),
1153                          Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2));
1154   auto *EmitArcsCallArgsArray =
1155       Builder.CreateLoad(FileInfoTy->getElementType(3),
1156                          Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3));
1157   auto *EnterCounterLoopCond =
1158       Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1159   Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1160 
1161   Builder.SetInsertPoint(CounterLoopHeader);
1162   auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1163   JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1164   auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP(
1165       EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV);
1166   auto *EmitFunctionCall = Builder.CreateCall(
1167       EmitFunction,
1168       {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0),
1169                           Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1170                                                   EmitFunctionCallArgsPtr, 0)),
1171        Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1),
1172                           Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1173                                                   EmitFunctionCallArgsPtr, 1)),
1174        Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2),
1175                           Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1176                                                   EmitFunctionCallArgsPtr,
1177                                                   2))});
1178   if (auto AK = TLI->getExtAttrForI32Param(false)) {
1179     EmitFunctionCall->addParamAttr(0, AK);
1180     EmitFunctionCall->addParamAttr(1, AK);
1181     EmitFunctionCall->addParamAttr(2, AK);
1182   }
1183   auto *EmitArcsCallArgsPtr =
1184       Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV);
1185   auto *EmitArcsCall = Builder.CreateCall(
1186       EmitArcs,
1187       {Builder.CreateLoad(
1188            EmitArcsCallArgsTy->getElementType(0),
1189            Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0)),
1190        Builder.CreateLoad(EmitArcsCallArgsTy->getElementType(1),
1191                           Builder.CreateStructGEP(EmitArcsCallArgsTy,
1192                                                   EmitArcsCallArgsPtr, 1))});
1193   if (auto AK = TLI->getExtAttrForI32Param(false))
1194     EmitArcsCall->addParamAttr(0, AK);
1195   auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1196   auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1197   Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1198   JV->addIncoming(NextJV, CounterLoopHeader);
1199 
1200   Builder.SetInsertPoint(FileLoopLatch);
1201   Builder.CreateCall(SummaryInfo, {});
1202   Builder.CreateCall(EndFile, {});
1203   auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1204   auto *FileLoopCond =
1205       Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1206   Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1207   IV->addIncoming(NextIV, FileLoopLatch);
1208 
1209   Builder.SetInsertPoint(ExitBB);
1210   Builder.CreateRetVoid();
1211 
1212   return WriteoutF;
1213 }
1214 
1215 Function *GCOVProfiler::insertReset(
1216     ArrayRef<std::pair<GlobalVariable *, MDNode *>> CountersBySP) {
1217   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1218   Function *ResetF = M->getFunction("__llvm_gcov_reset");
1219   if (!ResetF)
1220     ResetF = Function::Create(FTy, GlobalValue::InternalLinkage,
1221                               "__llvm_gcov_reset", M);
1222   else
1223     ResetF->setLinkage(GlobalValue::InternalLinkage);
1224   ResetF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1225   ResetF->addFnAttr(Attribute::NoInline);
1226   if (Options.NoRedZone)
1227     ResetF->addFnAttr(Attribute::NoRedZone);
1228 
1229   BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", ResetF);
1230   IRBuilder<> Builder(Entry);
1231 
1232   // Zero out the counters.
1233   for (const auto &I : CountersBySP) {
1234     GlobalVariable *GV = I.first;
1235     Constant *Null = Constant::getNullValue(GV->getValueType());
1236     Builder.CreateStore(Null, GV);
1237   }
1238 
1239   Type *RetTy = ResetF->getReturnType();
1240   if (RetTy->isVoidTy())
1241     Builder.CreateRetVoid();
1242   else if (RetTy->isIntegerTy())
1243     // Used if __llvm_gcov_reset was implicitly declared.
1244     Builder.CreateRet(ConstantInt::get(RetTy, 0));
1245   else
1246     report_fatal_error("invalid return type for __llvm_gcov_reset");
1247 
1248   return ResetF;
1249 }
1250 
1251 Function *GCOVProfiler::insertFlush(Function *ResetF) {
1252   FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1253   Function *FlushF = M->getFunction("__llvm_gcov_flush");
1254   if (!FlushF)
1255     FlushF = Function::Create(FTy, GlobalValue::InternalLinkage,
1256                               "__llvm_gcov_flush", M);
1257   else
1258     FlushF->setLinkage(GlobalValue::InternalLinkage);
1259   FlushF->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1260   FlushF->addFnAttr(Attribute::NoInline);
1261   if (Options.NoRedZone)
1262     FlushF->addFnAttr(Attribute::NoRedZone);
1263 
1264   BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1265 
1266   // Write out the current counters.
1267   Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1268   assert(WriteoutF && "Need to create the writeout function first!");
1269 
1270   IRBuilder<> Builder(Entry);
1271   Builder.CreateCall(WriteoutF, {});
1272   Builder.CreateCall(ResetF, {});
1273 
1274   Type *RetTy = FlushF->getReturnType();
1275   if (RetTy->isVoidTy())
1276     Builder.CreateRetVoid();
1277   else if (RetTy->isIntegerTy())
1278     // Used if __llvm_gcov_flush was implicitly declared.
1279     Builder.CreateRet(ConstantInt::get(RetTy, 0));
1280   else
1281     report_fatal_error("invalid return type for __llvm_gcov_flush");
1282 
1283   return FlushF;
1284 }
1285