clang  16.0.0git
CoverageMappingGen.cpp
Go to the documentation of this file.
1 //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
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 // Instrumentation-based code coverage mapping generator
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CoverageMappingGen.h"
14 #include "CodeGenFunction.h"
15 #include "clang/AST/StmtVisitor.h"
16 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Lex/Lexer.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
24 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25 #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
26 #include "llvm/ProfileData/InstrProfReader.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/Path.h"
29 
30 // This selects the coverage mapping format defined when `InstrProfData.inc`
31 // is textually included.
32 #define COVMAP_V3
33 
34 static llvm::cl::opt<bool> EmptyLineCommentCoverage(
35  "emptyline-comment-coverage",
36  llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
37  "disable it on test)"),
38  llvm::cl::init(true), llvm::cl::Hidden);
39 
40 using namespace clang;
41 using namespace CodeGen;
42 using namespace llvm::coverage;
43 
46  CoverageSourceInfo *CoverageInfo =
48  PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
50  PP.addCommentHandler(CoverageInfo);
51  PP.setEmptylineHandler(CoverageInfo);
52  PP.setPreprocessToken(true);
53  PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
54  // Update previous token location.
55  CoverageInfo->PrevTokLoc = Tok.getLocation();
56  if (Tok.getKind() != clang::tok::eod)
57  CoverageInfo->updateNextTokLoc(Tok.getLocation());
58  });
59  }
60  return CoverageInfo;
61 }
62 
64  SkippedRange::Kind RangeKind) {
65  if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
66  PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
67  SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
68  Range.getBegin()))
69  SkippedRanges.back().Range.setEnd(Range.getEnd());
70  else
71  SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
72 }
73 
75  AddSkippedRange(Range, SkippedRange::PPIfElse);
76 }
77 
79  AddSkippedRange(Range, SkippedRange::EmptyLine);
80 }
81 
83  AddSkippedRange(Range, SkippedRange::Comment);
84  return false;
85 }
86 
88  if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
89  SkippedRanges.back().NextTokLoc = Loc;
90 }
91 
92 namespace {
93 
94 /// A region of source code that can be mapped to a counter.
95 class SourceMappingRegion {
96  /// Primary Counter that is also used for Branch Regions for "True" branches.
97  Counter Count;
98 
99  /// Secondary Counter used for Branch Regions for "False" branches.
100  Optional<Counter> FalseCount;
101 
102  /// The region's starting location.
103  Optional<SourceLocation> LocStart;
104 
105  /// The region's ending location.
107 
108  /// Whether this region is a gap region. The count from a gap region is set
109  /// as the line execution count if there are no other regions on the line.
110  bool GapRegion;
111 
112 public:
113  SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
114  Optional<SourceLocation> LocEnd, bool GapRegion = false)
115  : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {
116  }
117 
118  SourceMappingRegion(Counter Count, Optional<Counter> FalseCount,
119  Optional<SourceLocation> LocStart,
120  Optional<SourceLocation> LocEnd, bool GapRegion = false)
121  : Count(Count), FalseCount(FalseCount), LocStart(LocStart),
122  LocEnd(LocEnd), GapRegion(GapRegion) {}
123 
124  const Counter &getCounter() const { return Count; }
125 
126  const Counter &getFalseCounter() const {
127  assert(FalseCount && "Region has no alternate counter");
128  return *FalseCount;
129  }
130 
131  void setCounter(Counter C) { Count = C; }
132 
133  bool hasStartLoc() const { return LocStart.has_value(); }
134 
135  void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
136 
137  SourceLocation getBeginLoc() const {
138  assert(LocStart && "Region has no start location");
139  return *LocStart;
140  }
141 
142  bool hasEndLoc() const { return LocEnd.has_value(); }
143 
144  void setEndLoc(SourceLocation Loc) {
145  assert(Loc.isValid() && "Setting an invalid end location");
146  LocEnd = Loc;
147  }
148 
149  SourceLocation getEndLoc() const {
150  assert(LocEnd && "Region has no end location");
151  return *LocEnd;
152  }
153 
154  bool isGap() const { return GapRegion; }
155 
156  void setGap(bool Gap) { GapRegion = Gap; }
157 
158  bool isBranch() const { return FalseCount.has_value(); }
159 };
160 
161 /// Spelling locations for the start and end of a source region.
162 struct SpellingRegion {
163  /// The line where the region starts.
164  unsigned LineStart;
165 
166  /// The column where the region starts.
167  unsigned ColumnStart;
168 
169  /// The line where the region ends.
170  unsigned LineEnd;
171 
172  /// The column where the region ends.
173  unsigned ColumnEnd;
174 
175  SpellingRegion(SourceManager &SM, SourceLocation LocStart,
176  SourceLocation LocEnd) {
177  LineStart = SM.getSpellingLineNumber(LocStart);
178  ColumnStart = SM.getSpellingColumnNumber(LocStart);
179  LineEnd = SM.getSpellingLineNumber(LocEnd);
180  ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
181  }
182 
183  SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
184  : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
185 
186  /// Check if the start and end locations appear in source order, i.e
187  /// top->bottom, left->right.
188  bool isInSourceOrder() const {
189  return (LineStart < LineEnd) ||
190  (LineStart == LineEnd && ColumnStart <= ColumnEnd);
191  }
192 };
193 
194 /// Provides the common functionality for the different
195 /// coverage mapping region builders.
196 class CoverageMappingBuilder {
197 public:
199  SourceManager &SM;
200  const LangOptions &LangOpts;
201 
202 private:
203  /// Map of clang's FileIDs to IDs used for coverage mapping.
204  llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
205  FileIDMapping;
206 
207 public:
208  /// The coverage mapping regions for this function
210  /// The source mapping regions for this function.
211  std::vector<SourceMappingRegion> SourceRegions;
212 
213  /// A set of regions which can be used as a filter.
214  ///
215  /// It is produced by emitExpansionRegions() and is used in
216  /// emitSourceRegions() to suppress producing code regions if
217  /// the same area is covered by expansion regions.
218  typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
219  SourceRegionFilter;
220 
221  CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
222  const LangOptions &LangOpts)
223  : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
224 
225  /// Return the precise end location for the given token.
226  SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
227  // We avoid getLocForEndOfToken here, because it doesn't do what we want for
228  // macro locations, which we just treat as expanded files.
229  unsigned TokLen =
230  Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
231  return Loc.getLocWithOffset(TokLen);
232  }
233 
234  /// Return the start location of an included file or expanded macro.
235  SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
236  if (Loc.isMacroID())
237  return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
238  return SM.getLocForStartOfFile(SM.getFileID(Loc));
239  }
240 
241  /// Return the end location of an included file or expanded macro.
242  SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
243  if (Loc.isMacroID())
244  return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
245  SM.getFileOffset(Loc));
246  return SM.getLocForEndOfFile(SM.getFileID(Loc));
247  }
248 
249  /// Find out where the current file is included or macro is expanded.
250  SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
251  return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
252  : SM.getIncludeLoc(SM.getFileID(Loc));
253  }
254 
255  /// Return true if \c Loc is a location in a built-in macro.
256  bool isInBuiltin(SourceLocation Loc) {
257  return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
258  }
259 
260  /// Check whether \c Loc is included or expanded from \c Parent.
261  bool isNestedIn(SourceLocation Loc, FileID Parent) {
262  do {
263  Loc = getIncludeOrExpansionLoc(Loc);
264  if (Loc.isInvalid())
265  return false;
266  } while (!SM.isInFileID(Loc, Parent));
267  return true;
268  }
269 
270  /// Get the start of \c S ignoring macro arguments and builtin macros.
271  SourceLocation getStart(const Stmt *S) {
272  SourceLocation Loc = S->getBeginLoc();
273  while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
274  Loc = SM.getImmediateExpansionRange(Loc).getBegin();
275  return Loc;
276  }
277 
278  /// Get the end of \c S ignoring macro arguments and builtin macros.
279  SourceLocation getEnd(const Stmt *S) {
280  SourceLocation Loc = S->getEndLoc();
281  while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
282  Loc = SM.getImmediateExpansionRange(Loc).getBegin();
283  return getPreciseTokenLocEnd(Loc);
284  }
285 
286  /// Find the set of files we have regions for and assign IDs
287  ///
288  /// Fills \c Mapping with the virtual file mapping needed to write out
289  /// coverage and collects the necessary file information to emit source and
290  /// expansion regions.
291  void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
292  FileIDMapping.clear();
293 
294  llvm::SmallSet<FileID, 8> Visited;
296  for (const auto &Region : SourceRegions) {
297  SourceLocation Loc = Region.getBeginLoc();
298  FileID File = SM.getFileID(Loc);
299  if (!Visited.insert(File).second)
300  continue;
301 
302  // Do not map FileID's associated with system headers.
303  if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
304  continue;
305 
306  unsigned Depth = 0;
307  for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
308  Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
309  ++Depth;
310  FileLocs.push_back(std::make_pair(Loc, Depth));
311  }
312  llvm::stable_sort(FileLocs, llvm::less_second());
313 
314  for (const auto &FL : FileLocs) {
315  SourceLocation Loc = FL.first;
316  FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
317  auto Entry = SM.getFileEntryForID(SpellingFile);
318  if (!Entry)
319  continue;
320 
321  FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
322  Mapping.push_back(CVM.getFileID(Entry));
323  }
324  }
325 
326  /// Get the coverage mapping file ID for \c Loc.
327  ///
328  /// If such file id doesn't exist, return std::nullopt.
329  Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
330  auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
331  if (Mapping != FileIDMapping.end())
332  return Mapping->second.first;
333  return std::nullopt;
334  }
335 
336  /// This shrinks the skipped range if it spans a line that contains a
337  /// non-comment token. If shrinking the skipped range would make it empty,
338  /// this returns std::nullopt.
339  /// Note this function can potentially be expensive because
340  /// getSpellingLineNumber uses getLineNumber, which is expensive.
341  Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
342  SourceLocation LocStart,
343  SourceLocation LocEnd,
344  SourceLocation PrevTokLoc,
345  SourceLocation NextTokLoc) {
346  SpellingRegion SR{SM, LocStart, LocEnd};
347  SR.ColumnStart = 1;
348  if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
349  SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
350  SR.LineStart++;
351  if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
352  SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
353  SR.LineEnd--;
354  SR.ColumnEnd++;
355  }
356  if (SR.isInSourceOrder())
357  return SR;
358  return std::nullopt;
359  }
360 
361  /// Gather all the regions that were skipped by the preprocessor
362  /// using the constructs like #if or comments.
363  void gatherSkippedRegions() {
364  /// An array of the minimum lineStarts and the maximum lineEnds
365  /// for mapping regions from the appropriate source files.
367  FileLineRanges.resize(
368  FileIDMapping.size(),
369  std::make_pair(std::numeric_limits<unsigned>::max(), 0));
370  for (const auto &R : MappingRegions) {
371  FileLineRanges[R.FileID].first =
372  std::min(FileLineRanges[R.FileID].first, R.LineStart);
373  FileLineRanges[R.FileID].second =
374  std::max(FileLineRanges[R.FileID].second, R.LineEnd);
375  }
376 
377  auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
378  for (auto &I : SkippedRanges) {
379  SourceRange Range = I.Range;
380  auto LocStart = Range.getBegin();
381  auto LocEnd = Range.getEnd();
382  assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
383  "region spans multiple files");
384 
385  auto CovFileID = getCoverageFileID(LocStart);
386  if (!CovFileID)
387  continue;
389  if (I.isComment())
390  SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc,
391  I.NextTokLoc);
392  else if (I.isPPIfElse() || I.isEmptyLine())
393  SR = {SM, LocStart, LocEnd};
394 
395  if (!SR)
396  continue;
397  auto Region = CounterMappingRegion::makeSkipped(
398  *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
399  SR->ColumnEnd);
400  // Make sure that we only collect the regions that are inside
401  // the source code of this function.
402  if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
403  Region.LineEnd <= FileLineRanges[*CovFileID].second)
404  MappingRegions.push_back(Region);
405  }
406  }
407 
408  /// Generate the coverage counter mapping regions from collected
409  /// source regions.
410  void emitSourceRegions(const SourceRegionFilter &Filter) {
411  for (const auto &Region : SourceRegions) {
412  assert(Region.hasEndLoc() && "incomplete region");
413 
414  SourceLocation LocStart = Region.getBeginLoc();
415  assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
416 
417  // Ignore regions from system headers.
418  if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
419  continue;
420 
421  auto CovFileID = getCoverageFileID(LocStart);
422  // Ignore regions that don't have a file, such as builtin macros.
423  if (!CovFileID)
424  continue;
425 
426  SourceLocation LocEnd = Region.getEndLoc();
427  assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
428  "region spans multiple files");
429 
430  // Don't add code regions for the area covered by expansion regions.
431  // This not only suppresses redundant regions, but sometimes prevents
432  // creating regions with wrong counters if, for example, a statement's
433  // body ends at the end of a nested macro.
434  if (Filter.count(std::make_pair(LocStart, LocEnd)))
435  continue;
436 
437  // Find the spelling locations for the mapping region.
438  SpellingRegion SR{SM, LocStart, LocEnd};
439  assert(SR.isInSourceOrder() && "region start and end out of order");
440 
441  if (Region.isGap()) {
442  MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
443  Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
444  SR.LineEnd, SR.ColumnEnd));
445  } else if (Region.isBranch()) {
446  MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
447  Region.getCounter(), Region.getFalseCounter(), *CovFileID,
448  SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
449  } else {
450  MappingRegions.push_back(CounterMappingRegion::makeRegion(
451  Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
452  SR.LineEnd, SR.ColumnEnd));
453  }
454  }
455  }
456 
457  /// Generate expansion regions for each virtual file we've seen.
458  SourceRegionFilter emitExpansionRegions() {
459  SourceRegionFilter Filter;
460  for (const auto &FM : FileIDMapping) {
461  SourceLocation ExpandedLoc = FM.second.second;
462  SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
463  if (ParentLoc.isInvalid())
464  continue;
465 
466  auto ParentFileID = getCoverageFileID(ParentLoc);
467  if (!ParentFileID)
468  continue;
469  auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
470  assert(ExpandedFileID && "expansion in uncovered file");
471 
472  SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
473  assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
474  "region spans multiple files");
475  Filter.insert(std::make_pair(ParentLoc, LocEnd));
476 
477  SpellingRegion SR{SM, ParentLoc, LocEnd};
478  assert(SR.isInSourceOrder() && "region start and end out of order");
479  MappingRegions.push_back(CounterMappingRegion::makeExpansion(
480  *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
481  SR.LineEnd, SR.ColumnEnd));
482  }
483  return Filter;
484  }
485 };
486 
487 /// Creates unreachable coverage regions for the functions that
488 /// are not emitted.
489 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
490  EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
491  const LangOptions &LangOpts)
492  : CoverageMappingBuilder(CVM, SM, LangOpts) {}
493 
494  void VisitDecl(const Decl *D) {
495  if (!D->hasBody())
496  return;
497  auto Body = D->getBody();
498  SourceLocation Start = getStart(Body);
499  SourceLocation End = getEnd(Body);
500  if (!SM.isWrittenInSameFile(Start, End)) {
501  // Walk up to find the common ancestor.
502  // Correct the locations accordingly.
503  FileID StartFileID = SM.getFileID(Start);
504  FileID EndFileID = SM.getFileID(End);
505  while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
506  Start = getIncludeOrExpansionLoc(Start);
507  assert(Start.isValid() &&
508  "Declaration start location not nested within a known region");
509  StartFileID = SM.getFileID(Start);
510  }
511  while (StartFileID != EndFileID) {
512  End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
513  assert(End.isValid() &&
514  "Declaration end location not nested within a known region");
515  EndFileID = SM.getFileID(End);
516  }
517  }
518  SourceRegions.emplace_back(Counter(), Start, End);
519  }
520 
521  /// Write the mapping data to the output stream
522  void write(llvm::raw_ostream &OS) {
523  SmallVector<unsigned, 16> FileIDMapping;
524  gatherFileIDs(FileIDMapping);
525  emitSourceRegions(SourceRegionFilter());
526 
527  if (MappingRegions.empty())
528  return;
529 
530  CoverageMappingWriter Writer(FileIDMapping, std::nullopt, MappingRegions);
531  Writer.write(OS);
532  }
533 };
534 
535 /// A StmtVisitor that creates coverage mapping regions which map
536 /// from the source code locations to the PGO counters.
537 struct CounterCoverageMappingBuilder
538  : public CoverageMappingBuilder,
539  public ConstStmtVisitor<CounterCoverageMappingBuilder> {
540  /// The map of statements to count values.
541  llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
542 
543  /// A stack of currently live regions.
544  std::vector<SourceMappingRegion> RegionStack;
545 
546  CounterExpressionBuilder Builder;
547 
548  /// A location in the most recently visited file or macro.
549  ///
550  /// This is used to adjust the active source regions appropriately when
551  /// expressions cross file or macro boundaries.
552  SourceLocation MostRecentLocation;
553 
554  /// Whether the visitor at a terminate statement.
555  bool HasTerminateStmt = false;
556 
557  /// Gap region counter after terminate statement.
558  Counter GapRegionCounter;
559 
560  /// Return a counter for the subtraction of \c RHS from \c LHS
561  Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
562  return Builder.subtract(LHS, RHS, Simplify);
563  }
564 
565  /// Return a counter for the sum of \c LHS and \c RHS.
566  Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
567  return Builder.add(LHS, RHS, Simplify);
568  }
569 
570  Counter addCounters(Counter C1, Counter C2, Counter C3,
571  bool Simplify = true) {
572  return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
573  }
574 
575  /// Return the region counter for the given statement.
576  ///
577  /// This should only be called on statements that have a dedicated counter.
578  Counter getRegionCounter(const Stmt *S) {
579  return Counter::getCounter(CounterMap[S]);
580  }
581 
582  /// Push a region onto the stack.
583  ///
584  /// Returns the index on the stack where the region was pushed. This can be
585  /// used with popRegions to exit a "scope", ending the region that was pushed.
586  size_t pushRegion(Counter Count,
587  Optional<SourceLocation> StartLoc = std::nullopt,
588  Optional<SourceLocation> EndLoc = std::nullopt,
589  Optional<Counter> FalseCount = std::nullopt) {
590 
591  if (StartLoc && !FalseCount) {
592  MostRecentLocation = *StartLoc;
593  }
594 
595  RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
596 
597  return RegionStack.size() - 1;
598  }
599 
600  size_t locationDepth(SourceLocation Loc) {
601  size_t Depth = 0;
602  while (Loc.isValid()) {
603  Loc = getIncludeOrExpansionLoc(Loc);
604  Depth++;
605  }
606  return Depth;
607  }
608 
609  /// Pop regions from the stack into the function's list of regions.
610  ///
611  /// Adds all regions from \c ParentIndex to the top of the stack to the
612  /// function's \c SourceRegions.
613  void popRegions(size_t ParentIndex) {
614  assert(RegionStack.size() >= ParentIndex && "parent not in stack");
615  while (RegionStack.size() > ParentIndex) {
616  SourceMappingRegion &Region = RegionStack.back();
617  if (Region.hasStartLoc()) {
618  SourceLocation StartLoc = Region.getBeginLoc();
619  SourceLocation EndLoc = Region.hasEndLoc()
620  ? Region.getEndLoc()
621  : RegionStack[ParentIndex].getEndLoc();
622  bool isBranch = Region.isBranch();
623  size_t StartDepth = locationDepth(StartLoc);
624  size_t EndDepth = locationDepth(EndLoc);
625  while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
626  bool UnnestStart = StartDepth >= EndDepth;
627  bool UnnestEnd = EndDepth >= StartDepth;
628  if (UnnestEnd) {
629  // The region ends in a nested file or macro expansion. If the
630  // region is not a branch region, create a separate region for each
631  // expansion, and for all regions, update the EndLoc. Branch
632  // regions should not be split in order to keep a straightforward
633  // correspondance between the region and its associated branch
634  // condition, even if the condition spans multiple depths.
635  SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
636  assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
637 
638  if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
639  SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
640  EndLoc);
641 
642  EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
643  if (EndLoc.isInvalid())
644  llvm::report_fatal_error(
645  "File exit not handled before popRegions");
646  EndDepth--;
647  }
648  if (UnnestStart) {
649  // The region ends in a nested file or macro expansion. If the
650  // region is not a branch region, create a separate region for each
651  // expansion, and for all regions, update the StartLoc. Branch
652  // regions should not be split in order to keep a straightforward
653  // correspondance between the region and its associated branch
654  // condition, even if the condition spans multiple depths.
655  SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
656  assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
657 
658  if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
659  SourceRegions.emplace_back(Region.getCounter(), StartLoc,
660  NestedLoc);
661 
662  StartLoc = getIncludeOrExpansionLoc(StartLoc);
663  if (StartLoc.isInvalid())
664  llvm::report_fatal_error(
665  "File exit not handled before popRegions");
666  StartDepth--;
667  }
668  }
669  Region.setStartLoc(StartLoc);
670  Region.setEndLoc(EndLoc);
671 
672  if (!isBranch) {
673  MostRecentLocation = EndLoc;
674  // If this region happens to span an entire expansion, we need to
675  // make sure we don't overlap the parent region with it.
676  if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
677  EndLoc == getEndOfFileOrMacro(EndLoc))
678  MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
679  }
680 
681  assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
682  assert(SpellingRegion(SM, Region).isInSourceOrder());
683  SourceRegions.push_back(Region);
684  }
685  RegionStack.pop_back();
686  }
687  }
688 
689  /// Return the currently active region.
690  SourceMappingRegion &getRegion() {
691  assert(!RegionStack.empty() && "statement has no region");
692  return RegionStack.back();
693  }
694 
695  /// Propagate counts through the children of \p S if \p VisitChildren is true.
696  /// Otherwise, only emit a count for \p S itself.
697  Counter propagateCounts(Counter TopCount, const Stmt *S,
698  bool VisitChildren = true) {
699  SourceLocation StartLoc = getStart(S);
700  SourceLocation EndLoc = getEnd(S);
701  size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
702  if (VisitChildren)
703  Visit(S);
704  Counter ExitCount = getRegion().getCounter();
705  popRegions(Index);
706 
707  // The statement may be spanned by an expansion. Make sure we handle a file
708  // exit out of this expansion before moving to the next statement.
709  if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
710  MostRecentLocation = EndLoc;
711 
712  return ExitCount;
713  }
714 
715  /// Determine whether the given condition can be constant folded.
716  bool ConditionFoldsToBool(const Expr *Cond) {
717  Expr::EvalResult Result;
718  return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
719  }
720 
721  /// Create a Branch Region around an instrumentable condition for coverage
722  /// and add it to the function's SourceRegions. A branch region tracks a
723  /// "True" counter and a "False" counter for boolean expressions that
724  /// result in the generation of a branch.
725  void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) {
726  // Check for NULL conditions.
727  if (!C)
728  return;
729 
730  // Ensure we are an instrumentable condition (i.e. no "&&" or "||"). Push
731  // region onto RegionStack but immediately pop it (which adds it to the
732  // function's SourceRegions) because it doesn't apply to any other source
733  // code other than the Condition.
735  // If a condition can fold to true or false, the corresponding branch
736  // will be removed. Create a region with both counters hard-coded to
737  // zero. This allows us to visualize them in a special way.
738  // Alternatively, we can prevent any optimization done via
739  // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
740  // CodeGenFunction.c always returns false, but that is very heavy-handed.
741  if (ConditionFoldsToBool(C))
742  popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
743  Counter::getZero()));
744  else
745  // Otherwise, create a region with the True counter and False counter.
746  popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt));
747  }
748  }
749 
750  /// Create a Branch Region around a SwitchCase for code coverage
751  /// and add it to the function's SourceRegions.
752  void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
753  Counter FalseCnt) {
754  // Push region onto RegionStack but immediately pop it (which adds it to
755  // the function's SourceRegions) because it doesn't apply to any other
756  // source other than the SwitchCase.
757  popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
758  }
759 
760  /// Check whether a region with bounds \c StartLoc and \c EndLoc
761  /// is already added to \c SourceRegions.
762  bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
763  bool isBranch = false) {
764  return llvm::any_of(
765  llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) {
766  return Region.getBeginLoc() == StartLoc &&
767  Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
768  });
769  }
770 
771  /// Adjust the most recently visited location to \c EndLoc.
772  ///
773  /// This should be used after visiting any statements in non-source order.
774  void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
775  MostRecentLocation = EndLoc;
776  // The code region for a whole macro is created in handleFileExit() when
777  // it detects exiting of the virtual file of that macro. If we visited
778  // statements in non-source order, we might already have such a region
779  // added, for example, if a body of a loop is divided among multiple
780  // macros. Avoid adding duplicate regions in such case.
781  if (getRegion().hasEndLoc() &&
782  MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
783  isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
784  MostRecentLocation, getRegion().isBranch()))
785  MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
786  }
787 
788  /// Adjust regions and state when \c NewLoc exits a file.
789  ///
790  /// If moving from our most recently tracked location to \c NewLoc exits any
791  /// files, this adjusts our current region stack and creates the file regions
792  /// for the exited file.
793  void handleFileExit(SourceLocation NewLoc) {
794  if (NewLoc.isInvalid() ||
795  SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
796  return;
797 
798  // If NewLoc is not in a file that contains MostRecentLocation, walk up to
799  // find the common ancestor.
800  SourceLocation LCA = NewLoc;
801  FileID ParentFile = SM.getFileID(LCA);
802  while (!isNestedIn(MostRecentLocation, ParentFile)) {
803  LCA = getIncludeOrExpansionLoc(LCA);
804  if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
805  // Since there isn't a common ancestor, no file was exited. We just need
806  // to adjust our location to the new file.
807  MostRecentLocation = NewLoc;
808  return;
809  }
810  ParentFile = SM.getFileID(LCA);
811  }
812 
813  llvm::SmallSet<SourceLocation, 8> StartLocs;
814  Optional<Counter> ParentCounter;
815  for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
816  if (!I.hasStartLoc())
817  continue;
818  SourceLocation Loc = I.getBeginLoc();
819  if (!isNestedIn(Loc, ParentFile)) {
820  ParentCounter = I.getCounter();
821  break;
822  }
823 
824  while (!SM.isInFileID(Loc, ParentFile)) {
825  // The most nested region for each start location is the one with the
826  // correct count. We avoid creating redundant regions by stopping once
827  // we've seen this region.
828  if (StartLocs.insert(Loc).second) {
829  if (I.isBranch())
830  SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc,
831  getEndOfFileOrMacro(Loc), I.isBranch());
832  else
833  SourceRegions.emplace_back(I.getCounter(), Loc,
834  getEndOfFileOrMacro(Loc));
835  }
836  Loc = getIncludeOrExpansionLoc(Loc);
837  }
838  I.setStartLoc(getPreciseTokenLocEnd(Loc));
839  }
840 
841  if (ParentCounter) {
842  // If the file is contained completely by another region and doesn't
843  // immediately start its own region, the whole file gets a region
844  // corresponding to the parent.
845  SourceLocation Loc = MostRecentLocation;
846  while (isNestedIn(Loc, ParentFile)) {
847  SourceLocation FileStart = getStartOfFileOrMacro(Loc);
848  if (StartLocs.insert(FileStart).second) {
849  SourceRegions.emplace_back(*ParentCounter, FileStart,
850  getEndOfFileOrMacro(Loc));
851  assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
852  }
853  Loc = getIncludeOrExpansionLoc(Loc);
854  }
855  }
856 
857  MostRecentLocation = NewLoc;
858  }
859 
860  /// Ensure that \c S is included in the current region.
861  void extendRegion(const Stmt *S) {
862  SourceMappingRegion &Region = getRegion();
863  SourceLocation StartLoc = getStart(S);
864 
865  handleFileExit(StartLoc);
866  if (!Region.hasStartLoc())
867  Region.setStartLoc(StartLoc);
868  }
869 
870  /// Mark \c S as a terminator, starting a zero region.
871  void terminateRegion(const Stmt *S) {
872  extendRegion(S);
873  SourceMappingRegion &Region = getRegion();
874  SourceLocation EndLoc = getEnd(S);
875  if (!Region.hasEndLoc())
876  Region.setEndLoc(EndLoc);
877  pushRegion(Counter::getZero());
878  HasTerminateStmt = true;
879  }
880 
881  /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
882  Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
883  SourceLocation BeforeLoc) {
884  // If AfterLoc is in function-like macro, use the right parenthesis
885  // location.
886  if (AfterLoc.isMacroID()) {
887  FileID FID = SM.getFileID(AfterLoc);
888  const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
889  if (EI->isFunctionMacroExpansion())
890  AfterLoc = EI->getExpansionLocEnd();
891  }
892 
893  size_t StartDepth = locationDepth(AfterLoc);
894  size_t EndDepth = locationDepth(BeforeLoc);
895  while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
896  bool UnnestStart = StartDepth >= EndDepth;
897  bool UnnestEnd = EndDepth >= StartDepth;
898  if (UnnestEnd) {
899  assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
900  BeforeLoc));
901 
902  BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
903  assert(BeforeLoc.isValid());
904  EndDepth--;
905  }
906  if (UnnestStart) {
907  assert(SM.isWrittenInSameFile(AfterLoc,
908  getEndOfFileOrMacro(AfterLoc)));
909 
910  AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
911  assert(AfterLoc.isValid());
912  AfterLoc = getPreciseTokenLocEnd(AfterLoc);
913  assert(AfterLoc.isValid());
914  StartDepth--;
915  }
916  }
917  AfterLoc = getPreciseTokenLocEnd(AfterLoc);
918  // If the start and end locations of the gap are both within the same macro
919  // file, the range may not be in source order.
920  if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
921  return std::nullopt;
922  if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
923  !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
924  return std::nullopt;
925  return {{AfterLoc, BeforeLoc}};
926  }
927 
928  /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
929  void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
930  Counter Count) {
931  if (StartLoc == EndLoc)
932  return;
933  assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
934  handleFileExit(StartLoc);
935  size_t Index = pushRegion(Count, StartLoc, EndLoc);
936  getRegion().setGap(true);
937  handleFileExit(EndLoc);
938  popRegions(Index);
939  }
940 
941  /// Keep counts of breaks and continues inside loops.
942  struct BreakContinue {
943  Counter BreakCount;
944  Counter ContinueCount;
945  };
946  SmallVector<BreakContinue, 8> BreakContinueStack;
947 
948  CounterCoverageMappingBuilder(
950  llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
951  const LangOptions &LangOpts)
952  : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
953 
954  /// Write the mapping data to the output stream
955  void write(llvm::raw_ostream &OS) {
956  llvm::SmallVector<unsigned, 8> VirtualFileMapping;
957  gatherFileIDs(VirtualFileMapping);
958  SourceRegionFilter Filter = emitExpansionRegions();
959  emitSourceRegions(Filter);
960  gatherSkippedRegions();
961 
962  if (MappingRegions.empty())
963  return;
964 
965  CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
966  MappingRegions);
967  Writer.write(OS);
968  }
969 
970  void VisitStmt(const Stmt *S) {
971  if (S->getBeginLoc().isValid())
972  extendRegion(S);
973  const Stmt *LastStmt = nullptr;
974  bool SaveTerminateStmt = HasTerminateStmt;
975  HasTerminateStmt = false;
976  GapRegionCounter = Counter::getZero();
977  for (const Stmt *Child : S->children())
978  if (Child) {
979  // If last statement contains terminate statements, add a gap area
980  // between the two statements. Skipping attributed statements, because
981  // they don't have valid start location.
982  if (LastStmt && HasTerminateStmt && !isa<AttributedStmt>(Child)) {
983  auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
984  if (Gap)
985  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
986  GapRegionCounter);
987  SaveTerminateStmt = true;
988  HasTerminateStmt = false;
989  }
990  this->Visit(Child);
991  LastStmt = Child;
992  }
993  if (SaveTerminateStmt)
994  HasTerminateStmt = true;
995  handleFileExit(getEnd(S));
996  }
997 
998  void VisitDecl(const Decl *D) {
999  Stmt *Body = D->getBody();
1000 
1001  // Do not propagate region counts into system headers.
1002  if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1003  return;
1004 
1005  // Do not visit the artificial children nodes of defaulted methods. The
1006  // lexer may not be able to report back precise token end locations for
1007  // these children nodes (llvm.org/PR39822), and moreover users will not be
1008  // able to see coverage for them.
1009  bool Defaulted = false;
1010  if (auto *Method = dyn_cast<CXXMethodDecl>(D))
1011  Defaulted = Method->isDefaulted();
1012 
1013  propagateCounts(getRegionCounter(Body), Body,
1014  /*VisitChildren=*/!Defaulted);
1015  assert(RegionStack.empty() && "Regions entered but never exited");
1016  }
1017 
1018  void VisitReturnStmt(const ReturnStmt *S) {
1019  extendRegion(S);
1020  if (S->getRetValue())
1021  Visit(S->getRetValue());
1022  terminateRegion(S);
1023  }
1024 
1025  void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1026  extendRegion(S);
1027  Visit(S->getBody());
1028  }
1029 
1030  void VisitCoreturnStmt(const CoreturnStmt *S) {
1031  extendRegion(S);
1032  if (S->getOperand())
1033  Visit(S->getOperand());
1034  terminateRegion(S);
1035  }
1036 
1037  void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1038  extendRegion(E);
1039  if (E->getSubExpr())
1040  Visit(E->getSubExpr());
1041  terminateRegion(E);
1042  }
1043 
1044  void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1045 
1046  void VisitLabelStmt(const LabelStmt *S) {
1047  Counter LabelCount = getRegionCounter(S);
1048  SourceLocation Start = getStart(S);
1049  // We can't extendRegion here or we risk overlapping with our new region.
1050  handleFileExit(Start);
1051  pushRegion(LabelCount, Start);
1052  Visit(S->getSubStmt());
1053  }
1054 
1055  void VisitBreakStmt(const BreakStmt *S) {
1056  assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1057  BreakContinueStack.back().BreakCount = addCounters(
1058  BreakContinueStack.back().BreakCount, getRegion().getCounter());
1059  // FIXME: a break in a switch should terminate regions for all preceding
1060  // case statements, not just the most recent one.
1061  terminateRegion(S);
1062  }
1063 
1064  void VisitContinueStmt(const ContinueStmt *S) {
1065  assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1066  BreakContinueStack.back().ContinueCount = addCounters(
1067  BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1068  terminateRegion(S);
1069  }
1070 
1071  void VisitCallExpr(const CallExpr *E) {
1072  VisitStmt(E);
1073 
1074  // Terminate the region when we hit a noreturn function.
1075  // (This is helpful dealing with switch statements.)
1076  QualType CalleeType = E->getCallee()->getType();
1077  if (getFunctionExtInfo(*CalleeType).getNoReturn())
1078  terminateRegion(E);
1079  }
1080 
1081  void VisitWhileStmt(const WhileStmt *S) {
1082  extendRegion(S);
1083 
1084  Counter ParentCount = getRegion().getCounter();
1085  Counter BodyCount = getRegionCounter(S);
1086 
1087  // Handle the body first so that we can get the backedge count.
1088  BreakContinueStack.push_back(BreakContinue());
1089  extendRegion(S->getBody());
1090  Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1091  BreakContinue BC = BreakContinueStack.pop_back_val();
1092 
1093  bool BodyHasTerminateStmt = HasTerminateStmt;
1094  HasTerminateStmt = false;
1095 
1096  // Go back to handle the condition.
1097  Counter CondCount =
1098  addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1099  propagateCounts(CondCount, S->getCond());
1100  adjustForOutOfOrderTraversal(getEnd(S));
1101 
1102  // The body count applies to the area immediately after the increment.
1103  auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1104  if (Gap)
1105  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1106 
1107  Counter OutCount =
1108  addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1109  if (OutCount != ParentCount) {
1110  pushRegion(OutCount);
1111  GapRegionCounter = OutCount;
1112  if (BodyHasTerminateStmt)
1113  HasTerminateStmt = true;
1114  }
1115 
1116  // Create Branch Region around condition.
1117  createBranchRegion(S->getCond(), BodyCount,
1118  subtractCounters(CondCount, BodyCount));
1119  }
1120 
1121  void VisitDoStmt(const DoStmt *S) {
1122  extendRegion(S);
1123 
1124  Counter ParentCount = getRegion().getCounter();
1125  Counter BodyCount = getRegionCounter(S);
1126 
1127  BreakContinueStack.push_back(BreakContinue());
1128  extendRegion(S->getBody());
1129  Counter BackedgeCount =
1130  propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1131  BreakContinue BC = BreakContinueStack.pop_back_val();
1132 
1133  bool BodyHasTerminateStmt = HasTerminateStmt;
1134  HasTerminateStmt = false;
1135 
1136  Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1137  propagateCounts(CondCount, S->getCond());
1138 
1139  Counter OutCount =
1140  addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1141  if (OutCount != ParentCount) {
1142  pushRegion(OutCount);
1143  GapRegionCounter = OutCount;
1144  }
1145 
1146  // Create Branch Region around condition.
1147  createBranchRegion(S->getCond(), BodyCount,
1148  subtractCounters(CondCount, BodyCount));
1149 
1150  if (BodyHasTerminateStmt)
1151  HasTerminateStmt = true;
1152  }
1153 
1154  void VisitForStmt(const ForStmt *S) {
1155  extendRegion(S);
1156  if (S->getInit())
1157  Visit(S->getInit());
1158 
1159  Counter ParentCount = getRegion().getCounter();
1160  Counter BodyCount = getRegionCounter(S);
1161 
1162  // The loop increment may contain a break or continue.
1163  if (S->getInc())
1164  BreakContinueStack.emplace_back();
1165 
1166  // Handle the body first so that we can get the backedge count.
1167  BreakContinueStack.emplace_back();
1168  extendRegion(S->getBody());
1169  Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1170  BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1171 
1172  bool BodyHasTerminateStmt = HasTerminateStmt;
1173  HasTerminateStmt = false;
1174 
1175  // The increment is essentially part of the body but it needs to include
1176  // the count for all the continue statements.
1177  BreakContinue IncrementBC;
1178  if (const Stmt *Inc = S->getInc()) {
1179  propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1180  IncrementBC = BreakContinueStack.pop_back_val();
1181  }
1182 
1183  // Go back to handle the condition.
1184  Counter CondCount = addCounters(
1185  addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1186  IncrementBC.ContinueCount);
1187  if (const Expr *Cond = S->getCond()) {
1188  propagateCounts(CondCount, Cond);
1189  adjustForOutOfOrderTraversal(getEnd(S));
1190  }
1191 
1192  // The body count applies to the area immediately after the increment.
1193  auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1194  if (Gap)
1195  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1196 
1197  Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1198  subtractCounters(CondCount, BodyCount));
1199  if (OutCount != ParentCount) {
1200  pushRegion(OutCount);
1201  GapRegionCounter = OutCount;
1202  if (BodyHasTerminateStmt)
1203  HasTerminateStmt = true;
1204  }
1205 
1206  // Create Branch Region around condition.
1207  createBranchRegion(S->getCond(), BodyCount,
1208  subtractCounters(CondCount, BodyCount));
1209  }
1210 
1211  void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1212  extendRegion(S);
1213  if (S->getInit())
1214  Visit(S->getInit());
1215  Visit(S->getLoopVarStmt());
1216  Visit(S->getRangeStmt());
1217 
1218  Counter ParentCount = getRegion().getCounter();
1219  Counter BodyCount = getRegionCounter(S);
1220 
1221  BreakContinueStack.push_back(BreakContinue());
1222  extendRegion(S->getBody());
1223  Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1224  BreakContinue BC = BreakContinueStack.pop_back_val();
1225 
1226  bool BodyHasTerminateStmt = HasTerminateStmt;
1227  HasTerminateStmt = false;
1228 
1229  // The body count applies to the area immediately after the range.
1230  auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1231  if (Gap)
1232  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1233 
1234  Counter LoopCount =
1235  addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1236  Counter OutCount =
1237  addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1238  if (OutCount != ParentCount) {
1239  pushRegion(OutCount);
1240  GapRegionCounter = OutCount;
1241  if (BodyHasTerminateStmt)
1242  HasTerminateStmt = true;
1243  }
1244 
1245  // Create Branch Region around condition.
1246  createBranchRegion(S->getCond(), BodyCount,
1247  subtractCounters(LoopCount, BodyCount));
1248  }
1249 
1250  void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1251  extendRegion(S);
1252  Visit(S->getElement());
1253 
1254  Counter ParentCount = getRegion().getCounter();
1255  Counter BodyCount = getRegionCounter(S);
1256 
1257  BreakContinueStack.push_back(BreakContinue());
1258  extendRegion(S->getBody());
1259  Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1260  BreakContinue BC = BreakContinueStack.pop_back_val();
1261 
1262  // The body count applies to the area immediately after the collection.
1263  auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1264  if (Gap)
1265  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1266 
1267  Counter LoopCount =
1268  addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1269  Counter OutCount =
1270  addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1271  if (OutCount != ParentCount) {
1272  pushRegion(OutCount);
1273  GapRegionCounter = OutCount;
1274  }
1275  }
1276 
1277  void VisitSwitchStmt(const SwitchStmt *S) {
1278  extendRegion(S);
1279  if (S->getInit())
1280  Visit(S->getInit());
1281  Visit(S->getCond());
1282 
1283  BreakContinueStack.push_back(BreakContinue());
1284 
1285  const Stmt *Body = S->getBody();
1286  extendRegion(Body);
1287  if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1288  if (!CS->body_empty()) {
1289  // Make a region for the body of the switch. If the body starts with
1290  // a case, that case will reuse this region; otherwise, this covers
1291  // the unreachable code at the beginning of the switch body.
1292  size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1293  getRegion().setGap(true);
1294  Visit(Body);
1295 
1296  // Set the end for the body of the switch, if it isn't already set.
1297  for (size_t i = RegionStack.size(); i != Index; --i) {
1298  if (!RegionStack[i - 1].hasEndLoc())
1299  RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1300  }
1301 
1302  popRegions(Index);
1303  }
1304  } else
1305  propagateCounts(Counter::getZero(), Body);
1306  BreakContinue BC = BreakContinueStack.pop_back_val();
1307 
1308  if (!BreakContinueStack.empty())
1309  BreakContinueStack.back().ContinueCount = addCounters(
1310  BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1311 
1312  Counter ParentCount = getRegion().getCounter();
1313  Counter ExitCount = getRegionCounter(S);
1314  SourceLocation ExitLoc = getEnd(S);
1315  pushRegion(ExitCount);
1316  GapRegionCounter = ExitCount;
1317 
1318  // Ensure that handleFileExit recognizes when the end location is located
1319  // in a different file.
1320  MostRecentLocation = getStart(S);
1321  handleFileExit(ExitLoc);
1322 
1323  // Create a Branch Region around each Case. Subtract the case's
1324  // counter from the Parent counter to track the "False" branch count.
1325  Counter CaseCountSum;
1326  bool HasDefaultCase = false;
1327  const SwitchCase *Case = S->getSwitchCaseList();
1328  for (; Case; Case = Case->getNextSwitchCase()) {
1329  HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1330  CaseCountSum =
1331  addCounters(CaseCountSum, getRegionCounter(Case), /*Simplify=*/false);
1332  createSwitchCaseRegion(
1333  Case, getRegionCounter(Case),
1334  subtractCounters(ParentCount, getRegionCounter(Case)));
1335  }
1336  // Simplify is skipped while building the counters above: it can get really
1337  // slow on top of switches with thousands of cases. Instead, trigger
1338  // simplification by adding zero to the last counter.
1339  CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
1340 
1341  // If no explicit default case exists, create a branch region to represent
1342  // the hidden branch, which will be added later by the CodeGen. This region
1343  // will be associated with the switch statement's condition.
1344  if (!HasDefaultCase) {
1345  Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1346  Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1347  createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1348  }
1349  }
1350 
1351  void VisitSwitchCase(const SwitchCase *S) {
1352  extendRegion(S);
1353 
1354  SourceMappingRegion &Parent = getRegion();
1355 
1356  Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1357  // Reuse the existing region if it starts at our label. This is typical of
1358  // the first case in a switch.
1359  if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1360  Parent.setCounter(Count);
1361  else
1362  pushRegion(Count, getStart(S));
1363 
1364  GapRegionCounter = Count;
1365 
1366  if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1367  Visit(CS->getLHS());
1368  if (const Expr *RHS = CS->getRHS())
1369  Visit(RHS);
1370  }
1371  Visit(S->getSubStmt());
1372  }
1373 
1374  void VisitIfStmt(const IfStmt *S) {
1375  extendRegion(S);
1376  if (S->getInit())
1377  Visit(S->getInit());
1378 
1379  // Extend into the condition before we propagate through it below - this is
1380  // needed to handle macros that generate the "if" but not the condition.
1381  if (!S->isConsteval())
1382  extendRegion(S->getCond());
1383 
1384  Counter ParentCount = getRegion().getCounter();
1385  Counter ThenCount = getRegionCounter(S);
1386 
1387  if (!S->isConsteval()) {
1388  // Emitting a counter for the condition makes it easier to interpret the
1389  // counter for the body when looking at the coverage.
1390  propagateCounts(ParentCount, S->getCond());
1391 
1392  // The 'then' count applies to the area immediately after the condition.
1393  Optional<SourceRange> Gap =
1394  findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1395  if (Gap)
1396  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1397  }
1398 
1399  extendRegion(S->getThen());
1400  Counter OutCount = propagateCounts(ThenCount, S->getThen());
1401 
1402  Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1403  if (const Stmt *Else = S->getElse()) {
1404  bool ThenHasTerminateStmt = HasTerminateStmt;
1405  HasTerminateStmt = false;
1406  // The 'else' count applies to the area immediately after the 'then'.
1407  Optional<SourceRange> Gap =
1408  findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1409  if (Gap)
1410  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
1411  extendRegion(Else);
1412  OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1413 
1414  if (ThenHasTerminateStmt)
1415  HasTerminateStmt = true;
1416  } else
1417  OutCount = addCounters(OutCount, ElseCount);
1418 
1419  if (OutCount != ParentCount) {
1420  pushRegion(OutCount);
1421  GapRegionCounter = OutCount;
1422  }
1423 
1424  if (!S->isConsteval()) {
1425  // Create Branch Region around condition.
1426  createBranchRegion(S->getCond(), ThenCount,
1427  subtractCounters(ParentCount, ThenCount));
1428  }
1429  }
1430 
1431  void VisitCXXTryStmt(const CXXTryStmt *S) {
1432  extendRegion(S);
1433  // Handle macros that generate the "try" but not the rest.
1434  extendRegion(S->getTryBlock());
1435 
1436  Counter ParentCount = getRegion().getCounter();
1437  propagateCounts(ParentCount, S->getTryBlock());
1438 
1439  for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1440  Visit(S->getHandler(I));
1441 
1442  Counter ExitCount = getRegionCounter(S);
1443  pushRegion(ExitCount);
1444  }
1445 
1446  void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1447  propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1448  }
1449 
1450  void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1451  extendRegion(E);
1452 
1453  Counter ParentCount = getRegion().getCounter();
1454  Counter TrueCount = getRegionCounter(E);
1455 
1456  propagateCounts(ParentCount, E->getCond());
1457 
1458  if (!isa<BinaryConditionalOperator>(E)) {
1459  // The 'then' count applies to the area immediately after the condition.
1460  auto Gap =
1461  findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1462  if (Gap)
1463  fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
1464 
1465  extendRegion(E->getTrueExpr());
1466  propagateCounts(TrueCount, E->getTrueExpr());
1467  }
1468 
1469  extendRegion(E->getFalseExpr());
1470  propagateCounts(subtractCounters(ParentCount, TrueCount),
1471  E->getFalseExpr());
1472 
1473  // Create Branch Region around condition.
1474  createBranchRegion(E->getCond(), TrueCount,
1475  subtractCounters(ParentCount, TrueCount));
1476  }
1477 
1478  void VisitBinLAnd(const BinaryOperator *E) {
1479  extendRegion(E->getLHS());
1480  propagateCounts(getRegion().getCounter(), E->getLHS());
1481  handleFileExit(getEnd(E->getLHS()));
1482 
1483  // Counter tracks the right hand side of a logical and operator.
1484  extendRegion(E->getRHS());
1485  propagateCounts(getRegionCounter(E), E->getRHS());
1486 
1487  // Extract the RHS's Execution Counter.
1488  Counter RHSExecCnt = getRegionCounter(E);
1489 
1490  // Extract the RHS's "True" Instance Counter.
1491  Counter RHSTrueCnt = getRegionCounter(E->getRHS());
1492 
1493  // Extract the Parent Region Counter.
1494  Counter ParentCnt = getRegion().getCounter();
1495 
1496  // Create Branch Region around LHS condition.
1497  createBranchRegion(E->getLHS(), RHSExecCnt,
1498  subtractCounters(ParentCnt, RHSExecCnt));
1499 
1500  // Create Branch Region around RHS condition.
1501  createBranchRegion(E->getRHS(), RHSTrueCnt,
1502  subtractCounters(RHSExecCnt, RHSTrueCnt));
1503  }
1504 
1505  void VisitBinLOr(const BinaryOperator *E) {
1506  extendRegion(E->getLHS());
1507  propagateCounts(getRegion().getCounter(), E->getLHS());
1508  handleFileExit(getEnd(E->getLHS()));
1509 
1510  // Counter tracks the right hand side of a logical or operator.
1511  extendRegion(E->getRHS());
1512  propagateCounts(getRegionCounter(E), E->getRHS());
1513 
1514  // Extract the RHS's Execution Counter.
1515  Counter RHSExecCnt = getRegionCounter(E);
1516 
1517  // Extract the RHS's "False" Instance Counter.
1518  Counter RHSFalseCnt = getRegionCounter(E->getRHS());
1519 
1520  // Extract the Parent Region Counter.
1521  Counter ParentCnt = getRegion().getCounter();
1522 
1523  // Create Branch Region around LHS condition.
1524  createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
1525  RHSExecCnt);
1526 
1527  // Create Branch Region around RHS condition.
1528  createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
1529  RHSFalseCnt);
1530  }
1531 
1532  void VisitLambdaExpr(const LambdaExpr *LE) {
1533  // Lambdas are treated as their own functions for now, so we shouldn't
1534  // propagate counts into them.
1535  }
1536 };
1537 
1538 } // end anonymous namespace
1539 
1540 static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1541  ArrayRef<CounterExpression> Expressions,
1543  OS << FunctionName << ":\n";
1544  CounterMappingContext Ctx(Expressions);
1545  for (const auto &R : Regions) {
1546  OS.indent(2);
1547  switch (R.Kind) {
1548  case CounterMappingRegion::CodeRegion:
1549  break;
1550  case CounterMappingRegion::ExpansionRegion:
1551  OS << "Expansion,";
1552  break;
1553  case CounterMappingRegion::SkippedRegion:
1554  OS << "Skipped,";
1555  break;
1556  case CounterMappingRegion::GapRegion:
1557  OS << "Gap,";
1558  break;
1559  case CounterMappingRegion::BranchRegion:
1560  OS << "Branch,";
1561  break;
1562  }
1563 
1564  OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1565  << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1566  Ctx.dump(R.Count, OS);
1567 
1568  if (R.Kind == CounterMappingRegion::BranchRegion) {
1569  OS << ", ";
1570  Ctx.dump(R.FalseCount, OS);
1571  }
1572 
1573  if (R.Kind == CounterMappingRegion::ExpansionRegion)
1574  OS << " (Expanded file = " << R.ExpandedFileID << ")";
1575  OS << "\n";
1576  }
1577 }
1578 
1580  CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
1581  : CGM(CGM), SourceInfo(SourceInfo) {
1582  CoveragePrefixMap = CGM.getCodeGenOpts().CoveragePrefixMap;
1583 }
1584 
1585 std::string CoverageMappingModuleGen::getCurrentDirname() {
1586  if (!CGM.getCodeGenOpts().CoverageCompilationDir.empty())
1588 
1589  SmallString<256> CWD;
1590  llvm::sys::fs::current_path(CWD);
1591  return CWD.str().str();
1592 }
1593 
1594 std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
1596  llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1597  for (const auto &Entry : CoveragePrefixMap) {
1598  if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second))
1599  break;
1600  }
1601  return Path.str().str();
1602 }
1603 
1605  llvm::InstrProfSectKind SK) {
1606  return llvm::getInstrProfSectionName(
1607  SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1608 }
1609 
1610 void CoverageMappingModuleGen::emitFunctionMappingRecord(
1611  const FunctionInfo &Info, uint64_t FilenamesRef) {
1612  llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1613 
1614  // Assign a name to the function record. This is used to merge duplicates.
1615  std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1616 
1617  // A dummy description for a function included-but-not-used in a TU can be
1618  // replaced by full description provided by a different TU. The two kinds of
1619  // descriptions play distinct roles: therefore, assign them different names
1620  // to prevent `linkonce_odr` merging.
1621  if (Info.IsUsed)
1622  FuncRecordName += "u";
1623 
1624  // Create the function record type.
1625  const uint64_t NameHash = Info.NameHash;
1626  const uint64_t FuncHash = Info.FuncHash;
1627  const std::string &CoverageMapping = Info.CoverageMapping;
1628 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1629  llvm::Type *FunctionRecordTypes[] = {
1630 #include "llvm/ProfileData/InstrProfData.inc"
1631  };
1632  auto *FunctionRecordTy =
1633  llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1634  /*isPacked=*/true);
1635 
1636  // Create the function record constant.
1637 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1638  llvm::Constant *FunctionRecordVals[] = {
1639  #include "llvm/ProfileData/InstrProfData.inc"
1640  };
1641  auto *FuncRecordConstant = llvm::ConstantStruct::get(
1642  FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1643 
1644  // Create the function record global.
1645  auto *FuncRecord = new llvm::GlobalVariable(
1646  CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1647  llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1648  FuncRecordName);
1649  FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1650  FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1651  FuncRecord->setAlignment(llvm::Align(8));
1652  if (CGM.supportsCOMDAT())
1653  FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1654 
1655  // Make sure the data doesn't get deleted.
1656  CGM.addUsedGlobal(FuncRecord);
1657 }
1658 
1660  llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1661  const std::string &CoverageMapping, bool IsUsed) {
1662  llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1663  const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1664  FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1665 
1666  if (!IsUsed)
1667  FunctionNames.push_back(
1668  llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1669 
1670  if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1671  // Dump the coverage mapping data for this function by decoding the
1672  // encoded data. This allows us to dump the mapping regions which were
1673  // also processed by the CoverageMappingWriter which performs
1674  // additional minimization operations such as reducing the number of
1675  // expressions.
1677  std::vector<StringRef> Filenames;
1678  std::vector<CounterExpression> Expressions;
1679  std::vector<CounterMappingRegion> Regions;
1680  FilenameStrs.resize(FileEntries.size() + 1);
1681  FilenameStrs[0] = normalizeFilename(getCurrentDirname());
1682  for (const auto &Entry : FileEntries) {
1683  auto I = Entry.second;
1684  FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1685  }
1686  ArrayRef<std::string> FilenameRefs = llvm::makeArrayRef(FilenameStrs);
1687  RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1688  Expressions, Regions);
1689  if (Reader.read())
1690  return;
1691  dump(llvm::outs(), NameValue, Expressions, Regions);
1692  }
1693 }
1694 
1696  if (FunctionRecords.empty())
1697  return;
1698  llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1699  auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1700 
1701  // Create the filenames and merge them with coverage mappings
1703  FilenameStrs.resize(FileEntries.size() + 1);
1704  // The first filename is the current working directory.
1705  FilenameStrs[0] = normalizeFilename(getCurrentDirname());
1706  for (const auto &Entry : FileEntries) {
1707  auto I = Entry.second;
1708  FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1709  }
1710 
1711  std::string Filenames;
1712  {
1713  llvm::raw_string_ostream OS(Filenames);
1714  CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
1715  }
1716  auto *FilenamesVal =
1717  llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1718  const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
1719 
1720  // Emit the function records.
1721  for (const FunctionInfo &Info : FunctionRecords)
1722  emitFunctionMappingRecord(Info, FilenamesRef);
1723 
1724  const unsigned NRecords = 0;
1725  const size_t FilenamesSize = Filenames.size();
1726  const unsigned CoverageMappingSize = 0;
1727  llvm::Type *CovDataHeaderTypes[] = {
1728 #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1729 #include "llvm/ProfileData/InstrProfData.inc"
1730  };
1731  auto CovDataHeaderTy =
1732  llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1733  llvm::Constant *CovDataHeaderVals[] = {
1734 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1735 #include "llvm/ProfileData/InstrProfData.inc"
1736  };
1737  auto CovDataHeaderVal = llvm::ConstantStruct::get(
1738  CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1739 
1740  // Create the coverage data record
1741  llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1742  auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1743  llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1744  auto CovDataVal =
1745  llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1746  auto CovData = new llvm::GlobalVariable(
1747  CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
1748  CovDataVal, llvm::getCoverageMappingVarName());
1749 
1750  CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1751  CovData->setAlignment(llvm::Align(8));
1752 
1753  // Make sure the data doesn't get deleted.
1754  CGM.addUsedGlobal(CovData);
1755  // Create the deferred function records array
1756  if (!FunctionNames.empty()) {
1757  auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1758  FunctionNames.size());
1759  auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1760  // This variable will *NOT* be emitted to the object file. It is used
1761  // to pass the list of names referenced to codegen.
1762  new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1764  llvm::getCoverageUnusedNamesVarName());
1765  }
1766 }
1767 
1769  auto It = FileEntries.find(File);
1770  if (It != FileEntries.end())
1771  return It->second;
1772  unsigned FileID = FileEntries.size() + 1;
1773  FileEntries.insert(std::make_pair(File, FileID));
1774  return FileID;
1775 }
1776 
1778  llvm::raw_ostream &OS) {
1779  assert(CounterMap);
1780  CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1781  Walker.VisitDecl(D);
1782  Walker.write(OS);
1783 }
1784 
1786  llvm::raw_ostream &OS) {
1787  EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1788  Walker.VisitDecl(D);
1789  Walker.write(OS);
1790 }
clang::FunctionDefinitionKind::Defaulted
@ Defaulted
clang::InternalLinkage
@ InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
clang::LabelStmt
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:1835
clang::CodeGen::CoverageMappingModuleGen::addFunctionMappingRecord
void addFunctionMappingRecord(llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue, uint64_t FunctionHash, const std::string &CoverageMapping, bool IsUsed=true)
Add a function's coverage mapping record to the collection of the function mapping records.
Definition: CoverageMappingGen.cpp:1659
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::CodeGenOptions::CoveragePrefixMap
std::map< std::string, std::string > CoveragePrefixMap
Definition: CodeGenOptions.h:190
EmptyLineCommentCoverage
static llvm::cl::opt< bool > EmptyLineCommentCoverage("emptyline-comment-coverage", llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only " "disable it on test)"), llvm::cl::init(true), llvm::cl::Hidden)
clang::HiddenVisibility
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:36
clang::CoverageSourceInfo::getSkippedRanges
std::vector< SkippedRange > & getSkippedRanges()
Definition: CoverageMappingGen.h:77
clang::SwitchStmt
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2186
clang::DeclaratorContext::File
@ File
CodeGenFunction.h
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::WhileStmt
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2377
clang::CodeGen::CodeGenModule::addUsedGlobal
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
Definition: CodeGenModule.cpp:2477
clang::SkippedRange::Comment
@ Comment
Definition: CoverageMappingGen.h:37
llvm::SmallVector
Definition: LLVM.h:38
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::AbstractConditionalOperator
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4113
clang::SourceLocation::getLocWithOffset
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
Definition: SourceLocation.h:134
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:737
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:56
clang::SrcMgr::ExpansionInfo::isFunctionMacroExpansion
bool isFunctionMacroExpansion() const
Definition: SourceManager.h:402
clang::AbstractConditionalOperator::getTrueExpr
Expr * getTrueExpr() const
Definition: Expr.h:4297
clang::tooling::Filter
llvm::cl::opt< std::string > Filter
getInstrProfSection
static std::string getInstrProfSection(const CodeGenModule &CGM, llvm::InstrProfSectKind SK)
Definition: CoverageMappingGen.cpp:1604
clang::CodeGen::CoverageMappingModuleGen::getCodeGenModule
CodeGenModule & getCodeGenModule()
Return an interface into CodeGenModule.
Definition: CoverageMappingGen.h:144
clang::CodeGen::CodeGenModule::getContext
ASTContext & getContext() const
Definition: CodeGenModule.h:728
clang::Decl::hasBody
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:1058
Filename
StringRef Filename
Definition: Format.cpp:2715
clang::IfStmt
IfStmt - This represents an if/then/else.
Definition: Stmt.h:1940
clang::CodeGen::CoverageMappingGen::emitCounterMapping
void emitCounterMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data which maps the regions of code to counters that will be used to find t...
Definition: CoverageMappingGen.cpp:1777
clang::GotoStmt
GotoStmt - This represents a direct goto.
Definition: Stmt.h:2641
llvm::Optional
Definition: LLVM.h:40
clang::getFunctionExtInfo
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Definition: Type.h:6783
clang::CoreturnStmt
Represents a 'co_return' statement in the C++ Coroutines TS.
Definition: StmtCXX.h:458
clang::ObjCForCollectionStmt
Represents Objective-C's collection statement.
Definition: StmtObjC.h:23
clang::Lexer::MeasureTokenLength
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition: Lexer.cpp:451
clang::CoverageSourceInfo
Stores additional source code information like skipped ranges which is required by the coverage mappi...
Definition: CoverageMappingGen.h:62
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
Definition: CoverageMappingGen.cpp:45
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:637
clang::CXXThrowExpr
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1188
clang::CoverageSourceInfo::AddSkippedRange
void AddSkippedRange(SourceRange Range, SkippedRange::Kind RangeKind)
Definition: CoverageMappingGen.cpp:63
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:2961
clang::CoverageSourceInfo::SourceRangeSkipped
void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override
Hook called when a source range is skipped.
Definition: CoverageMappingGen.cpp:74
min
__DEVICE__ int min(int __a, int __b)
Definition: __clang_cuda_math.h:197
clang::CodeGen::CoverageMappingModuleGen
Organizes the cross-function state that is used while generating code coverage mapping data.
Definition: CoverageMappingGen.h:96
clang::CodeGen::CoverageMappingModuleGen::emit
void emit()
Emit the coverage mapping data for a translation unit.
Definition: CoverageMappingGen.cpp:1695
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3813
clang::SrcMgr::ExpansionInfo
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
Definition: SourceManager.h:354
hlsl::uint64_t
unsigned long uint64_t
Definition: hlsl_basic_types.h:25
clang::LambdaExpr
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1872
clang::interp::LE
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:504
clang::FunctionType::ExtInfo::getNoReturn
bool getNoReturn() const
Definition: Type.h:3834
clang::Preprocessor::setPreprocessToken
void setPreprocessToken(bool Preprocess)
Definition: Preprocessor.h:1187
clang::CodeGen::CodeGenModule::getCodeGenOpts
const CodeGenOptions & getCodeGenOpts() const
Definition: CodeGenModule.h:737
clang::Preprocessor::addCommentHandler
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
Definition: Preprocessor.cpp:1394
clang::Token::getKind
tok::TokenKind getKind() const
Definition: Token.h:93
Diagnostic.h
clang::CodeGenOptions::CoverageCompilationDir
std::string CoverageCompilationDir
The string to embed in coverage mapping as the current working directory.
Definition: CodeGenOptions.h:179
Depth
int Depth
Definition: ASTDiff.cpp:189
clang::ForStmt
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2570
clang::CodeGen::CodeGenModule::getModule
llvm::Module & getModule() const
Definition: CodeGenModule.h:738
clang::AbstractConditionalOperator::getFalseExpr
Expr * getFalseExpr() const
Definition: Expr.h:4303
llvm::SmallString
Definition: LLVM.h:37
clang::Expr::EvalResult
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:622
clang::CXXTryStmt
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:68
clang::SwitchCase
Definition: Stmt.h:1558
clang::CodeGen::CoverageMappingModuleGen::getSourceInfo
CoverageSourceInfo & getSourceInfo() const
Definition: CoverageMappingGen.h:124
clang::CoverageSourceInfo::updateNextTokLoc
void updateNextTokLoc(SourceLocation Loc)
Definition: CoverageMappingGen.cpp:87
clang::FileEntry
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:366
clang::CodeGen::CodeGenFunction::isInstrumentedCondition
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
Definition: CodeGenFunction.cpp:1605
clang::Preprocessor::getSourceManager
SourceManager & getSourceManager() const
Definition: Preprocessor.h:1065
clang::transformer::EditKind::Range
@ Range
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1198
clang::SkippedRange::EmptyLine
@ EmptyLine
Definition: CoverageMappingGen.h:36
clang::SkippedRange::Kind
Kind
Definition: CoverageMappingGen.h:34
clang::BinaryOperator::getLHS
Expr * getLHS() const
Definition: Expr.h:3862
dump
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Definition: CoverageMappingGen.cpp:1540
clang::CodeGen::CodeGenModule
This class organizes the cross-function state that is used while generating LLVM code.
Definition: CodeGenModule.h:279
llvm::ArrayRef
Definition: LLVM.h:34
Lexer.h
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::Preprocessor::setEmptylineHandler
void setEmptylineHandler(EmptylineHandler *Handler)
Set empty line handler.
Definition: Preprocessor.h:1406
clang::DoStmt
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2514
StmtVisitor.h
clang::CXXThrowExpr::getSubExpr
const Expr * getSubExpr() const
Definition: ExprCXX.h:1208
clang::CodeGen::CoverageMappingModuleGen::getFileID
unsigned getFileID(const FileEntry *File)
Return the coverage mapping translation unit file id for the given file.
Definition: CoverageMappingGen.cpp:1768
clang::SrcMgr::ExpansionInfo::getExpansionLocEnd
SourceLocation getExpansionLocEnd() const
Definition: SourceManager.h:380
clang::CoroutineBodyStmt
Represents the body of a coroutine.
Definition: StmtCXX.h:317
clang::BreakStmt
BreakStmt - This represents a break.
Definition: Stmt.h:2759
clang::CodeGen::CoverageMappingGen::emitEmptyMapping
void emitEmptyMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data for an unused function.
Definition: CoverageMappingGen.cpp:1785
clang::ConstStmtVisitor
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:193
clang::CoverageSourceInfo::HandleComment
bool HandleComment(Preprocessor &PP, SourceRange Range) override
Definition: CoverageMappingGen.cpp:82
clang::Token::getLocation
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:126
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:746
clang::Expr::EvaluateAsInt
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Definition: ExprConstant.cpp:15155
clang::SourceLocation::isMacroID
bool isMacroID() const
Definition: SourceLocation.h:103
clang::CXXForRangeStmt
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:134
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:81
clang::CodeGen::CodeGenModule::supportsCOMDAT
bool supportsCOMDAT() const
Definition: TargetInfo.cpp:12064
clang::SkippedRange::PPIfElse
@ PPIfElse
Definition: CoverageMappingGen.h:35
clang::ContinueStmt
ContinueStmt - This represents a continue.
Definition: Stmt.h:2729
clang::Decl::getBody
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:1052
clang::AbstractConditionalOperator::getCond
Expr * getCond() const
Definition: Expr.h:4291
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang
Definition: CalledOnceCheck.h:17
clang::Preprocessor::addPPCallbacks
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
Definition: Preprocessor.h:1159
clang::CoverageSourceInfo::HandleEmptyline
void HandleEmptyline(SourceRange Range) override
Definition: CoverageMappingGen.cpp:78
hlsl::int64_t
long int64_t
Definition: hlsl_basic_types.h:26
FrontendDiagnostic.h
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:71
clang::BinaryOperator::getRHS
Expr * getRHS() const
Definition: Expr.h:3864
clang::CXXCatchStmt
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
clang::Expr::getType
QualType getType() const
Definition: Expr.h:141
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::serialization::ComputeHash
unsigned ComputeHash(Selector Sel)
Definition: ASTCommon.cpp:276
Parent
NodeId Parent
Definition: ASTDiff.cpp:190
clang::Preprocessor::setTokenWatcher
void setTokenWatcher(llvm::unique_function< void(const clang::Token &)> F)
Register a function that would be called on each token in the final expanded token stream.
Definition: Preprocessor.h:1183
clang::AbstractConditionalOperator::getQuestionLoc
SourceLocation getQuestionLoc() const
Definition: Expr.h:4140
llvm::SmallVectorImpl
Definition: Randstruct.h:18
FileManager.h
clang::CodeGen::CoverageMappingModuleGen::CoverageMappingModuleGen
CoverageMappingModuleGen(CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
Definition: CoverageMappingGen.cpp:1579
clang::Expr
This represents one expression.
Definition: Expr.h:109
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:129
clang::CoverageSourceInfo::PrevTokLoc
SourceLocation PrevTokLoc
Definition: CoverageMappingGen.h:73
SM
#define SM(sm)
Definition: Cuda.cpp:79
CoverageMappingGen.h
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2811
clang::CodeGen::CodeGenModule::getLLVMContext
llvm::LLVMContext & getLLVMContext()
Definition: CodeGenModule.h:749
clang::SwitchCase::getColonLoc
SourceLocation getColonLoc() const
Definition: Stmt.h:1584
clang::ReturnStmt
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2796
clang::SwitchCase::getNextSwitchCase
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1578