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