LLVM  10.0.0
GCOVProfiling.cpp
Go to the documentation of this file.
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"
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"
36 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Regex.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 
53 DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden,
55 static cl::opt<bool> DefaultExitBlockBeforeBody("gcov-exit-block-before-body",
56  cl::init(false), cl::Hidden);
57 
59  GCOVOptions Options;
60  Options.EmitNotes = true;
61  Options.EmitData = true;
62  Options.UseCfgChecksum = false;
63  Options.NoRedZone = false;
64  Options.FunctionNamesInData = true;
66 
67  if (DefaultGCOVVersion.size() != 4) {
68  llvm::report_fatal_error(std::string("Invalid -default-gcov-version: ") +
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 *insertFlush(ArrayRef<std::pair<GlobalVariable *, MDNode *>>);
119 
120  void AddFlushBeforeForkAndExec();
121 
122  enum class GCovFileType { GCNO, GCDA };
123  std::string mangleName(const DICompileUnit *CU, GCovFileType FileType);
124 
125  GCOVOptions Options;
126 
127  // Reversed, NUL-terminated copy of Options.Version.
128  char ReversedVersion[5];
129  // Checksum, produced by hash of EdgeDestinations
130  SmallVector<uint32_t, 4> FileChecksums;
131 
132  Module *M = nullptr;
133  std::function<const TargetLibraryInfo &(Function &F)> GetTLI;
134  LLVMContext *Ctx = nullptr;
136  std::vector<Regex> FilterRe;
137  std::vector<Regex> ExcludeRe;
138  StringMap<bool> InstrumentedFiles;
139 };
140 
141 class GCOVProfilerLegacyPass : public ModulePass {
142 public:
143  static char ID;
144  GCOVProfilerLegacyPass()
145  : GCOVProfilerLegacyPass(GCOVOptions::getDefault()) {}
146  GCOVProfilerLegacyPass(const GCOVOptions &Opts)
147  : ModulePass(ID), Profiler(Opts) {
149  }
150  StringRef getPassName() const override { return "GCOV Profiler"; }
151 
152  bool runOnModule(Module &M) override {
153  return Profiler.runOnModule(M, [this](Function &F) -> TargetLibraryInfo & {
154  return getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
155  });
156  }
157 
158  void getAnalysisUsage(AnalysisUsage &AU) const override {
160  }
161 
162 private:
163  GCOVProfiler Profiler;
164 };
165 }
166 
169  GCOVProfilerLegacyPass, "insert-gcov-profiling",
170  "Insert instrumentation for GCOV profiling", false, false)
173  GCOVProfilerLegacyPass, "insert-gcov-profiling",
174  "Insert instrumentation for GCOV profiling", false, false)
175 
177  return new GCOVProfilerLegacyPass(Options);
178 }
179 
181  if (!SP->getLinkageName().empty())
182  return SP->getLinkageName();
183  return SP->getName();
184 }
185 
186 /// Extract a filename for a DISubprogram.
187 ///
188 /// Prefer relative paths in the coverage notes. Clang also may split
189 /// up absolute paths into a directory and filename component. When
190 /// the relative path doesn't exist, reconstruct the absolute path.
192  SmallString<128> Path;
193  StringRef RelPath = SP->getFilename();
194  if (sys::fs::exists(RelPath))
195  Path = RelPath;
196  else
197  sys::path::append(Path, SP->getDirectory(), SP->getFilename());
198  return Path;
199 }
200 
201 namespace {
202  class GCOVRecord {
203  protected:
204  static const char *const LinesTag;
205  static const char *const FunctionTag;
206  static const char *const BlockTag;
207  static const char *const EdgeTag;
208 
209  GCOVRecord() = default;
210 
211  void writeBytes(const char *Bytes, int Size) {
212  os->write(Bytes, Size);
213  }
214 
215  void write(uint32_t i) {
216  writeBytes(reinterpret_cast<char*>(&i), 4);
217  }
218 
219  // Returns the length measured in 4-byte blocks that will be used to
220  // represent this string in a GCOV file
221  static unsigned lengthOfGCOVString(StringRef s) {
222  // A GCOV string is a length, followed by a NUL, then between 0 and 3 NULs
223  // padding out to the next 4-byte word. The length is measured in 4-byte
224  // words including padding, not bytes of actual string.
225  return (s.size() / 4) + 1;
226  }
227 
228  void writeGCOVString(StringRef s) {
229  uint32_t Len = lengthOfGCOVString(s);
230  write(Len);
231  writeBytes(s.data(), s.size());
232 
233  // Write 1 to 4 bytes of NUL padding.
234  assert((unsigned)(4 - (s.size() % 4)) > 0);
235  assert((unsigned)(4 - (s.size() % 4)) <= 4);
236  writeBytes("\0\0\0\0", 4 - (s.size() % 4));
237  }
238 
239  raw_ostream *os;
240  };
241  const char *const GCOVRecord::LinesTag = "\0\0\x45\x01";
242  const char *const GCOVRecord::FunctionTag = "\0\0\0\1";
243  const char *const GCOVRecord::BlockTag = "\0\0\x41\x01";
244  const char *const GCOVRecord::EdgeTag = "\0\0\x43\x01";
245 
246  class GCOVFunction;
247  class GCOVBlock;
248 
249  // Constructed only by requesting it from a GCOVBlock, this object stores a
250  // list of line numbers and a single filename, representing lines that belong
251  // to the block.
252  class GCOVLines : public GCOVRecord {
253  public:
254  void addLine(uint32_t Line) {
255  assert(Line != 0 && "Line zero is not a valid real line number.");
256  Lines.push_back(Line);
257  }
258 
259  uint32_t length() const {
260  // Here 2 = 1 for string length + 1 for '0' id#.
261  return lengthOfGCOVString(Filename) + 2 + Lines.size();
262  }
263 
264  void writeOut() {
265  write(0);
266  writeGCOVString(Filename);
267  for (int i = 0, e = Lines.size(); i != e; ++i)
268  write(Lines[i]);
269  }
270 
271  GCOVLines(StringRef F, raw_ostream *os)
272  : Filename(F) {
273  this->os = os;
274  }
275 
276  private:
277  std::string Filename;
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,
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 
329  : Number(Number) {
330  this->os = os;
331  }
332 
334  StringMap<GCOVLines> LinesByFile;
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:
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;
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  }
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 Notes ? NotesFile->getString() : DataFile->getString();
541  }
542 
543  MDString *GCovFile = dyn_cast<MDString>(N->getOperand(0));
544  if (!GCovFile)
545  continue;
546 
547  SmallString<128> Filename = GCovFile->getString();
548  sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
549  return Filename.str();
550  }
551  }
552 
553  SmallString<128> Filename = CU->getFilename();
554  sys::path::replace_extension(Filename, Notes ? "gcno" : "gcda");
555  StringRef FName = sys::path::filename(Filename);
556  SmallString<128> CurPath;
557  if (sys::fs::current_path(CurPath)) return FName;
558  sys::path::append(CurPath, FName);
559  return CurPath.str();
560 }
561 
562 bool GCOVProfiler::runOnModule(
563  Module &M, std::function<const TargetLibraryInfo &(Function &F)> GetTLI) {
564  this->M = &M;
565  this->GetTLI = std::move(GetTLI);
566  Ctx = &M.getContext();
567 
568  AddFlushBeforeForkAndExec();
569 
570  FilterRe = createRegexesFromString(Options.Filter);
571  ExcludeRe = createRegexesFromString(Options.Exclude);
572 
573  if (Options.EmitNotes) emitProfileNotes();
574  if (Options.EmitData) return emitProfileArcs();
575  return false;
576 }
577 
579  ModuleAnalysisManager &AM) {
580 
581  GCOVProfiler Profiler(GCOVOpts);
583  AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
584 
585  if (!Profiler.runOnModule(M, [&](Function &F) -> TargetLibraryInfo & {
586  return FAM.getResult<TargetLibraryAnalysis>(F);
587  }))
588  return PreservedAnalyses::all();
589 
590  return PreservedAnalyses::none();
591 }
592 
593 static bool functionHasLines(Function &F) {
594  // Check whether this function actually has any source lines. Not only
595  // do these waste space, they also can crash gcov.
596  for (auto &BB : F) {
597  for (auto &I : BB) {
598  // Debug intrinsic locations correspond to the location of the
599  // declaration, not necessarily any statements or expressions.
600  if (isa<DbgInfoIntrinsic>(&I)) continue;
601 
602  const DebugLoc &Loc = I.getDebugLoc();
603  if (!Loc)
604  continue;
605 
606  // Artificial lines such as calls to the global constructors.
607  if (Loc.getLine() == 0) continue;
608 
609  return true;
610  }
611  }
612  return false;
613 }
614 
615 static bool isUsingScopeBasedEH(Function &F) {
616  if (!F.hasPersonalityFn()) return false;
617 
619  return isScopedEHPersonality(Personality);
620 }
621 
623  if (isa<AllocaInst>(*It)) return true;
624  if (isa<DbgInfoIntrinsic>(*It)) return true;
625  if (auto *II = dyn_cast<IntrinsicInst>(It)) {
626  if (II->getIntrinsicID() == llvm::Intrinsic::localescape) return true;
627  }
628 
629  return false;
630 }
631 
632 void GCOVProfiler::AddFlushBeforeForkAndExec() {
633  SmallVector<Instruction *, 2> ForkAndExecs;
634  for (auto &F : M->functions()) {
635  auto *TLI = &GetTLI(F);
636  for (auto &I : instructions(F)) {
637  if (CallInst *CI = dyn_cast<CallInst>(&I)) {
638  if (Function *Callee = CI->getCalledFunction()) {
639  LibFunc LF;
640  if (TLI->getLibFunc(*Callee, LF) &&
641  (LF == LibFunc_fork || LF == LibFunc_execl ||
642  LF == LibFunc_execle || LF == LibFunc_execlp ||
643  LF == LibFunc_execv || LF == LibFunc_execvp ||
644  LF == LibFunc_execve || LF == LibFunc_execvpe ||
645  LF == LibFunc_execvP)) {
646  ForkAndExecs.push_back(&I);
647  }
648  }
649  }
650  }
651  }
652 
653  // We need to split the block after the fork/exec call
654  // because else the counters for the lines after will be
655  // the same as before the call.
656  for (auto I : ForkAndExecs) {
657  IRBuilder<> Builder(I);
658  FunctionType *FTy = FunctionType::get(Builder.getVoidTy(), {}, false);
659  FunctionCallee GCOVFlush = M->getOrInsertFunction("__gcov_flush", FTy);
660  Builder.CreateCall(GCOVFlush);
661  I->getParent()->splitBasicBlock(I);
662  }
663 }
664 
665 void GCOVProfiler::emitProfileNotes() {
666  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
667  if (!CU_Nodes) return;
668 
669  for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
670  // Each compile unit gets its own .gcno file. This means that whether we run
671  // this pass over the original .o's as they're produced, or run it after
672  // LTO, we'll generate the same .gcno files.
673 
674  auto *CU = cast<DICompileUnit>(CU_Nodes->getOperand(i));
675 
676  // Skip module skeleton (and module) CUs.
677  if (CU->getDWOId())
678  continue;
679 
680  std::error_code EC;
681  raw_fd_ostream out(mangleName(CU, GCovFileType::GCNO), EC,
683  if (EC) {
684  Ctx->emitError(Twine("failed to open coverage notes file for writing: ") +
685  EC.message());
686  continue;
687  }
688 
689  std::string EdgeDestinations;
690 
691  unsigned FunctionIdent = 0;
692  for (auto &F : M->functions()) {
694  if (!SP) continue;
695  if (!functionHasLines(F) || !isFunctionInstrumented(F))
696  continue;
697  // TODO: Functions using scope-based EH are currently not supported.
698  if (isUsingScopeBasedEH(F)) continue;
699 
700  // gcov expects every function to start with an entry block that has a
701  // single successor, so split the entry block to make sure of that.
702  BasicBlock &EntryBlock = F.getEntryBlock();
703  BasicBlock::iterator It = EntryBlock.begin();
704  while (shouldKeepInEntry(It))
705  ++It;
706  EntryBlock.splitBasicBlock(It);
707 
708  Funcs.push_back(std::make_unique<GCOVFunction>(SP, &F, &out, FunctionIdent++,
709  Options.UseCfgChecksum,
710  Options.ExitBlockBeforeBody));
711  GCOVFunction &Func = *Funcs.back();
712 
713  // Add the function line number to the lines of the entry block
714  // to have a counter for the function definition.
715  uint32_t Line = SP->getLine();
716  auto Filename = getFilename(SP);
717 
718  // Artificial functions such as global initializers
719  if (!SP->isArtificial())
720  Func.getBlock(&EntryBlock).getFile(Filename).addLine(Line);
721 
722  for (auto &BB : F) {
723  GCOVBlock &Block = Func.getBlock(&BB);
724  Instruction *TI = BB.getTerminator();
725  if (int successors = TI->getNumSuccessors()) {
726  for (int i = 0; i != successors; ++i) {
727  Block.addEdge(Func.getBlock(TI->getSuccessor(i)));
728  }
729  } else if (isa<ReturnInst>(TI)) {
730  Block.addEdge(Func.getReturnBlock());
731  }
732 
733  for (auto &I : BB) {
734  // Debug intrinsic locations correspond to the location of the
735  // declaration, not necessarily any statements or expressions.
736  if (isa<DbgInfoIntrinsic>(&I)) continue;
737 
738  const DebugLoc &Loc = I.getDebugLoc();
739  if (!Loc)
740  continue;
741 
742  // Artificial lines such as calls to the global constructors.
743  if (Loc.getLine() == 0 || Loc.isImplicitCode())
744  continue;
745 
746  if (Line == Loc.getLine()) continue;
747  Line = Loc.getLine();
748  if (SP != getDISubprogram(Loc.getScope()))
749  continue;
750 
751  GCOVLines &Lines = Block.getFile(Filename);
752  Lines.addLine(Loc.getLine());
753  }
754  Line = 0;
755  }
756  EdgeDestinations += Func.getEdgeDestinations();
757  }
758 
759  FileChecksums.push_back(hash_value(EdgeDestinations));
760  out.write("oncg", 4);
761  out.write(ReversedVersion, 4);
762  out.write(reinterpret_cast<char*>(&FileChecksums.back()), 4);
763 
764  for (auto &Func : Funcs) {
765  Func->setCfgChecksum(FileChecksums.back());
766  Func->writeOut();
767  }
768 
769  out.write("\0\0\0\0\0\0\0\0", 8); // EOF
770  out.close();
771  }
772 }
773 
774 bool GCOVProfiler::emitProfileArcs() {
775  NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
776  if (!CU_Nodes) return false;
777 
778  bool Result = false;
779  for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
781  for (auto &F : M->functions()) {
783  if (!SP) continue;
784  if (!functionHasLines(F) || !isFunctionInstrumented(F))
785  continue;
786  // TODO: Functions using scope-based EH are currently not supported.
787  if (isUsingScopeBasedEH(F)) continue;
788  if (!Result) Result = true;
789 
790  DenseMap<std::pair<BasicBlock *, BasicBlock *>, unsigned> EdgeToCounter;
791  unsigned Edges = 0;
792  for (auto &BB : F) {
793  Instruction *TI = BB.getTerminator();
794  if (isa<ReturnInst>(TI)) {
795  EdgeToCounter[{&BB, nullptr}] = Edges++;
796  } else {
797  for (BasicBlock *Succ : successors(TI)) {
798  EdgeToCounter[{&BB, Succ}] = Edges++;
799  }
800  }
801  }
802 
803  ArrayType *CounterTy =
804  ArrayType::get(Type::getInt64Ty(*Ctx), Edges);
805  GlobalVariable *Counters =
806  new GlobalVariable(*M, CounterTy, false,
808  Constant::getNullValue(CounterTy),
809  "__llvm_gcov_ctr");
810  CountersBySP.push_back(std::make_pair(Counters, SP));
811 
812  // If a BB has several predecessors, use a PHINode to select
813  // the correct counter.
814  for (auto &BB : F) {
815  const unsigned EdgeCount =
816  std::distance(pred_begin(&BB), pred_end(&BB));
817  if (EdgeCount) {
818  // The phi node must be at the begin of the BB.
819  IRBuilder<> BuilderForPhi(&*BB.begin());
820  Type *Int64PtrTy = Type::getInt64PtrTy(*Ctx);
821  PHINode *Phi = BuilderForPhi.CreatePHI(Int64PtrTy, EdgeCount);
822  for (BasicBlock *Pred : predecessors(&BB)) {
823  auto It = EdgeToCounter.find({Pred, &BB});
824  assert(It != EdgeToCounter.end());
825  const unsigned Edge = It->second;
826  Value *EdgeCounter = BuilderForPhi.CreateConstInBoundsGEP2_64(
827  Counters->getValueType(), Counters, 0, Edge);
828  Phi->addIncoming(EdgeCounter, Pred);
829  }
830 
831  // Skip phis, landingpads.
832  IRBuilder<> Builder(&*BB.getFirstInsertionPt());
833  Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Phi);
834  Count = Builder.CreateAdd(Count, Builder.getInt64(1));
835  Builder.CreateStore(Count, Phi);
836 
837  Instruction *TI = BB.getTerminator();
838  if (isa<ReturnInst>(TI)) {
839  auto It = EdgeToCounter.find({&BB, nullptr});
840  assert(It != EdgeToCounter.end());
841  const unsigned Edge = It->second;
842  Value *Counter = Builder.CreateConstInBoundsGEP2_64(
843  Counters->getValueType(), Counters, 0, Edge);
844  Value *Count = Builder.CreateLoad(Builder.getInt64Ty(), Counter);
845  Count = Builder.CreateAdd(Count, Builder.getInt64(1));
846  Builder.CreateStore(Count, Counter);
847  }
848  }
849  }
850  }
851 
852  Function *WriteoutF = insertCounterWriteout(CountersBySP);
853  Function *FlushF = insertFlush(CountersBySP);
854 
855  // Create a small bit of code that registers the "__llvm_gcov_writeout" to
856  // be executed at exit and the "__llvm_gcov_flush" function to be executed
857  // when "__gcov_flush" is called.
858  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
860  "__llvm_gcov_init", M);
863  F->addFnAttr(Attribute::NoInline);
864  if (Options.NoRedZone)
865  F->addFnAttr(Attribute::NoRedZone);
866 
867  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", F);
868  IRBuilder<> Builder(BB);
869 
870  FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
871  Type *Params[] = {
872  PointerType::get(FTy, 0),
873  PointerType::get(FTy, 0)
874  };
875  FTy = FunctionType::get(Builder.getVoidTy(), Params, false);
876 
877  // Initialize the environment and register the local writeout and flush
878  // functions.
879  FunctionCallee GCOVInit = M->getOrInsertFunction("llvm_gcov_init", FTy);
880  Builder.CreateCall(GCOVInit, {WriteoutF, FlushF});
881  Builder.CreateRetVoid();
882 
883  appendToGlobalCtors(*M, F, 0);
884  }
885 
886  return Result;
887 }
888 
889 FunctionCallee GCOVProfiler::getStartFileFunc(const TargetLibraryInfo *TLI) {
890  Type *Args[] = {
891  Type::getInt8PtrTy(*Ctx), // const char *orig_filename
892  Type::getInt8PtrTy(*Ctx), // const char version[4]
893  Type::getInt32Ty(*Ctx), // uint32_t checksum
894  };
895  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
897  if (auto AK = TLI->getExtAttrForI32Param(false))
898  AL = AL.addParamAttribute(*Ctx, 2, AK);
899  FunctionCallee Res = M->getOrInsertFunction("llvm_gcda_start_file", FTy, AL);
900  return Res;
901 }
902 
903 FunctionCallee GCOVProfiler::getEmitFunctionFunc(const TargetLibraryInfo *TLI) {
904  Type *Args[] = {
905  Type::getInt32Ty(*Ctx), // uint32_t ident
906  Type::getInt8PtrTy(*Ctx), // const char *function_name
907  Type::getInt32Ty(*Ctx), // uint32_t func_checksum
908  Type::getInt8Ty(*Ctx), // uint8_t use_extra_checksum
909  Type::getInt32Ty(*Ctx), // uint32_t cfg_checksum
910  };
911  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
913  if (auto AK = TLI->getExtAttrForI32Param(false)) {
914  AL = AL.addParamAttribute(*Ctx, 0, AK);
915  AL = AL.addParamAttribute(*Ctx, 2, AK);
916  AL = AL.addParamAttribute(*Ctx, 3, AK);
917  AL = AL.addParamAttribute(*Ctx, 4, AK);
918  }
919  return M->getOrInsertFunction("llvm_gcda_emit_function", FTy);
920 }
921 
922 FunctionCallee GCOVProfiler::getEmitArcsFunc(const TargetLibraryInfo *TLI) {
923  Type *Args[] = {
924  Type::getInt32Ty(*Ctx), // uint32_t num_counters
925  Type::getInt64PtrTy(*Ctx), // uint64_t *counters
926  };
927  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), Args, false);
929  if (auto AK = TLI->getExtAttrForI32Param(false))
930  AL = AL.addParamAttribute(*Ctx, 0, AK);
931  return M->getOrInsertFunction("llvm_gcda_emit_arcs", FTy, AL);
932 }
933 
934 FunctionCallee GCOVProfiler::getSummaryInfoFunc() {
935  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
936  return M->getOrInsertFunction("llvm_gcda_summary_info", FTy);
937 }
938 
939 FunctionCallee GCOVProfiler::getEndFileFunc() {
940  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
941  return M->getOrInsertFunction("llvm_gcda_end_file", FTy);
942 }
943 
944 Function *GCOVProfiler::insertCounterWriteout(
945  ArrayRef<std::pair<GlobalVariable *, MDNode *> > CountersBySP) {
946  FunctionType *WriteoutFTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
947  Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
948  if (!WriteoutF)
949  WriteoutF = Function::Create(WriteoutFTy, GlobalValue::InternalLinkage,
950  "__llvm_gcov_writeout", M);
952  WriteoutF->addFnAttr(Attribute::NoInline);
953  if (Options.NoRedZone)
954  WriteoutF->addFnAttr(Attribute::NoRedZone);
955 
956  BasicBlock *BB = BasicBlock::Create(*Ctx, "entry", WriteoutF);
957  IRBuilder<> Builder(BB);
958 
959  auto *TLI = &GetTLI(*WriteoutF);
960 
961  FunctionCallee StartFile = getStartFileFunc(TLI);
962  FunctionCallee EmitFunction = getEmitFunctionFunc(TLI);
963  FunctionCallee EmitArcs = getEmitArcsFunc(TLI);
964  FunctionCallee SummaryInfo = getSummaryInfoFunc();
965  FunctionCallee EndFile = getEndFileFunc();
966 
967  NamedMDNode *CUNodes = M->getNamedMetadata("llvm.dbg.cu");
968  if (!CUNodes) {
969  Builder.CreateRetVoid();
970  return WriteoutF;
971  }
972 
973  // Collect the relevant data into a large constant data structure that we can
974  // walk to write out everything.
975  StructType *StartFileCallArgsTy = StructType::create(
976  {Builder.getInt8PtrTy(), Builder.getInt8PtrTy(), Builder.getInt32Ty()});
977  StructType *EmitFunctionCallArgsTy = StructType::create(
978  {Builder.getInt32Ty(), Builder.getInt8PtrTy(), Builder.getInt32Ty(),
979  Builder.getInt8Ty(), Builder.getInt32Ty()});
980  StructType *EmitArcsCallArgsTy = StructType::create(
981  {Builder.getInt32Ty(), Builder.getInt64Ty()->getPointerTo()});
982  StructType *FileInfoTy =
983  StructType::create({StartFileCallArgsTy, Builder.getInt32Ty(),
984  EmitFunctionCallArgsTy->getPointerTo(),
985  EmitArcsCallArgsTy->getPointerTo()});
986 
987  Constant *Zero32 = Builder.getInt32(0);
988  // Build an explicit array of two zeros for use in ConstantExpr GEP building.
989  Constant *TwoZero32s[] = {Zero32, Zero32};
990 
991  SmallVector<Constant *, 8> FileInfos;
992  for (int i : llvm::seq<int>(0, CUNodes->getNumOperands())) {
993  auto *CU = cast<DICompileUnit>(CUNodes->getOperand(i));
994 
995  // Skip module skeleton (and module) CUs.
996  if (CU->getDWOId())
997  continue;
998 
999  std::string FilenameGcda = mangleName(CU, GCovFileType::GCDA);
1000  uint32_t CfgChecksum = FileChecksums.empty() ? 0 : FileChecksums[i];
1001  auto *StartFileCallArgs = ConstantStruct::get(
1002  StartFileCallArgsTy, {Builder.CreateGlobalStringPtr(FilenameGcda),
1003  Builder.CreateGlobalStringPtr(ReversedVersion),
1004  Builder.getInt32(CfgChecksum)});
1005 
1006  SmallVector<Constant *, 8> EmitFunctionCallArgsArray;
1007  SmallVector<Constant *, 8> EmitArcsCallArgsArray;
1008  for (int j : llvm::seq<int>(0, CountersBySP.size())) {
1009  auto *SP = cast_or_null<DISubprogram>(CountersBySP[j].second);
1010  uint32_t FuncChecksum = Funcs.empty() ? 0 : Funcs[j]->getFuncChecksum();
1011  EmitFunctionCallArgsArray.push_back(ConstantStruct::get(
1012  EmitFunctionCallArgsTy,
1013  {Builder.getInt32(j),
1014  Options.FunctionNamesInData
1016  : Constant::getNullValue(Builder.getInt8PtrTy()),
1017  Builder.getInt32(FuncChecksum),
1018  Builder.getInt8(Options.UseCfgChecksum),
1019  Builder.getInt32(CfgChecksum)}));
1020 
1021  GlobalVariable *GV = CountersBySP[j].first;
1022  unsigned Arcs = cast<ArrayType>(GV->getValueType())->getNumElements();
1023  EmitArcsCallArgsArray.push_back(ConstantStruct::get(
1024  EmitArcsCallArgsTy,
1026  GV->getValueType(), GV, TwoZero32s)}));
1027  }
1028  // Create global arrays for the two emit calls.
1029  int CountersSize = CountersBySP.size();
1030  assert(CountersSize == (int)EmitFunctionCallArgsArray.size() &&
1031  "Mismatched array size!");
1032  assert(CountersSize == (int)EmitArcsCallArgsArray.size() &&
1033  "Mismatched array size!");
1034  auto *EmitFunctionCallArgsArrayTy =
1035  ArrayType::get(EmitFunctionCallArgsTy, CountersSize);
1036  auto *EmitFunctionCallArgsArrayGV = new GlobalVariable(
1037  *M, EmitFunctionCallArgsArrayTy, /*isConstant*/ true,
1039  ConstantArray::get(EmitFunctionCallArgsArrayTy,
1040  EmitFunctionCallArgsArray),
1041  Twine("__llvm_internal_gcov_emit_function_args.") + Twine(i));
1042  auto *EmitArcsCallArgsArrayTy =
1043  ArrayType::get(EmitArcsCallArgsTy, CountersSize);
1044  EmitFunctionCallArgsArrayGV->setUnnamedAddr(
1046  auto *EmitArcsCallArgsArrayGV = new GlobalVariable(
1047  *M, EmitArcsCallArgsArrayTy, /*isConstant*/ true,
1049  ConstantArray::get(EmitArcsCallArgsArrayTy, EmitArcsCallArgsArray),
1050  Twine("__llvm_internal_gcov_emit_arcs_args.") + Twine(i));
1051  EmitArcsCallArgsArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1052 
1053  FileInfos.push_back(ConstantStruct::get(
1054  FileInfoTy,
1055  {StartFileCallArgs, Builder.getInt32(CountersSize),
1056  ConstantExpr::getInBoundsGetElementPtr(EmitFunctionCallArgsArrayTy,
1057  EmitFunctionCallArgsArrayGV,
1058  TwoZero32s),
1060  EmitArcsCallArgsArrayTy, EmitArcsCallArgsArrayGV, TwoZero32s)}));
1061  }
1062 
1063  // If we didn't find anything to actually emit, bail on out.
1064  if (FileInfos.empty()) {
1065  Builder.CreateRetVoid();
1066  return WriteoutF;
1067  }
1068 
1069  // To simplify code, we cap the number of file infos we write out to fit
1070  // easily in a 32-bit signed integer. This gives consistent behavior between
1071  // 32-bit and 64-bit systems without requiring (potentially very slow) 64-bit
1072  // operations on 32-bit systems. It also seems unreasonable to try to handle
1073  // more than 2 billion files.
1074  if ((int64_t)FileInfos.size() > (int64_t)INT_MAX)
1075  FileInfos.resize(INT_MAX);
1076 
1077  // Create a global for the entire data structure so we can walk it more
1078  // easily.
1079  auto *FileInfoArrayTy = ArrayType::get(FileInfoTy, FileInfos.size());
1080  auto *FileInfoArrayGV = new GlobalVariable(
1081  *M, FileInfoArrayTy, /*isConstant*/ true, GlobalValue::InternalLinkage,
1082  ConstantArray::get(FileInfoArrayTy, FileInfos),
1083  "__llvm_internal_gcov_emit_file_info");
1084  FileInfoArrayGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
1085 
1086  // Create the CFG for walking this data structure.
1087  auto *FileLoopHeader =
1088  BasicBlock::Create(*Ctx, "file.loop.header", WriteoutF);
1089  auto *CounterLoopHeader =
1090  BasicBlock::Create(*Ctx, "counter.loop.header", WriteoutF);
1091  auto *FileLoopLatch = BasicBlock::Create(*Ctx, "file.loop.latch", WriteoutF);
1092  auto *ExitBB = BasicBlock::Create(*Ctx, "exit", WriteoutF);
1093 
1094  // We always have at least one file, so just branch to the header.
1095  Builder.CreateBr(FileLoopHeader);
1096 
1097  // The index into the files structure is our loop induction variable.
1098  Builder.SetInsertPoint(FileLoopHeader);
1099  PHINode *IV =
1100  Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1101  IV->addIncoming(Builder.getInt32(0), BB);
1102  auto *FileInfoPtr = Builder.CreateInBoundsGEP(
1103  FileInfoArrayTy, FileInfoArrayGV, {Builder.getInt32(0), IV});
1104  auto *StartFileCallArgsPtr =
1105  Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 0);
1106  auto *StartFileCall = Builder.CreateCall(
1107  StartFile,
1108  {Builder.CreateLoad(StartFileCallArgsTy->getElementType(0),
1109  Builder.CreateStructGEP(StartFileCallArgsTy,
1110  StartFileCallArgsPtr, 0)),
1111  Builder.CreateLoad(StartFileCallArgsTy->getElementType(1),
1112  Builder.CreateStructGEP(StartFileCallArgsTy,
1113  StartFileCallArgsPtr, 1)),
1114  Builder.CreateLoad(StartFileCallArgsTy->getElementType(2),
1115  Builder.CreateStructGEP(StartFileCallArgsTy,
1116  StartFileCallArgsPtr, 2))});
1117  if (auto AK = TLI->getExtAttrForI32Param(false))
1118  StartFileCall->addParamAttr(2, AK);
1119  auto *NumCounters =
1120  Builder.CreateLoad(FileInfoTy->getElementType(1),
1121  Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 1));
1122  auto *EmitFunctionCallArgsArray =
1123  Builder.CreateLoad(FileInfoTy->getElementType(2),
1124  Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 2));
1125  auto *EmitArcsCallArgsArray =
1126  Builder.CreateLoad(FileInfoTy->getElementType(3),
1127  Builder.CreateStructGEP(FileInfoTy, FileInfoPtr, 3));
1128  auto *EnterCounterLoopCond =
1129  Builder.CreateICmpSLT(Builder.getInt32(0), NumCounters);
1130  Builder.CreateCondBr(EnterCounterLoopCond, CounterLoopHeader, FileLoopLatch);
1131 
1132  Builder.SetInsertPoint(CounterLoopHeader);
1133  auto *JV = Builder.CreatePHI(Builder.getInt32Ty(), /*NumReservedValues*/ 2);
1134  JV->addIncoming(Builder.getInt32(0), FileLoopHeader);
1135  auto *EmitFunctionCallArgsPtr = Builder.CreateInBoundsGEP(
1136  EmitFunctionCallArgsTy, EmitFunctionCallArgsArray, JV);
1137  auto *EmitFunctionCall = Builder.CreateCall(
1138  EmitFunction,
1139  {Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(0),
1140  Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1141  EmitFunctionCallArgsPtr, 0)),
1142  Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(1),
1143  Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1144  EmitFunctionCallArgsPtr, 1)),
1145  Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(2),
1146  Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1147  EmitFunctionCallArgsPtr, 2)),
1148  Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(3),
1149  Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1150  EmitFunctionCallArgsPtr, 3)),
1151  Builder.CreateLoad(EmitFunctionCallArgsTy->getElementType(4),
1152  Builder.CreateStructGEP(EmitFunctionCallArgsTy,
1153  EmitFunctionCallArgsPtr,
1154  4))});
1155  if (auto AK = TLI->getExtAttrForI32Param(false)) {
1156  EmitFunctionCall->addParamAttr(0, AK);
1157  EmitFunctionCall->addParamAttr(2, AK);
1158  EmitFunctionCall->addParamAttr(3, AK);
1159  EmitFunctionCall->addParamAttr(4, AK);
1160  }
1161  auto *EmitArcsCallArgsPtr =
1162  Builder.CreateInBoundsGEP(EmitArcsCallArgsTy, EmitArcsCallArgsArray, JV);
1163  auto *EmitArcsCall = Builder.CreateCall(
1164  EmitArcs,
1165  {Builder.CreateLoad(
1166  EmitArcsCallArgsTy->getElementType(0),
1167  Builder.CreateStructGEP(EmitArcsCallArgsTy, EmitArcsCallArgsPtr, 0)),
1168  Builder.CreateLoad(EmitArcsCallArgsTy->getElementType(1),
1169  Builder.CreateStructGEP(EmitArcsCallArgsTy,
1170  EmitArcsCallArgsPtr, 1))});
1171  if (auto AK = TLI->getExtAttrForI32Param(false))
1172  EmitArcsCall->addParamAttr(0, AK);
1173  auto *NextJV = Builder.CreateAdd(JV, Builder.getInt32(1));
1174  auto *CounterLoopCond = Builder.CreateICmpSLT(NextJV, NumCounters);
1175  Builder.CreateCondBr(CounterLoopCond, CounterLoopHeader, FileLoopLatch);
1176  JV->addIncoming(NextJV, CounterLoopHeader);
1177 
1178  Builder.SetInsertPoint(FileLoopLatch);
1179  Builder.CreateCall(SummaryInfo, {});
1180  Builder.CreateCall(EndFile, {});
1181  auto *NextIV = Builder.CreateAdd(IV, Builder.getInt32(1));
1182  auto *FileLoopCond =
1183  Builder.CreateICmpSLT(NextIV, Builder.getInt32(FileInfos.size()));
1184  Builder.CreateCondBr(FileLoopCond, FileLoopHeader, ExitBB);
1185  IV->addIncoming(NextIV, FileLoopLatch);
1186 
1187  Builder.SetInsertPoint(ExitBB);
1188  Builder.CreateRetVoid();
1189 
1190  return WriteoutF;
1191 }
1192 
1193 Function *GCOVProfiler::
1194 insertFlush(ArrayRef<std::pair<GlobalVariable*, MDNode*> > CountersBySP) {
1195  FunctionType *FTy = FunctionType::get(Type::getVoidTy(*Ctx), false);
1196  Function *FlushF = M->getFunction("__llvm_gcov_flush");
1197  if (!FlushF)
1199  "__llvm_gcov_flush", M);
1200  else
1203  FlushF->addFnAttr(Attribute::NoInline);
1204  if (Options.NoRedZone)
1205  FlushF->addFnAttr(Attribute::NoRedZone);
1206 
1207  BasicBlock *Entry = BasicBlock::Create(*Ctx, "entry", FlushF);
1208 
1209  // Write out the current counters.
1210  Function *WriteoutF = M->getFunction("__llvm_gcov_writeout");
1211  assert(WriteoutF && "Need to create the writeout function first!");
1212 
1213  IRBuilder<> Builder(Entry);
1214  Builder.CreateCall(WriteoutF, {});
1215 
1216  // Zero out the counters.
1217  for (const auto &I : CountersBySP) {
1218  GlobalVariable *GV = I.first;
1220  Builder.CreateStore(Null, GV);
1221  }
1222 
1223  Type *RetTy = FlushF->getReturnType();
1224  if (RetTy == Type::getVoidTy(*Ctx))
1225  Builder.CreateRetVoid();
1226  else if (RetTy->isIntegerTy())
1227  // Used if __llvm_gcov_flush was implicitly declared.
1228  Builder.CreateRet(ConstantInt::get(RetTy, 0));
1229  else
1230  report_fatal_error("invalid return type for __llvm_gcov_flush");
1231 
1232  return FlushF;
1233 }
static StringRef getFunctionName(TargetLowering::CallLoweringInfo &CLI)
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
Definition: IRBuilder.h:1827
This routine provides some synthesis utilities to produce sequences of values.
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional &#39;br Cond, TrueDest, FalseDest&#39; instruction.
Definition: IRBuilder.h:977
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1082
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:777
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Type * getElementType(unsigned N) const
Definition: DerivedTypes.h:351
StringMapEntry - This is used to represent one value that is inserted into a StringMap.
Definition: StringMap.h:158
ModulePass * createGCOVProfilerPass(const GCOVOptions &Options=GCOVOptions::getDefault())
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve &#39;CreateLoad(Ty, Ptr, "...")&#39; correctly, instead of converting the string to &#39;bool...
Definition: IRBuilder.h:1669
static cl::opt< bool > DefaultExitBlockBeforeBody("gcov-exit-block-before-body", cl::init(false), cl::Hidden)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
static GCOVOptions getDefault()
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
Definition: DerivedTypes.h:170
size_t find(char C, size_t From=0) const
find - Search for the first character C in the string.
Definition: SmallString.h:146
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2278
static SmallString< 128 > getFilename(const DISubprogram *SP)
Extract a filename for a DISubprogram.
This class represents a function call, abstracting a target machine&#39;s calling convention.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:637
std::error_code current_path(SmallVectorImpl< char > &result)
Get the current path.
unsigned getLine() const
Definition: DebugLoc.cpp:25
uint64_t getDWOId() const
A debug info location.
Definition: DebugLoc.h:33
Metadata node.
Definition: Metadata.h:872
F(f)
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1077
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:181
static PointerType * getInt64PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:236
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1065
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:318
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:273
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition: IRBuilder.h:395
Attribute::AttrKind getExtAttrForI32Param(bool Signed=true) const
Returns extension attribute kind to be used for i32 parameters corresponding to C-level int or unsign...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:455
A tuple of MDNodes.
Definition: Metadata.h:1334
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
IntegerType * getInt64Ty()
Fetch the type representing a 64-bit integer.
Definition: IRBuilder.h:400
bool isImplicitCode() const
Check if the DebugLoc corresponds to an implicit code.
Definition: DebugLoc.cpp:58
Class to represent struct types.
Definition: DerivedTypes.h:238
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:245
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:659
ReturnInst * CreateRet(Value *V)
Create a &#39;ret <val>&#39; instruction.
Definition: IRBuilder.h:952
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:197
unsigned getNumOperands() const
Definition: Metadata.cpp:1078
static bool isUsingScopeBasedEH(Function &F)
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1211
DISubprogram * getDISubprogram(const MDNode *Scope)
Find subprogram that is enclosing this scope.
Definition: DebugInfo.cpp:43
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
StringRef getFilename() const
Type * getVoidTy()
Fetch the type representing void.
Definition: IRBuilder.h:428
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch, catchpad/ret, and cleanuppad/ret.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1698
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:266
Subprogram description.
Class to represent function types.
Definition: DerivedTypes.h:108
This file provides the interface for the GCOV style profiler pass.
Class to represent array types.
Definition: DerivedTypes.h:408
NamedMDNode * getNamedMetadata(const Twine &Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:250
GCOVBlock - Collects block information.
Definition: GCOV.h:313
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:151
hash_code hash_value(const APFloat &Arg)
See friend declarations above.
Definition: APFloat.cpp:4510
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:743
iterator begin()
Definition: Function.h:691
static void addEdge(SmallVectorImpl< LazyCallGraph::Edge > &Edges, DenseMap< LazyCallGraph::Node *, int > &EdgeIndexMap, LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Definition: IRBuilder.h:132
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
StringRef getString() const
Definition: Metadata.cpp:463
const BasicBlock & getEntryBlock() const
Definition: Function.h:675
std::error_code real_path(const Twine &path, SmallVectorImpl< char > &output, bool expand_tilde=false)
Collapse all .
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
Type * getReturnType() const
Returns the type of the ret val.
Definition: Function.h:168
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:135
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
iterator_range< iterator > functions()
Definition: Module.h:610
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
LLVM_NODISCARD AttributeList addParamAttribute(LLVMContext &C, unsigned ArgNo, Attribute::AttrKind Kind) const
Add an argument attribute to the list.
Definition: Attributes.h:413
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:63
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1525
This is an important base class in LLVM.
Definition: Constant.h:41
StringRef getKey() const
Definition: StringMap.h:162
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:112
INITIALIZE_PASS_BEGIN(GCOVProfilerLegacyPass, "insert-gcov-profiling", "Insert instrumentation for GCOV profiling", false, false) INITIALIZE_PASS_END(GCOVProfilerLegacyPass
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
Definition: Type.cpp:165
constexpr double e
Definition: MathExtras.h:57
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:301
static Constant * get(StructType *T, ArrayRef< Constant *> V)
Definition: Constants.cpp:1126
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:115
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:99
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:360
MDNode * getScope() const
Definition: DebugLoc.cpp:35
static void write(bool isBE, void *P, T V)
StringRef getDirectory() const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
size_t size() const
Definition: SmallVector.h:52
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:433
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:224
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
raw_ostream & write(unsigned char C)
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1114
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition: IRBuilder.h:2411
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
Definition: InstrTypes.h:1415
Iterator for intrusive lists based on ilist_node.
static bool functionHasLines(Function &F)
FileType
Defines the file type this file represents.
Definition: InterfaceFile.h:57
StringRef getName() const
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition: Path.cpp:480
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:718
void initializeGCOVProfilerLegacyPassPass(PassRegistry &)
bool isValid(std::string &Error) const
isValid - returns the error encountered during regex compilation, if any.
Definition: Regex.cpp:68
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:355
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:704
void appendToGlobalCtors(Module &M, Function *F, int Priority, Constant *Data=nullptr)
Append F to the list of global ctors of module M with the given Priority.
Definition: ModuleUtils.cpp:64
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:124
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
Definition: Module.cpp:143
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:454
Constant * CreateGlobalStringPtr(StringRef Str, const Twine &Name="", unsigned AddressSpace=0)
Same as CreateGlobalString, but return a pointer with "i8*" type instead of a pointer to array of i8...
Definition: IRBuilder.h:1992
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:174
amdgpu Simplify well known AMD library false FunctionCallee Callee
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition: IRBuilder.h:385
static bool shouldKeepInEntry(BasicBlock::iterator It)
static cl::opt< std::string > DefaultGCOVVersion("default-gcov-version", cl::init("402*"), cl::Hidden, cl::ValueRequired)
ReturnInst * CreateRetVoid()
Create a &#39;ret void&#39; instruction.
Definition: IRBuilder.h:947
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
GCOVFunction - Collects function information.
Definition: GCOV.h:276
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:397
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:219
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:588
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:180
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
static Constant * getInBoundsGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant *> IdxList)
Create an "inbounds" getelementptr.
Definition: Constants.h:1181
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:222
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
Definition: Type.cpp:587
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Type * getValueType() const
Definition: GlobalValue.h:279
uint32_t Size
Definition: Profile.cpp:46
Rename collisions when linking (static functions).
Definition: GlobalValue.h:55
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2419
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:414
void close()
Manually flush the stream and close the file.
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:143
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:516
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:74
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1484
succ_range successors(Instruction *I)
Definition: CFG.h:259
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional &#39;br label X&#39; instruction.
Definition: IRBuilder.h:971
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:441
Value * CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, const Twine &Name="")
Definition: IRBuilder.h:1981
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.h:229
ConstantInt * getInt8(uint8_t C)
Get a constant 8-bit value.
Definition: IRBuilder.h:345
print Print MemDeps of function
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
inst_range instructions(Function *F)
Definition: InstIterator.h:133
A single uniqued string.
Definition: Metadata.h:604
A container for analyses that lazily runs them and caches their results.
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1083
#define LLVM_DEBUG(X)
Definition: Debug.h:122
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1048
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:178
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:1045
void resize(size_type N)
Definition: SmallVector.h:344