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