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