1 //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // Instrumentation-based code coverage mapping generator
11 //===----------------------------------------------------------------------===//
13 #include "CoverageMappingGen.h"
14 #include "CodeGenFunction.h"
15 #include "clang/AST/StmtVisitor.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Lex/Lexer.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
22 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23 #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Path.h"
28 // This selects the coverage mapping format defined when `InstrProfData.inc`
29 // is textually included.
34 EnableSingleByteCoverage("enable-single-byte-coverage",
36 llvm::cl::desc("Enable single byte coverage"),
37 llvm::cl::Hidden
, llvm::cl::init(false));
40 static llvm::cl::opt
<bool> EmptyLineCommentCoverage(
41 "emptyline-comment-coverage",
42 llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
43 "disable it on test)"),
44 llvm::cl::init(true), llvm::cl::Hidden
);
46 namespace llvm::coverage
{
47 cl::opt
<bool> SystemHeadersCoverage(
48 "system-headers-coverage",
49 cl::desc("Enable collecting coverage from system headers"), cl::init(false),
53 using namespace clang
;
54 using namespace CodeGen
;
55 using namespace llvm::coverage
;
58 CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor
&PP
) {
59 CoverageSourceInfo
*CoverageInfo
=
60 new CoverageSourceInfo(PP
.getSourceManager());
61 PP
.addPPCallbacks(std::unique_ptr
<PPCallbacks
>(CoverageInfo
));
62 if (EmptyLineCommentCoverage
) {
63 PP
.addCommentHandler(CoverageInfo
);
64 PP
.setEmptylineHandler(CoverageInfo
);
65 PP
.setPreprocessToken(true);
66 PP
.setTokenWatcher([CoverageInfo
](clang::Token Tok
) {
67 // Update previous token location.
68 CoverageInfo
->PrevTokLoc
= Tok
.getLocation();
69 if (Tok
.getKind() != clang::tok::eod
)
70 CoverageInfo
->updateNextTokLoc(Tok
.getLocation());
76 void CoverageSourceInfo::AddSkippedRange(SourceRange Range
,
77 SkippedRange::Kind RangeKind
) {
78 if (EmptyLineCommentCoverage
&& !SkippedRanges
.empty() &&
79 PrevTokLoc
== SkippedRanges
.back().PrevTokLoc
&&
80 SourceMgr
.isWrittenInSameFile(SkippedRanges
.back().Range
.getEnd(),
82 SkippedRanges
.back().Range
.setEnd(Range
.getEnd());
84 SkippedRanges
.push_back({Range
, RangeKind
, PrevTokLoc
});
87 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range
, SourceLocation
) {
88 AddSkippedRange(Range
, SkippedRange::PPIfElse
);
91 void CoverageSourceInfo::HandleEmptyline(SourceRange Range
) {
92 AddSkippedRange(Range
, SkippedRange::EmptyLine
);
95 bool CoverageSourceInfo::HandleComment(Preprocessor
&PP
, SourceRange Range
) {
96 AddSkippedRange(Range
, SkippedRange::Comment
);
100 void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc
) {
101 if (!SkippedRanges
.empty() && SkippedRanges
.back().NextTokLoc
.isInvalid())
102 SkippedRanges
.back().NextTokLoc
= Loc
;
106 /// A region of source code that can be mapped to a counter.
107 class SourceMappingRegion
{
108 /// Primary Counter that is also used for Branch Regions for "True" branches.
111 /// Secondary Counter used for Branch Regions for "False" branches.
112 std::optional
<Counter
> FalseCount
;
114 /// Parameters used for Modified Condition/Decision Coverage
115 mcdc::Parameters MCDCParams
;
117 /// The region's starting location.
118 std::optional
<SourceLocation
> LocStart
;
120 /// The region's ending location.
121 std::optional
<SourceLocation
> LocEnd
;
123 /// Whether this region is a gap region. The count from a gap region is set
124 /// as the line execution count if there are no other regions on the line.
127 /// Whetever this region is skipped ('if constexpr' or 'if consteval' untaken
128 /// branch, or anything skipped but not empty line / comments)
132 SourceMappingRegion(Counter Count
, std::optional
<SourceLocation
> LocStart
,
133 std::optional
<SourceLocation
> LocEnd
,
134 bool GapRegion
= false)
135 : Count(Count
), LocStart(LocStart
), LocEnd(LocEnd
), GapRegion(GapRegion
),
136 SkippedRegion(false) {}
138 SourceMappingRegion(Counter Count
, std::optional
<Counter
> FalseCount
,
139 mcdc::Parameters MCDCParams
,
140 std::optional
<SourceLocation
> LocStart
,
141 std::optional
<SourceLocation
> LocEnd
,
142 bool GapRegion
= false)
143 : Count(Count
), FalseCount(FalseCount
), MCDCParams(MCDCParams
),
144 LocStart(LocStart
), LocEnd(LocEnd
), GapRegion(GapRegion
),
145 SkippedRegion(false) {}
147 SourceMappingRegion(mcdc::Parameters MCDCParams
,
148 std::optional
<SourceLocation
> LocStart
,
149 std::optional
<SourceLocation
> LocEnd
)
150 : MCDCParams(MCDCParams
), LocStart(LocStart
), LocEnd(LocEnd
),
151 GapRegion(false), SkippedRegion(false) {}
153 const Counter
&getCounter() const { return Count
; }
155 const Counter
&getFalseCounter() const {
156 assert(FalseCount
&& "Region has no alternate counter");
160 void setCounter(Counter C
) { Count
= C
; }
162 bool hasStartLoc() const { return LocStart
.has_value(); }
164 void setStartLoc(SourceLocation Loc
) { LocStart
= Loc
; }
166 SourceLocation
getBeginLoc() const {
167 assert(LocStart
&& "Region has no start location");
171 bool hasEndLoc() const { return LocEnd
.has_value(); }
173 void setEndLoc(SourceLocation Loc
) {
174 assert(Loc
.isValid() && "Setting an invalid end location");
178 SourceLocation
getEndLoc() const {
179 assert(LocEnd
&& "Region has no end location");
183 bool isGap() const { return GapRegion
; }
185 void setGap(bool Gap
) { GapRegion
= Gap
; }
187 bool isSkipped() const { return SkippedRegion
; }
189 void setSkipped(bool Skipped
) { SkippedRegion
= Skipped
; }
191 bool isBranch() const { return FalseCount
.has_value(); }
193 bool isMCDCBranch() const {
194 return std::holds_alternative
<mcdc::BranchParameters
>(MCDCParams
);
197 const auto &getMCDCBranchParams() const {
198 return mcdc::getParams
<const mcdc::BranchParameters
>(MCDCParams
);
201 bool isMCDCDecision() const {
202 return std::holds_alternative
<mcdc::DecisionParameters
>(MCDCParams
);
205 const auto &getMCDCDecisionParams() const {
206 return mcdc::getParams
<const mcdc::DecisionParameters
>(MCDCParams
);
209 const mcdc::Parameters
&getMCDCParams() const { return MCDCParams
; }
211 void resetMCDCParams() { MCDCParams
= mcdc::Parameters(); }
214 /// Spelling locations for the start and end of a source region.
215 struct SpellingRegion
{
216 /// The line where the region starts.
219 /// The column where the region starts.
220 unsigned ColumnStart
;
222 /// The line where the region ends.
225 /// The column where the region ends.
228 SpellingRegion(SourceManager
&SM
, SourceLocation LocStart
,
229 SourceLocation LocEnd
) {
230 LineStart
= SM
.getSpellingLineNumber(LocStart
);
231 ColumnStart
= SM
.getSpellingColumnNumber(LocStart
);
232 LineEnd
= SM
.getSpellingLineNumber(LocEnd
);
233 ColumnEnd
= SM
.getSpellingColumnNumber(LocEnd
);
236 SpellingRegion(SourceManager
&SM
, SourceMappingRegion
&R
)
237 : SpellingRegion(SM
, R
.getBeginLoc(), R
.getEndLoc()) {}
239 /// Check if the start and end locations appear in source order, i.e
240 /// top->bottom, left->right.
241 bool isInSourceOrder() const {
242 return (LineStart
< LineEnd
) ||
243 (LineStart
== LineEnd
&& ColumnStart
<= ColumnEnd
);
247 /// Provides the common functionality for the different
248 /// coverage mapping region builders.
249 class CoverageMappingBuilder
{
251 CoverageMappingModuleGen
&CVM
;
253 const LangOptions
&LangOpts
;
256 /// Map of clang's FileIDs to IDs used for coverage mapping.
257 llvm::SmallDenseMap
<FileID
, std::pair
<unsigned, SourceLocation
>, 8>
261 /// The coverage mapping regions for this function
262 llvm::SmallVector
<CounterMappingRegion
, 32> MappingRegions
;
263 /// The source mapping regions for this function.
264 std::vector
<SourceMappingRegion
> SourceRegions
;
266 /// A set of regions which can be used as a filter.
268 /// It is produced by emitExpansionRegions() and is used in
269 /// emitSourceRegions() to suppress producing code regions if
270 /// the same area is covered by expansion regions.
271 typedef llvm::SmallSet
<std::pair
<SourceLocation
, SourceLocation
>, 8>
274 CoverageMappingBuilder(CoverageMappingModuleGen
&CVM
, SourceManager
&SM
,
275 const LangOptions
&LangOpts
)
276 : CVM(CVM
), SM(SM
), LangOpts(LangOpts
) {}
278 /// Return the precise end location for the given token.
279 SourceLocation
getPreciseTokenLocEnd(SourceLocation Loc
) {
280 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
281 // macro locations, which we just treat as expanded files.
283 Lexer::MeasureTokenLength(SM
.getSpellingLoc(Loc
), SM
, LangOpts
);
284 return Loc
.getLocWithOffset(TokLen
);
287 /// Return the start location of an included file or expanded macro.
288 SourceLocation
getStartOfFileOrMacro(SourceLocation Loc
) {
290 return Loc
.getLocWithOffset(-SM
.getFileOffset(Loc
));
291 return SM
.getLocForStartOfFile(SM
.getFileID(Loc
));
294 /// Return the end location of an included file or expanded macro.
295 SourceLocation
getEndOfFileOrMacro(SourceLocation Loc
) {
297 return Loc
.getLocWithOffset(SM
.getFileIDSize(SM
.getFileID(Loc
)) -
298 SM
.getFileOffset(Loc
));
299 return SM
.getLocForEndOfFile(SM
.getFileID(Loc
));
302 /// Find out where a macro is expanded. If the immediate result is a
303 /// <scratch space>, keep looking until the result isn't. Return a pair of
304 /// \c SourceLocation. The first object is always the begin sloc of found
305 /// result. The second should be checked by the caller: if it has value, it's
306 /// the end sloc of the found result. Otherwise the while loop didn't get
307 /// executed, which means the location wasn't changed and the caller has to
308 /// learn the end sloc from somewhere else.
309 std::pair
<SourceLocation
, std::optional
<SourceLocation
>>
310 getNonScratchExpansionLoc(SourceLocation Loc
) {
311 std::optional
<SourceLocation
> EndLoc
= std::nullopt
;
312 while (Loc
.isMacroID() &&
313 SM
.isWrittenInScratchSpace(SM
.getSpellingLoc(Loc
))) {
314 auto ExpansionRange
= SM
.getImmediateExpansionRange(Loc
);
315 Loc
= ExpansionRange
.getBegin();
316 EndLoc
= ExpansionRange
.getEnd();
318 return std::make_pair(Loc
, EndLoc
);
321 /// Find out where the current file is included or macro is expanded. If
322 /// \c AcceptScratch is set to false, keep looking for expansions until the
323 /// found sloc is not a <scratch space>.
324 SourceLocation
getIncludeOrExpansionLoc(SourceLocation Loc
,
325 bool AcceptScratch
= true) {
326 if (!Loc
.isMacroID())
327 return SM
.getIncludeLoc(SM
.getFileID(Loc
));
328 Loc
= SM
.getImmediateExpansionRange(Loc
).getBegin();
331 return getNonScratchExpansionLoc(Loc
).first
;
334 /// Return true if \c Loc is a location in a built-in macro.
335 bool isInBuiltin(SourceLocation Loc
) {
336 return SM
.getBufferName(SM
.getSpellingLoc(Loc
)) == "<built-in>";
339 /// Check whether \c Loc is included or expanded from \c Parent.
340 bool isNestedIn(SourceLocation Loc
, FileID Parent
) {
342 Loc
= getIncludeOrExpansionLoc(Loc
);
345 } while (!SM
.isInFileID(Loc
, Parent
));
349 /// Get the start of \c S ignoring macro arguments and builtin macros.
350 SourceLocation
getStart(const Stmt
*S
) {
351 SourceLocation Loc
= S
->getBeginLoc();
352 while (SM
.isMacroArgExpansion(Loc
) || isInBuiltin(Loc
))
353 Loc
= SM
.getImmediateExpansionRange(Loc
).getBegin();
357 /// Get the end of \c S ignoring macro arguments and builtin macros.
358 SourceLocation
getEnd(const Stmt
*S
) {
359 SourceLocation Loc
= S
->getEndLoc();
360 while (SM
.isMacroArgExpansion(Loc
) || isInBuiltin(Loc
))
361 Loc
= SM
.getImmediateExpansionRange(Loc
).getBegin();
362 return getPreciseTokenLocEnd(Loc
);
365 /// Find the set of files we have regions for and assign IDs
367 /// Fills \c Mapping with the virtual file mapping needed to write out
368 /// coverage and collects the necessary file information to emit source and
369 /// expansion regions.
370 void gatherFileIDs(SmallVectorImpl
<unsigned> &Mapping
) {
371 FileIDMapping
.clear();
373 llvm::SmallSet
<FileID
, 8> Visited
;
374 SmallVector
<std::pair
<SourceLocation
, unsigned>, 8> FileLocs
;
375 for (auto &Region
: SourceRegions
) {
376 SourceLocation Loc
= Region
.getBeginLoc();
378 // Replace Region with its definition if it is in <scratch space>.
379 auto NonScratchExpansionLoc
= getNonScratchExpansionLoc(Loc
);
380 auto EndLoc
= NonScratchExpansionLoc
.second
;
381 if (EndLoc
.has_value()) {
382 Loc
= NonScratchExpansionLoc
.first
;
383 Region
.setStartLoc(Loc
);
384 Region
.setEndLoc(EndLoc
.value());
387 // Replace Loc with FileLoc if it is expanded with system headers.
388 if (!SystemHeadersCoverage
&& SM
.isInSystemMacro(Loc
)) {
389 auto BeginLoc
= SM
.getSpellingLoc(Loc
);
390 auto EndLoc
= SM
.getSpellingLoc(Region
.getEndLoc());
391 if (SM
.isWrittenInSameFile(BeginLoc
, EndLoc
)) {
392 Loc
= SM
.getFileLoc(Loc
);
393 Region
.setStartLoc(Loc
);
394 Region
.setEndLoc(SM
.getFileLoc(Region
.getEndLoc()));
398 FileID File
= SM
.getFileID(Loc
);
399 if (!Visited
.insert(File
).second
)
402 assert(SystemHeadersCoverage
||
403 !SM
.isInSystemHeader(SM
.getSpellingLoc(Loc
)));
406 for (SourceLocation Parent
= getIncludeOrExpansionLoc(Loc
);
407 Parent
.isValid(); Parent
= getIncludeOrExpansionLoc(Parent
))
409 FileLocs
.push_back(std::make_pair(Loc
, Depth
));
411 llvm::stable_sort(FileLocs
, llvm::less_second());
413 for (const auto &FL
: FileLocs
) {
414 SourceLocation Loc
= FL
.first
;
415 FileID SpellingFile
= SM
.getDecomposedSpellingLoc(Loc
).first
;
416 auto Entry
= SM
.getFileEntryRefForID(SpellingFile
);
420 FileIDMapping
[SM
.getFileID(Loc
)] = std::make_pair(Mapping
.size(), Loc
);
421 Mapping
.push_back(CVM
.getFileID(*Entry
));
425 /// Get the coverage mapping file ID for \c Loc.
427 /// If such file id doesn't exist, return std::nullopt.
428 std::optional
<unsigned> getCoverageFileID(SourceLocation Loc
) {
429 auto Mapping
= FileIDMapping
.find(SM
.getFileID(Loc
));
430 if (Mapping
!= FileIDMapping
.end())
431 return Mapping
->second
.first
;
435 /// This shrinks the skipped range if it spans a line that contains a
436 /// non-comment token. If shrinking the skipped range would make it empty,
437 /// this returns std::nullopt.
438 /// Note this function can potentially be expensive because
439 /// getSpellingLineNumber uses getLineNumber, which is expensive.
440 std::optional
<SpellingRegion
> adjustSkippedRange(SourceManager
&SM
,
441 SourceLocation LocStart
,
442 SourceLocation LocEnd
,
443 SourceLocation PrevTokLoc
,
444 SourceLocation NextTokLoc
) {
445 SpellingRegion SR
{SM
, LocStart
, LocEnd
};
447 if (PrevTokLoc
.isValid() && SM
.isWrittenInSameFile(LocStart
, PrevTokLoc
) &&
448 SR
.LineStart
== SM
.getSpellingLineNumber(PrevTokLoc
))
450 if (NextTokLoc
.isValid() && SM
.isWrittenInSameFile(LocEnd
, NextTokLoc
) &&
451 SR
.LineEnd
== SM
.getSpellingLineNumber(NextTokLoc
)) {
455 if (SR
.isInSourceOrder())
460 /// Gather all the regions that were skipped by the preprocessor
461 /// using the constructs like #if or comments.
462 void gatherSkippedRegions() {
463 /// An array of the minimum lineStarts and the maximum lineEnds
464 /// for mapping regions from the appropriate source files.
465 llvm::SmallVector
<std::pair
<unsigned, unsigned>, 8> FileLineRanges
;
466 FileLineRanges
.resize(
467 FileIDMapping
.size(),
468 std::make_pair(std::numeric_limits
<unsigned>::max(), 0));
469 for (const auto &R
: MappingRegions
) {
470 FileLineRanges
[R
.FileID
].first
=
471 std::min(FileLineRanges
[R
.FileID
].first
, R
.LineStart
);
472 FileLineRanges
[R
.FileID
].second
=
473 std::max(FileLineRanges
[R
.FileID
].second
, R
.LineEnd
);
476 auto SkippedRanges
= CVM
.getSourceInfo().getSkippedRanges();
477 for (auto &I
: SkippedRanges
) {
478 SourceRange Range
= I
.Range
;
479 auto LocStart
= Range
.getBegin();
480 auto LocEnd
= Range
.getEnd();
481 assert(SM
.isWrittenInSameFile(LocStart
, LocEnd
) &&
482 "region spans multiple files");
484 auto CovFileID
= getCoverageFileID(LocStart
);
487 std::optional
<SpellingRegion
> SR
;
489 SR
= adjustSkippedRange(SM
, LocStart
, LocEnd
, I
.PrevTokLoc
,
491 else if (I
.isPPIfElse() || I
.isEmptyLine())
492 SR
= {SM
, LocStart
, LocEnd
};
496 auto Region
= CounterMappingRegion::makeSkipped(
497 *CovFileID
, SR
->LineStart
, SR
->ColumnStart
, SR
->LineEnd
,
499 // Make sure that we only collect the regions that are inside
500 // the source code of this function.
501 if (Region
.LineStart
>= FileLineRanges
[*CovFileID
].first
&&
502 Region
.LineEnd
<= FileLineRanges
[*CovFileID
].second
)
503 MappingRegions
.push_back(Region
);
507 /// Generate the coverage counter mapping regions from collected
509 void emitSourceRegions(const SourceRegionFilter
&Filter
) {
510 for (const auto &Region
: SourceRegions
) {
511 assert(Region
.hasEndLoc() && "incomplete region");
513 SourceLocation LocStart
= Region
.getBeginLoc();
514 assert(SM
.getFileID(LocStart
).isValid() && "region in invalid file");
516 // Ignore regions from system headers unless collecting coverage from
517 // system headers is explicitly enabled.
518 if (!SystemHeadersCoverage
&&
519 SM
.isInSystemHeader(SM
.getSpellingLoc(LocStart
))) {
520 assert(!Region
.isMCDCBranch() && !Region
.isMCDCDecision() &&
521 "Don't suppress the condition in system headers");
525 auto CovFileID
= getCoverageFileID(LocStart
);
526 // Ignore regions that don't have a file, such as builtin macros.
528 assert(!Region
.isMCDCBranch() && !Region
.isMCDCDecision() &&
529 "Don't suppress the condition in non-file regions");
533 SourceLocation LocEnd
= Region
.getEndLoc();
534 assert(SM
.isWrittenInSameFile(LocStart
, LocEnd
) &&
535 "region spans multiple files");
537 // Don't add code regions for the area covered by expansion regions.
538 // This not only suppresses redundant regions, but sometimes prevents
539 // creating regions with wrong counters if, for example, a statement's
540 // body ends at the end of a nested macro.
541 if (Filter
.count(std::make_pair(LocStart
, LocEnd
))) {
542 assert(!Region
.isMCDCBranch() && !Region
.isMCDCDecision() &&
543 "Don't suppress the condition");
547 // Find the spelling locations for the mapping region.
548 SpellingRegion SR
{SM
, LocStart
, LocEnd
};
549 assert(SR
.isInSourceOrder() && "region start and end out of order");
551 if (Region
.isGap()) {
552 MappingRegions
.push_back(CounterMappingRegion::makeGapRegion(
553 Region
.getCounter(), *CovFileID
, SR
.LineStart
, SR
.ColumnStart
,
554 SR
.LineEnd
, SR
.ColumnEnd
));
555 } else if (Region
.isSkipped()) {
556 MappingRegions
.push_back(CounterMappingRegion::makeSkipped(
557 *CovFileID
, SR
.LineStart
, SR
.ColumnStart
, SR
.LineEnd
,
559 } else if (Region
.isBranch()) {
560 MappingRegions
.push_back(CounterMappingRegion::makeBranchRegion(
561 Region
.getCounter(), Region
.getFalseCounter(), *CovFileID
,
562 SR
.LineStart
, SR
.ColumnStart
, SR
.LineEnd
, SR
.ColumnEnd
,
563 Region
.getMCDCParams()));
564 } else if (Region
.isMCDCDecision()) {
565 MappingRegions
.push_back(CounterMappingRegion::makeDecisionRegion(
566 Region
.getMCDCDecisionParams(), *CovFileID
, SR
.LineStart
,
567 SR
.ColumnStart
, SR
.LineEnd
, SR
.ColumnEnd
));
569 MappingRegions
.push_back(CounterMappingRegion::makeRegion(
570 Region
.getCounter(), *CovFileID
, SR
.LineStart
, SR
.ColumnStart
,
571 SR
.LineEnd
, SR
.ColumnEnd
));
576 /// Generate expansion regions for each virtual file we've seen.
577 SourceRegionFilter
emitExpansionRegions() {
578 SourceRegionFilter Filter
;
579 for (const auto &FM
: FileIDMapping
) {
580 SourceLocation ExpandedLoc
= FM
.second
.second
;
581 SourceLocation ParentLoc
= getIncludeOrExpansionLoc(ExpandedLoc
, false);
582 if (ParentLoc
.isInvalid())
585 auto ParentFileID
= getCoverageFileID(ParentLoc
);
588 auto ExpandedFileID
= getCoverageFileID(ExpandedLoc
);
589 assert(ExpandedFileID
&& "expansion in uncovered file");
591 SourceLocation LocEnd
= getPreciseTokenLocEnd(ParentLoc
);
592 assert(SM
.isWrittenInSameFile(ParentLoc
, LocEnd
) &&
593 "region spans multiple files");
594 Filter
.insert(std::make_pair(ParentLoc
, LocEnd
));
596 SpellingRegion SR
{SM
, ParentLoc
, LocEnd
};
597 assert(SR
.isInSourceOrder() && "region start and end out of order");
598 MappingRegions
.push_back(CounterMappingRegion::makeExpansion(
599 *ParentFileID
, *ExpandedFileID
, SR
.LineStart
, SR
.ColumnStart
,
600 SR
.LineEnd
, SR
.ColumnEnd
));
606 /// Creates unreachable coverage regions for the functions that
608 struct EmptyCoverageMappingBuilder
: public CoverageMappingBuilder
{
609 EmptyCoverageMappingBuilder(CoverageMappingModuleGen
&CVM
, SourceManager
&SM
,
610 const LangOptions
&LangOpts
)
611 : CoverageMappingBuilder(CVM
, SM
, LangOpts
) {}
613 void VisitDecl(const Decl
*D
) {
616 auto Body
= D
->getBody();
617 SourceLocation Start
= getStart(Body
);
618 SourceLocation End
= getEnd(Body
);
619 if (!SM
.isWrittenInSameFile(Start
, End
)) {
620 // Walk up to find the common ancestor.
621 // Correct the locations accordingly.
622 FileID StartFileID
= SM
.getFileID(Start
);
623 FileID EndFileID
= SM
.getFileID(End
);
624 while (StartFileID
!= EndFileID
&& !isNestedIn(End
, StartFileID
)) {
625 Start
= getIncludeOrExpansionLoc(Start
);
626 assert(Start
.isValid() &&
627 "Declaration start location not nested within a known region");
628 StartFileID
= SM
.getFileID(Start
);
630 while (StartFileID
!= EndFileID
) {
631 End
= getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End
));
632 assert(End
.isValid() &&
633 "Declaration end location not nested within a known region");
634 EndFileID
= SM
.getFileID(End
);
637 SourceRegions
.emplace_back(Counter(), Start
, End
);
640 /// Write the mapping data to the output stream
641 void write(llvm::raw_ostream
&OS
) {
642 SmallVector
<unsigned, 16> FileIDMapping
;
643 gatherFileIDs(FileIDMapping
);
644 emitSourceRegions(SourceRegionFilter());
646 if (MappingRegions
.empty())
649 CoverageMappingWriter
Writer(FileIDMapping
, {}, MappingRegions
);
654 /// A wrapper object for maintaining stacks to track the resursive AST visitor
655 /// walks for the purpose of assigning IDs to leaf-level conditions measured by
656 /// MC/DC. The object is created with a reference to the MCDCBitmapMap that was
657 /// created during the initial AST walk. The presence of a bitmap associated
658 /// with a boolean expression (top-level logical operator nest) indicates that
659 /// the boolean expression qualified for MC/DC. The resulting condition IDs
660 /// are preserved in a map reference that is also provided during object
662 struct MCDCCoverageBuilder
{
664 /// The AST walk recursively visits nested logical-AND or logical-OR binary
665 /// operator nodes and then visits their LHS and RHS children nodes. As this
666 /// happens, the algorithm will assign IDs to each operator's LHS and RHS side
667 /// as the walk moves deeper into the nest. At each level of the recursive
668 /// nest, the LHS and RHS may actually correspond to larger subtrees (not
669 /// leaf-conditions). If this is the case, when that node is visited, the ID
670 /// assigned to the subtree is re-assigned to its LHS, and a new ID is given
671 /// to its RHS. At the end of the walk, all leaf-level conditions will have a
672 /// unique ID -- keep in mind that the final set of IDs may not be in
673 /// numerical order from left to right.
675 /// Example: "x = (A && B) || (C && D) || (D && F)"
678 /// (A && B) || (C && D) || (D && F)
679 /// ^-------LHS--------^ ^-RHS--^
682 /// Visit LHS-Depth2:
683 /// (A && B) || (C && D)
684 /// ^-LHS--^ ^-RHS--^
687 /// Visit LHS-Depth3:
692 /// Visit RHS-Depth3:
697 /// Visit RHS-Depth2: (D && F)
702 /// (A && B) || (C && D) || (D && F)
703 /// ID=1 ID=4 ID=3 ID=5 ID=2 ID=6
705 /// A node ID of '0' always means MC/DC isn't being tracked.
707 /// As the AST walk proceeds recursively, the algorithm will also use a stack
708 /// to track the IDs of logical-AND and logical-OR operations on the RHS so
709 /// that it can be determined which nodes are executed next, depending on how
710 /// a LHS or RHS of a logical-AND or logical-OR is evaluated. This
711 /// information relies on the assigned IDs and are embedded within the
712 /// coverage region IDs of each branch region associated with a leaf-level
713 /// condition. This information helps the visualization tool reconstruct all
714 /// possible test vectors for the purposes of MC/DC analysis. If a "next" node
715 /// ID is '0', it means it's the end of the test vector. The following rules
718 /// For logical-AND ("LHS && RHS"):
719 /// - If LHS is TRUE, execution goes to the RHS node.
720 /// - If LHS is FALSE, execution goes to the LHS node of the next logical-OR.
721 /// If that does not exist, execution exits (ID == 0).
723 /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
724 /// If that does not exist, execution exits (ID == 0).
725 /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
726 /// If that does not exist, execution exits (ID == 0).
728 /// For logical-OR ("LHS || RHS"):
729 /// - If LHS is TRUE, execution goes to the LHS node of the next logical-AND.
730 /// If that does not exist, execution exits (ID == 0).
731 /// - If LHS is FALSE, execution goes to the RHS node.
733 /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
734 /// If that does not exist, execution exits (ID == 0).
735 /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
736 /// If that does not exist, execution exits (ID == 0).
738 /// Finally, the condition IDs are also used when instrumenting the code to
739 /// indicate a unique offset into a temporary bitmap that represents the true
740 /// or false evaluation of that particular condition.
742 /// NOTE regarding the use of CodeGenFunction::stripCond(). Even though, for
743 /// simplicity, parentheses and unary logical-NOT operators are considered
744 /// part of their underlying condition for both MC/DC and branch coverage, the
745 /// condition IDs themselves are assigned and tracked using the underlying
746 /// condition itself. This is done solely for consistency since parentheses
747 /// and logical-NOTs are ignored when checking whether the condition is
748 /// actually an instrumentable condition. This can also make debugging a bit
754 llvm::SmallVector
<mcdc::ConditionIDs
> DecisionStack
;
755 MCDC::State
&MCDCState
;
756 const Stmt
*DecisionStmt
= nullptr;
757 mcdc::ConditionID NextID
= 0;
758 bool NotMapped
= false;
760 /// Represent a sentinel value as a pair of final decisions for the bottom
762 static constexpr mcdc::ConditionIDs DecisionStackSentinel
{-1, -1};
764 /// Is this a logical-AND operation?
765 bool isLAnd(const BinaryOperator
*E
) const {
766 return E
->getOpcode() == BO_LAnd
;
770 MCDCCoverageBuilder(CodeGenModule
&CGM
, MCDC::State
&MCDCState
)
771 : CGM(CGM
), DecisionStack(1, DecisionStackSentinel
),
772 MCDCState(MCDCState
) {}
774 /// Return whether the build of the control flow map is at the top-level
775 /// (root) of a logical operator nest in a boolean expression prior to the
776 /// assignment of condition IDs.
777 bool isIdle() const { return (NextID
== 0 && !NotMapped
); }
779 /// Return whether any IDs have been assigned in the build of the control
780 /// flow map, indicating that the map is being generated for this boolean
782 bool isBuilding() const { return (NextID
> 0); }
784 /// Set the given condition's ID.
785 void setCondID(const Expr
*Cond
, mcdc::ConditionID ID
) {
786 MCDCState
.BranchByStmt
[CodeGenFunction::stripCond(Cond
)] = {ID
,
790 /// Return the ID of a given condition.
791 mcdc::ConditionID
getCondID(const Expr
*Cond
) const {
792 auto I
= MCDCState
.BranchByStmt
.find(CodeGenFunction::stripCond(Cond
));
793 if (I
== MCDCState
.BranchByStmt
.end())
799 /// Return the LHS Decision ([0,0] if not set).
800 const mcdc::ConditionIDs
&back() const { return DecisionStack
.back(); }
802 /// Push the binary operator statement to track the nest level and assign IDs
803 /// to the operator's LHS and RHS. The RHS may be a larger subtree that is
804 /// broken up on successive levels.
805 void pushAndAssignIDs(const BinaryOperator
*E
) {
806 if (!CGM
.getCodeGenOpts().MCDCCoverage
)
809 // If binary expression is disqualified, don't do mapping.
811 !MCDCState
.DecisionByStmt
.contains(CodeGenFunction::stripCond(E
)))
814 // Don't go any further if we don't need to map condition IDs.
820 assert(MCDCState
.DecisionByStmt
.contains(E
));
823 const mcdc::ConditionIDs
&ParentDecision
= DecisionStack
.back();
825 // If the operator itself has an assigned ID, this means it represents a
826 // larger subtree. In this case, assign that ID to its LHS node. Its RHS
827 // will receive a new ID below. Otherwise, assign ID+1 to LHS.
828 if (MCDCState
.BranchByStmt
.contains(CodeGenFunction::stripCond(E
)))
829 setCondID(E
->getLHS(), getCondID(E
));
831 setCondID(E
->getLHS(), NextID
++);
833 // Assign a ID+1 for the RHS.
834 mcdc::ConditionID RHSid
= NextID
++;
835 setCondID(E
->getRHS(), RHSid
);
837 // Push the LHS decision IDs onto the DecisionStack.
839 DecisionStack
.push_back({ParentDecision
[false], RHSid
});
841 DecisionStack
.push_back({RHSid
, ParentDecision
[true]});
844 /// Pop and return the LHS Decision ([0,0] if not set).
845 mcdc::ConditionIDs
pop() {
846 if (!CGM
.getCodeGenOpts().MCDCCoverage
|| NotMapped
)
847 return DecisionStackSentinel
;
849 assert(DecisionStack
.size() > 1);
850 return DecisionStack
.pop_back_val();
853 /// Return the total number of conditions and reset the state. The number of
854 /// conditions is zero if the expression isn't mapped.
855 unsigned getTotalConditionsAndReset(const BinaryOperator
*E
) {
856 if (!CGM
.getCodeGenOpts().MCDCCoverage
)
860 assert(DecisionStack
.size() == 1);
862 // Reset state if not doing mapping.
869 // Set number of conditions and reset.
870 unsigned TotalConds
= NextID
;
872 // Reset ID back to beginning.
879 /// A StmtVisitor that creates coverage mapping regions which map
880 /// from the source code locations to the PGO counters.
881 struct CounterCoverageMappingBuilder
882 : public CoverageMappingBuilder
,
883 public ConstStmtVisitor
<CounterCoverageMappingBuilder
> {
884 /// The map of statements to count values.
885 llvm::DenseMap
<const Stmt
*, unsigned> &CounterMap
;
887 MCDC::State
&MCDCState
;
889 /// A stack of currently live regions.
890 llvm::SmallVector
<SourceMappingRegion
> RegionStack
;
892 /// Set if the Expr should be handled as a leaf even if it is kind of binary
893 /// logical ops (&&, ||).
894 llvm::DenseSet
<const Stmt
*> LeafExprSet
;
896 /// An object to manage MCDC regions.
897 MCDCCoverageBuilder MCDCBuilder
;
899 CounterExpressionBuilder Builder
;
901 /// A location in the most recently visited file or macro.
903 /// This is used to adjust the active source regions appropriately when
904 /// expressions cross file or macro boundaries.
905 SourceLocation MostRecentLocation
;
907 /// Whether the visitor at a terminate statement.
908 bool HasTerminateStmt
= false;
910 /// Gap region counter after terminate statement.
911 Counter GapRegionCounter
;
913 /// Return a counter for the subtraction of \c RHS from \c LHS
914 Counter
subtractCounters(Counter LHS
, Counter RHS
, bool Simplify
= true) {
915 assert(!llvm::EnableSingleByteCoverage
&&
916 "cannot add counters when single byte coverage mode is enabled");
917 return Builder
.subtract(LHS
, RHS
, Simplify
);
920 /// Return a counter for the sum of \c LHS and \c RHS.
921 Counter
addCounters(Counter LHS
, Counter RHS
, bool Simplify
= true) {
922 assert(!llvm::EnableSingleByteCoverage
&&
923 "cannot add counters when single byte coverage mode is enabled");
924 return Builder
.add(LHS
, RHS
, Simplify
);
927 Counter
addCounters(Counter C1
, Counter C2
, Counter C3
,
928 bool Simplify
= true) {
929 assert(!llvm::EnableSingleByteCoverage
&&
930 "cannot add counters when single byte coverage mode is enabled");
931 return addCounters(addCounters(C1
, C2
, Simplify
), C3
, Simplify
);
934 /// Return the region counter for the given statement.
936 /// This should only be called on statements that have a dedicated counter.
937 Counter
getRegionCounter(const Stmt
*S
) {
938 return Counter::getCounter(CounterMap
[S
]);
941 /// Push a region onto the stack.
943 /// Returns the index on the stack where the region was pushed. This can be
944 /// used with popRegions to exit a "scope", ending the region that was pushed.
945 size_t pushRegion(Counter Count
,
946 std::optional
<SourceLocation
> StartLoc
= std::nullopt
,
947 std::optional
<SourceLocation
> EndLoc
= std::nullopt
,
948 std::optional
<Counter
> FalseCount
= std::nullopt
,
949 const mcdc::Parameters
&BranchParams
= std::monostate()) {
951 if (StartLoc
&& !FalseCount
) {
952 MostRecentLocation
= *StartLoc
;
955 // If either of these locations is invalid, something elsewhere in the
956 // compiler has broken.
957 assert((!StartLoc
|| StartLoc
->isValid()) && "Start location is not valid");
958 assert((!EndLoc
|| EndLoc
->isValid()) && "End location is not valid");
960 // However, we can still recover without crashing.
961 // If either location is invalid, set it to std::nullopt to avoid
962 // letting users of RegionStack think that region has a valid start/end
964 if (StartLoc
&& StartLoc
->isInvalid())
965 StartLoc
= std::nullopt
;
966 if (EndLoc
&& EndLoc
->isInvalid())
967 EndLoc
= std::nullopt
;
968 RegionStack
.emplace_back(Count
, FalseCount
, BranchParams
, StartLoc
, EndLoc
);
970 return RegionStack
.size() - 1;
973 size_t pushRegion(const mcdc::DecisionParameters
&DecisionParams
,
974 std::optional
<SourceLocation
> StartLoc
= std::nullopt
,
975 std::optional
<SourceLocation
> EndLoc
= std::nullopt
) {
977 RegionStack
.emplace_back(DecisionParams
, StartLoc
, EndLoc
);
979 return RegionStack
.size() - 1;
982 size_t locationDepth(SourceLocation Loc
) {
984 while (Loc
.isValid()) {
985 Loc
= getIncludeOrExpansionLoc(Loc
);
991 /// Pop regions from the stack into the function's list of regions.
993 /// Adds all regions from \c ParentIndex to the top of the stack to the
994 /// function's \c SourceRegions.
995 void popRegions(size_t ParentIndex
) {
996 assert(RegionStack
.size() >= ParentIndex
&& "parent not in stack");
997 while (RegionStack
.size() > ParentIndex
) {
998 SourceMappingRegion
&Region
= RegionStack
.back();
999 if (Region
.hasStartLoc() &&
1000 (Region
.hasEndLoc() || RegionStack
[ParentIndex
].hasEndLoc())) {
1001 SourceLocation StartLoc
= Region
.getBeginLoc();
1002 SourceLocation EndLoc
= Region
.hasEndLoc()
1003 ? Region
.getEndLoc()
1004 : RegionStack
[ParentIndex
].getEndLoc();
1005 bool isBranch
= Region
.isBranch();
1006 size_t StartDepth
= locationDepth(StartLoc
);
1007 size_t EndDepth
= locationDepth(EndLoc
);
1008 while (!SM
.isWrittenInSameFile(StartLoc
, EndLoc
)) {
1009 bool UnnestStart
= StartDepth
>= EndDepth
;
1010 bool UnnestEnd
= EndDepth
>= StartDepth
;
1012 // The region ends in a nested file or macro expansion. If the
1013 // region is not a branch region, create a separate region for each
1014 // expansion, and for all regions, update the EndLoc. Branch
1015 // regions should not be split in order to keep a straightforward
1016 // correspondance between the region and its associated branch
1017 // condition, even if the condition spans multiple depths.
1018 SourceLocation NestedLoc
= getStartOfFileOrMacro(EndLoc
);
1019 assert(SM
.isWrittenInSameFile(NestedLoc
, EndLoc
));
1021 if (!isBranch
&& !isRegionAlreadyAdded(NestedLoc
, EndLoc
))
1022 SourceRegions
.emplace_back(Region
.getCounter(), NestedLoc
,
1025 EndLoc
= getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc
));
1026 if (EndLoc
.isInvalid())
1027 llvm::report_fatal_error(
1028 "File exit not handled before popRegions");
1032 // The region ends in a nested file or macro expansion. If the
1033 // region is not a branch region, create a separate region for each
1034 // expansion, and for all regions, update the StartLoc. Branch
1035 // regions should not be split in order to keep a straightforward
1036 // correspondance between the region and its associated branch
1037 // condition, even if the condition spans multiple depths.
1038 SourceLocation NestedLoc
= getEndOfFileOrMacro(StartLoc
);
1039 assert(SM
.isWrittenInSameFile(StartLoc
, NestedLoc
));
1041 if (!isBranch
&& !isRegionAlreadyAdded(StartLoc
, NestedLoc
))
1042 SourceRegions
.emplace_back(Region
.getCounter(), StartLoc
,
1045 StartLoc
= getIncludeOrExpansionLoc(StartLoc
);
1046 if (StartLoc
.isInvalid())
1047 llvm::report_fatal_error(
1048 "File exit not handled before popRegions");
1052 Region
.setStartLoc(StartLoc
);
1053 Region
.setEndLoc(EndLoc
);
1056 MostRecentLocation
= EndLoc
;
1057 // If this region happens to span an entire expansion, we need to
1058 // make sure we don't overlap the parent region with it.
1059 if (StartLoc
== getStartOfFileOrMacro(StartLoc
) &&
1060 EndLoc
== getEndOfFileOrMacro(EndLoc
))
1061 MostRecentLocation
= getIncludeOrExpansionLoc(EndLoc
);
1064 assert(SM
.isWrittenInSameFile(Region
.getBeginLoc(), EndLoc
));
1065 assert(SpellingRegion(SM
, Region
).isInSourceOrder());
1066 SourceRegions
.push_back(Region
);
1068 RegionStack
.pop_back();
1072 /// Return the currently active region.
1073 SourceMappingRegion
&getRegion() {
1074 assert(!RegionStack
.empty() && "statement has no region");
1075 return RegionStack
.back();
1078 /// Propagate counts through the children of \p S if \p VisitChildren is true.
1079 /// Otherwise, only emit a count for \p S itself.
1080 Counter
propagateCounts(Counter TopCount
, const Stmt
*S
,
1081 bool VisitChildren
= true) {
1082 SourceLocation StartLoc
= getStart(S
);
1083 SourceLocation EndLoc
= getEnd(S
);
1084 size_t Index
= pushRegion(TopCount
, StartLoc
, EndLoc
);
1087 Counter ExitCount
= getRegion().getCounter();
1090 // The statement may be spanned by an expansion. Make sure we handle a file
1091 // exit out of this expansion before moving to the next statement.
1092 if (SM
.isBeforeInTranslationUnit(StartLoc
, S
->getBeginLoc()))
1093 MostRecentLocation
= EndLoc
;
1098 /// Create a Branch Region around an instrumentable condition for coverage
1099 /// and add it to the function's SourceRegions. A branch region tracks a
1100 /// "True" counter and a "False" counter for boolean expressions that
1101 /// result in the generation of a branch.
1102 void createBranchRegion(const Expr
*C
, Counter TrueCnt
, Counter FalseCnt
,
1103 const mcdc::ConditionIDs
&Conds
= {}) {
1104 // Check for NULL conditions.
1108 // Ensure we are an instrumentable condition (i.e. no "&&" or "||"). Push
1109 // region onto RegionStack but immediately pop it (which adds it to the
1110 // function's SourceRegions) because it doesn't apply to any other source
1111 // code other than the Condition.
1112 // With !SystemHeadersCoverage, binary logical ops in system headers may be
1113 // treated as instrumentable conditions.
1114 if (CodeGenFunction::isInstrumentedCondition(C
) ||
1115 LeafExprSet
.count(CodeGenFunction::stripCond(C
))) {
1116 mcdc::Parameters BranchParams
;
1117 mcdc::ConditionID ID
= MCDCBuilder
.getCondID(C
);
1119 BranchParams
= mcdc::BranchParameters
{ID
, Conds
};
1121 // If a condition can fold to true or false, the corresponding branch
1122 // will be removed. Create a region with both counters hard-coded to
1123 // zero. This allows us to visualize them in a special way.
1124 // Alternatively, we can prevent any optimization done via
1125 // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
1126 // CodeGenFunction.c always returns false, but that is very heavy-handed.
1127 Expr::EvalResult Result
;
1128 if (C
->EvaluateAsInt(Result
, CVM
.getCodeGenModule().getContext())) {
1129 if (Result
.Val
.getInt().getBoolValue())
1130 FalseCnt
= Counter::getZero();
1132 TrueCnt
= Counter::getZero();
1135 pushRegion(TrueCnt
, getStart(C
), getEnd(C
), FalseCnt
, BranchParams
));
1139 /// Create a Decision Region with a BitmapIdx and number of Conditions. This
1140 /// type of region "contains" branch regions, one for each of the conditions.
1141 /// The visualization tool will group everything together.
1142 void createDecisionRegion(const Expr
*C
,
1143 const mcdc::DecisionParameters
&DecisionParams
) {
1144 popRegions(pushRegion(DecisionParams
, getStart(C
), getEnd(C
)));
1147 /// Create a Branch Region around a SwitchCase for code coverage
1148 /// and add it to the function's SourceRegions.
1149 void createSwitchCaseRegion(const SwitchCase
*SC
, Counter TrueCnt
) {
1150 // Push region onto RegionStack but immediately pop it (which adds it to
1151 // the function's SourceRegions) because it doesn't apply to any other
1152 // source other than the SwitchCase.
1153 popRegions(pushRegion(TrueCnt
, getStart(SC
), SC
->getColonLoc(),
1154 Counter::getZero()));
1157 /// Check whether a region with bounds \c StartLoc and \c EndLoc
1158 /// is already added to \c SourceRegions.
1159 bool isRegionAlreadyAdded(SourceLocation StartLoc
, SourceLocation EndLoc
,
1160 bool isBranch
= false) {
1161 return llvm::any_of(
1162 llvm::reverse(SourceRegions
), [&](const SourceMappingRegion
&Region
) {
1163 return Region
.getBeginLoc() == StartLoc
&&
1164 Region
.getEndLoc() == EndLoc
&& Region
.isBranch() == isBranch
;
1168 /// Adjust the most recently visited location to \c EndLoc.
1170 /// This should be used after visiting any statements in non-source order.
1171 void adjustForOutOfOrderTraversal(SourceLocation EndLoc
) {
1172 MostRecentLocation
= EndLoc
;
1173 // The code region for a whole macro is created in handleFileExit() when
1174 // it detects exiting of the virtual file of that macro. If we visited
1175 // statements in non-source order, we might already have such a region
1176 // added, for example, if a body of a loop is divided among multiple
1177 // macros. Avoid adding duplicate regions in such case.
1178 if (getRegion().hasEndLoc() &&
1179 MostRecentLocation
== getEndOfFileOrMacro(MostRecentLocation
) &&
1180 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation
),
1181 MostRecentLocation
, getRegion().isBranch()))
1182 MostRecentLocation
= getIncludeOrExpansionLoc(MostRecentLocation
);
1185 /// Adjust regions and state when \c NewLoc exits a file.
1187 /// If moving from our most recently tracked location to \c NewLoc exits any
1188 /// files, this adjusts our current region stack and creates the file regions
1189 /// for the exited file.
1190 void handleFileExit(SourceLocation NewLoc
) {
1191 if (NewLoc
.isInvalid() ||
1192 SM
.isWrittenInSameFile(MostRecentLocation
, NewLoc
))
1195 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
1196 // find the common ancestor.
1197 SourceLocation LCA
= NewLoc
;
1198 FileID ParentFile
= SM
.getFileID(LCA
);
1199 while (!isNestedIn(MostRecentLocation
, ParentFile
)) {
1200 LCA
= getIncludeOrExpansionLoc(LCA
);
1201 if (LCA
.isInvalid() || SM
.isWrittenInSameFile(LCA
, MostRecentLocation
)) {
1202 // Since there isn't a common ancestor, no file was exited. We just need
1203 // to adjust our location to the new file.
1204 MostRecentLocation
= NewLoc
;
1207 ParentFile
= SM
.getFileID(LCA
);
1210 llvm::SmallSet
<SourceLocation
, 8> StartLocs
;
1211 std::optional
<Counter
> ParentCounter
;
1212 for (SourceMappingRegion
&I
: llvm::reverse(RegionStack
)) {
1213 if (!I
.hasStartLoc())
1215 SourceLocation Loc
= I
.getBeginLoc();
1216 if (!isNestedIn(Loc
, ParentFile
)) {
1217 ParentCounter
= I
.getCounter();
1221 while (!SM
.isInFileID(Loc
, ParentFile
)) {
1222 // The most nested region for each start location is the one with the
1223 // correct count. We avoid creating redundant regions by stopping once
1224 // we've seen this region.
1225 if (StartLocs
.insert(Loc
).second
) {
1227 SourceRegions
.emplace_back(I
.getCounter(), I
.getFalseCounter(),
1228 I
.getMCDCParams(), Loc
,
1229 getEndOfFileOrMacro(Loc
), I
.isBranch());
1231 SourceRegions
.emplace_back(I
.getCounter(), Loc
,
1232 getEndOfFileOrMacro(Loc
));
1234 Loc
= getIncludeOrExpansionLoc(Loc
);
1236 I
.setStartLoc(getPreciseTokenLocEnd(Loc
));
1239 if (ParentCounter
) {
1240 // If the file is contained completely by another region and doesn't
1241 // immediately start its own region, the whole file gets a region
1242 // corresponding to the parent.
1243 SourceLocation Loc
= MostRecentLocation
;
1244 while (isNestedIn(Loc
, ParentFile
)) {
1245 SourceLocation FileStart
= getStartOfFileOrMacro(Loc
);
1246 if (StartLocs
.insert(FileStart
).second
) {
1247 SourceRegions
.emplace_back(*ParentCounter
, FileStart
,
1248 getEndOfFileOrMacro(Loc
));
1249 assert(SpellingRegion(SM
, SourceRegions
.back()).isInSourceOrder());
1251 Loc
= getIncludeOrExpansionLoc(Loc
);
1255 MostRecentLocation
= NewLoc
;
1258 /// Ensure that \c S is included in the current region.
1259 void extendRegion(const Stmt
*S
) {
1260 SourceMappingRegion
&Region
= getRegion();
1261 SourceLocation StartLoc
= getStart(S
);
1263 handleFileExit(StartLoc
);
1264 if (!Region
.hasStartLoc())
1265 Region
.setStartLoc(StartLoc
);
1268 /// Mark \c S as a terminator, starting a zero region.
1269 void terminateRegion(const Stmt
*S
) {
1271 SourceMappingRegion
&Region
= getRegion();
1272 SourceLocation EndLoc
= getEnd(S
);
1273 if (!Region
.hasEndLoc())
1274 Region
.setEndLoc(EndLoc
);
1275 pushRegion(Counter::getZero());
1276 HasTerminateStmt
= true;
1279 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
1280 std::optional
<SourceRange
> findGapAreaBetween(SourceLocation AfterLoc
,
1281 SourceLocation BeforeLoc
) {
1282 // Some statements (like AttributedStmt and ImplicitValueInitExpr) don't
1283 // have valid source locations. Do not emit a gap region if this is the case
1284 // in either AfterLoc end or BeforeLoc end.
1285 if (AfterLoc
.isInvalid() || BeforeLoc
.isInvalid())
1286 return std::nullopt
;
1288 // If AfterLoc is in function-like macro, use the right parenthesis
1290 if (AfterLoc
.isMacroID()) {
1291 FileID FID
= SM
.getFileID(AfterLoc
);
1292 const SrcMgr::ExpansionInfo
*EI
= &SM
.getSLocEntry(FID
).getExpansion();
1293 if (EI
->isFunctionMacroExpansion())
1294 AfterLoc
= EI
->getExpansionLocEnd();
1297 size_t StartDepth
= locationDepth(AfterLoc
);
1298 size_t EndDepth
= locationDepth(BeforeLoc
);
1299 while (!SM
.isWrittenInSameFile(AfterLoc
, BeforeLoc
)) {
1300 bool UnnestStart
= StartDepth
>= EndDepth
;
1301 bool UnnestEnd
= EndDepth
>= StartDepth
;
1303 assert(SM
.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc
),
1306 BeforeLoc
= getIncludeOrExpansionLoc(BeforeLoc
);
1307 assert(BeforeLoc
.isValid());
1311 assert(SM
.isWrittenInSameFile(AfterLoc
,
1312 getEndOfFileOrMacro(AfterLoc
)));
1314 AfterLoc
= getIncludeOrExpansionLoc(AfterLoc
);
1315 assert(AfterLoc
.isValid());
1316 AfterLoc
= getPreciseTokenLocEnd(AfterLoc
);
1317 assert(AfterLoc
.isValid());
1321 AfterLoc
= getPreciseTokenLocEnd(AfterLoc
);
1322 // If the start and end locations of the gap are both within the same macro
1323 // file, the range may not be in source order.
1324 if (AfterLoc
.isMacroID() || BeforeLoc
.isMacroID())
1325 return std::nullopt
;
1326 if (!SM
.isWrittenInSameFile(AfterLoc
, BeforeLoc
) ||
1327 !SpellingRegion(SM
, AfterLoc
, BeforeLoc
).isInSourceOrder())
1328 return std::nullopt
;
1329 return {{AfterLoc
, BeforeLoc
}};
1332 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
1333 void fillGapAreaWithCount(SourceLocation StartLoc
, SourceLocation EndLoc
,
1335 if (StartLoc
== EndLoc
)
1337 assert(SpellingRegion(SM
, StartLoc
, EndLoc
).isInSourceOrder());
1338 handleFileExit(StartLoc
);
1339 size_t Index
= pushRegion(Count
, StartLoc
, EndLoc
);
1340 getRegion().setGap(true);
1341 handleFileExit(EndLoc
);
1345 /// Find a valid range starting with \p StartingLoc and ending before \p
1347 std::optional
<SourceRange
> findAreaStartingFromTo(SourceLocation StartingLoc
,
1348 SourceLocation BeforeLoc
) {
1349 // If StartingLoc is in function-like macro, use its start location.
1350 if (StartingLoc
.isMacroID()) {
1351 FileID FID
= SM
.getFileID(StartingLoc
);
1352 const SrcMgr::ExpansionInfo
*EI
= &SM
.getSLocEntry(FID
).getExpansion();
1353 if (EI
->isFunctionMacroExpansion())
1354 StartingLoc
= EI
->getExpansionLocStart();
1357 size_t StartDepth
= locationDepth(StartingLoc
);
1358 size_t EndDepth
= locationDepth(BeforeLoc
);
1359 while (!SM
.isWrittenInSameFile(StartingLoc
, BeforeLoc
)) {
1360 bool UnnestStart
= StartDepth
>= EndDepth
;
1361 bool UnnestEnd
= EndDepth
>= StartDepth
;
1363 assert(SM
.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc
),
1366 BeforeLoc
= getIncludeOrExpansionLoc(BeforeLoc
);
1367 assert(BeforeLoc
.isValid());
1371 assert(SM
.isWrittenInSameFile(StartingLoc
,
1372 getStartOfFileOrMacro(StartingLoc
)));
1374 StartingLoc
= getIncludeOrExpansionLoc(StartingLoc
);
1375 assert(StartingLoc
.isValid());
1379 // If the start and end locations of the gap are both within the same macro
1380 // file, the range may not be in source order.
1381 if (StartingLoc
.isMacroID() || BeforeLoc
.isMacroID())
1382 return std::nullopt
;
1383 if (!SM
.isWrittenInSameFile(StartingLoc
, BeforeLoc
) ||
1384 !SpellingRegion(SM
, StartingLoc
, BeforeLoc
).isInSourceOrder())
1385 return std::nullopt
;
1386 return {{StartingLoc
, BeforeLoc
}};
1389 void markSkipped(SourceLocation StartLoc
, SourceLocation BeforeLoc
) {
1390 const auto Skipped
= findAreaStartingFromTo(StartLoc
, BeforeLoc
);
1395 const auto NewStartLoc
= Skipped
->getBegin();
1396 const auto EndLoc
= Skipped
->getEnd();
1398 if (NewStartLoc
== EndLoc
)
1400 assert(SpellingRegion(SM
, NewStartLoc
, EndLoc
).isInSourceOrder());
1401 handleFileExit(NewStartLoc
);
1402 size_t Index
= pushRegion(Counter
{}, NewStartLoc
, EndLoc
);
1403 getRegion().setSkipped(true);
1404 handleFileExit(EndLoc
);
1408 /// Keep counts of breaks and continues inside loops.
1409 struct BreakContinue
{
1411 Counter ContinueCount
;
1413 SmallVector
<BreakContinue
, 8> BreakContinueStack
;
1415 CounterCoverageMappingBuilder(
1416 CoverageMappingModuleGen
&CVM
,
1417 llvm::DenseMap
<const Stmt
*, unsigned> &CounterMap
,
1418 MCDC::State
&MCDCState
, SourceManager
&SM
, const LangOptions
&LangOpts
)
1419 : CoverageMappingBuilder(CVM
, SM
, LangOpts
), CounterMap(CounterMap
),
1420 MCDCState(MCDCState
), MCDCBuilder(CVM
.getCodeGenModule(), MCDCState
) {}
1422 /// Write the mapping data to the output stream
1423 void write(llvm::raw_ostream
&OS
) {
1424 llvm::SmallVector
<unsigned, 8> VirtualFileMapping
;
1425 gatherFileIDs(VirtualFileMapping
);
1426 SourceRegionFilter Filter
= emitExpansionRegions();
1427 emitSourceRegions(Filter
);
1428 gatherSkippedRegions();
1430 if (MappingRegions
.empty())
1433 CoverageMappingWriter
Writer(VirtualFileMapping
, Builder
.getExpressions(),
1438 void VisitStmt(const Stmt
*S
) {
1439 if (S
->getBeginLoc().isValid())
1441 const Stmt
*LastStmt
= nullptr;
1442 bool SaveTerminateStmt
= HasTerminateStmt
;
1443 HasTerminateStmt
= false;
1444 GapRegionCounter
= Counter::getZero();
1445 for (const Stmt
*Child
: S
->children())
1447 // If last statement contains terminate statements, add a gap area
1448 // between the two statements.
1449 if (LastStmt
&& HasTerminateStmt
) {
1450 auto Gap
= findGapAreaBetween(getEnd(LastStmt
), getStart(Child
));
1452 fillGapAreaWithCount(Gap
->getBegin(), Gap
->getEnd(),
1454 SaveTerminateStmt
= true;
1455 HasTerminateStmt
= false;
1460 if (SaveTerminateStmt
)
1461 HasTerminateStmt
= true;
1462 handleFileExit(getEnd(S
));
1465 void VisitDecl(const Decl
*D
) {
1466 Stmt
*Body
= D
->getBody();
1468 // Do not propagate region counts into system headers unless collecting
1469 // coverage from system headers is explicitly enabled.
1470 if (!SystemHeadersCoverage
&& Body
&&
1471 SM
.isInSystemHeader(SM
.getSpellingLoc(getStart(Body
))))
1474 // Do not visit the artificial children nodes of defaulted methods. The
1475 // lexer may not be able to report back precise token end locations for
1476 // these children nodes (llvm.org/PR39822), and moreover users will not be
1477 // able to see coverage for them.
1478 Counter BodyCounter
= getRegionCounter(Body
);
1479 bool Defaulted
= false;
1480 if (auto *Method
= dyn_cast
<CXXMethodDecl
>(D
))
1481 Defaulted
= Method
->isDefaulted();
1482 if (auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(D
)) {
1483 for (auto *Initializer
: Ctor
->inits()) {
1484 if (Initializer
->isWritten()) {
1485 auto *Init
= Initializer
->getInit();
1486 if (getStart(Init
).isValid() && getEnd(Init
).isValid())
1487 propagateCounts(BodyCounter
, Init
);
1492 propagateCounts(BodyCounter
, Body
,
1493 /*VisitChildren=*/!Defaulted
);
1494 assert(RegionStack
.empty() && "Regions entered but never exited");
1497 void VisitReturnStmt(const ReturnStmt
*S
) {
1499 if (S
->getRetValue())
1500 Visit(S
->getRetValue());
1504 void VisitCoroutineBodyStmt(const CoroutineBodyStmt
*S
) {
1506 Visit(S
->getBody());
1509 void VisitCoreturnStmt(const CoreturnStmt
*S
) {
1511 if (S
->getOperand())
1512 Visit(S
->getOperand());
1516 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr
*E
) {
1517 Visit(E
->getOperand());
1520 void VisitCXXThrowExpr(const CXXThrowExpr
*E
) {
1522 if (E
->getSubExpr())
1523 Visit(E
->getSubExpr());
1527 void VisitGotoStmt(const GotoStmt
*S
) { terminateRegion(S
); }
1529 void VisitLabelStmt(const LabelStmt
*S
) {
1530 Counter LabelCount
= getRegionCounter(S
);
1531 SourceLocation Start
= getStart(S
);
1532 // We can't extendRegion here or we risk overlapping with our new region.
1533 handleFileExit(Start
);
1534 pushRegion(LabelCount
, Start
);
1535 Visit(S
->getSubStmt());
1538 void VisitBreakStmt(const BreakStmt
*S
) {
1539 assert(!BreakContinueStack
.empty() && "break not in a loop or switch!");
1540 if (!llvm::EnableSingleByteCoverage
)
1541 BreakContinueStack
.back().BreakCount
= addCounters(
1542 BreakContinueStack
.back().BreakCount
, getRegion().getCounter());
1543 // FIXME: a break in a switch should terminate regions for all preceding
1544 // case statements, not just the most recent one.
1548 void VisitContinueStmt(const ContinueStmt
*S
) {
1549 assert(!BreakContinueStack
.empty() && "continue stmt not in a loop!");
1550 if (!llvm::EnableSingleByteCoverage
)
1551 BreakContinueStack
.back().ContinueCount
= addCounters(
1552 BreakContinueStack
.back().ContinueCount
, getRegion().getCounter());
1556 void VisitCallExpr(const CallExpr
*E
) {
1559 // Terminate the region when we hit a noreturn function.
1560 // (This is helpful dealing with switch statements.)
1561 QualType CalleeType
= E
->getCallee()->getType();
1562 if (getFunctionExtInfo(*CalleeType
).getNoReturn())
1566 void VisitWhileStmt(const WhileStmt
*S
) {
1569 Counter ParentCount
= getRegion().getCounter();
1570 Counter BodyCount
= llvm::EnableSingleByteCoverage
1571 ? getRegionCounter(S
->getBody())
1572 : getRegionCounter(S
);
1574 // Handle the body first so that we can get the backedge count.
1575 BreakContinueStack
.push_back(BreakContinue());
1576 extendRegion(S
->getBody());
1577 Counter BackedgeCount
= propagateCounts(BodyCount
, S
->getBody());
1578 BreakContinue BC
= BreakContinueStack
.pop_back_val();
1580 bool BodyHasTerminateStmt
= HasTerminateStmt
;
1581 HasTerminateStmt
= false;
1583 // Go back to handle the condition.
1585 llvm::EnableSingleByteCoverage
1586 ? getRegionCounter(S
->getCond())
1587 : addCounters(ParentCount
, BackedgeCount
, BC
.ContinueCount
);
1588 propagateCounts(CondCount
, S
->getCond());
1589 adjustForOutOfOrderTraversal(getEnd(S
));
1591 // The body count applies to the area immediately after the increment.
1592 auto Gap
= findGapAreaBetween(S
->getRParenLoc(), getStart(S
->getBody()));
1594 fillGapAreaWithCount(Gap
->getBegin(), Gap
->getEnd(), BodyCount
);
1597 llvm::EnableSingleByteCoverage
1598 ? getRegionCounter(S
)
1599 : addCounters(BC
.BreakCount
,
1600 subtractCounters(CondCount
, BodyCount
));
1602 if (OutCount
!= ParentCount
) {
1603 pushRegion(OutCount
);
1604 GapRegionCounter
= OutCount
;
1605 if (BodyHasTerminateStmt
)
1606 HasTerminateStmt
= true;
1609 // Create Branch Region around condition.
1610 if (!llvm::EnableSingleByteCoverage
)
1611 createBranchRegion(S
->getCond(), BodyCount
,
1612 subtractCounters(CondCount
, BodyCount
));
1615 void VisitDoStmt(const DoStmt
*S
) {
1618 Counter ParentCount
= getRegion().getCounter();
1619 Counter BodyCount
= llvm::EnableSingleByteCoverage
1620 ? getRegionCounter(S
->getBody())
1621 : getRegionCounter(S
);
1623 BreakContinueStack
.push_back(BreakContinue());
1624 extendRegion(S
->getBody());
1626 Counter BackedgeCount
;
1627 if (llvm::EnableSingleByteCoverage
)
1628 propagateCounts(BodyCount
, S
->getBody());
1631 propagateCounts(addCounters(ParentCount
, BodyCount
), S
->getBody());
1633 BreakContinue BC
= BreakContinueStack
.pop_back_val();
1635 bool BodyHasTerminateStmt
= HasTerminateStmt
;
1636 HasTerminateStmt
= false;
1638 Counter CondCount
= llvm::EnableSingleByteCoverage
1639 ? getRegionCounter(S
->getCond())
1640 : addCounters(BackedgeCount
, BC
.ContinueCount
);
1641 propagateCounts(CondCount
, S
->getCond());
1644 llvm::EnableSingleByteCoverage
1645 ? getRegionCounter(S
)
1646 : addCounters(BC
.BreakCount
,
1647 subtractCounters(CondCount
, BodyCount
));
1648 if (OutCount
!= ParentCount
) {
1649 pushRegion(OutCount
);
1650 GapRegionCounter
= OutCount
;
1653 // Create Branch Region around condition.
1654 if (!llvm::EnableSingleByteCoverage
)
1655 createBranchRegion(S
->getCond(), BodyCount
,
1656 subtractCounters(CondCount
, BodyCount
));
1658 if (BodyHasTerminateStmt
)
1659 HasTerminateStmt
= true;
1662 void VisitForStmt(const ForStmt
*S
) {
1665 Visit(S
->getInit());
1667 Counter ParentCount
= getRegion().getCounter();
1668 Counter BodyCount
= llvm::EnableSingleByteCoverage
1669 ? getRegionCounter(S
->getBody())
1670 : getRegionCounter(S
);
1672 // The loop increment may contain a break or continue.
1674 BreakContinueStack
.emplace_back();
1676 // Handle the body first so that we can get the backedge count.
1677 BreakContinueStack
.emplace_back();
1678 extendRegion(S
->getBody());
1679 Counter BackedgeCount
= propagateCounts(BodyCount
, S
->getBody());
1680 BreakContinue BodyBC
= BreakContinueStack
.pop_back_val();
1682 bool BodyHasTerminateStmt
= HasTerminateStmt
;
1683 HasTerminateStmt
= false;
1685 // The increment is essentially part of the body but it needs to include
1686 // the count for all the continue statements.
1687 BreakContinue IncrementBC
;
1688 if (const Stmt
*Inc
= S
->getInc()) {
1690 if (llvm::EnableSingleByteCoverage
)
1691 IncCount
= getRegionCounter(S
->getInc());
1693 IncCount
= addCounters(BackedgeCount
, BodyBC
.ContinueCount
);
1694 propagateCounts(IncCount
, Inc
);
1695 IncrementBC
= BreakContinueStack
.pop_back_val();
1698 // Go back to handle the condition.
1700 llvm::EnableSingleByteCoverage
1701 ? getRegionCounter(S
->getCond())
1703 addCounters(ParentCount
, BackedgeCount
, BodyBC
.ContinueCount
),
1704 IncrementBC
.ContinueCount
);
1706 if (const Expr
*Cond
= S
->getCond()) {
1707 propagateCounts(CondCount
, Cond
);
1708 adjustForOutOfOrderTraversal(getEnd(S
));
1711 // The body count applies to the area immediately after the increment.
1712 auto Gap
= findGapAreaBetween(S
->getRParenLoc(), getStart(S
->getBody()));
1714 fillGapAreaWithCount(Gap
->getBegin(), Gap
->getEnd(), BodyCount
);
1717 llvm::EnableSingleByteCoverage
1718 ? getRegionCounter(S
)
1719 : addCounters(BodyBC
.BreakCount
, IncrementBC
.BreakCount
,
1720 subtractCounters(CondCount
, BodyCount
));
1721 if (OutCount
!= ParentCount
) {
1722 pushRegion(OutCount
);
1723 GapRegionCounter
= OutCount
;
1724 if (BodyHasTerminateStmt
)
1725 HasTerminateStmt
= true;
1728 // Create Branch Region around condition.
1729 if (!llvm::EnableSingleByteCoverage
)
1730 createBranchRegion(S
->getCond(), BodyCount
,
1731 subtractCounters(CondCount
, BodyCount
));
1734 void VisitCXXForRangeStmt(const CXXForRangeStmt
*S
) {
1737 Visit(S
->getInit());
1738 Visit(S
->getLoopVarStmt());
1739 Visit(S
->getRangeStmt());
1741 Counter ParentCount
= getRegion().getCounter();
1742 Counter BodyCount
= llvm::EnableSingleByteCoverage
1743 ? getRegionCounter(S
->getBody())
1744 : getRegionCounter(S
);
1746 BreakContinueStack
.push_back(BreakContinue());
1747 extendRegion(S
->getBody());
1748 Counter BackedgeCount
= propagateCounts(BodyCount
, S
->getBody());
1749 BreakContinue BC
= BreakContinueStack
.pop_back_val();
1751 bool BodyHasTerminateStmt
= HasTerminateStmt
;
1752 HasTerminateStmt
= false;
1754 // The body count applies to the area immediately after the range.
1755 auto Gap
= findGapAreaBetween(S
->getRParenLoc(), getStart(S
->getBody()));
1757 fillGapAreaWithCount(Gap
->getBegin(), Gap
->getEnd(), BodyCount
);
1761 if (llvm::EnableSingleByteCoverage
)
1762 OutCount
= getRegionCounter(S
);
1764 LoopCount
= addCounters(ParentCount
, BackedgeCount
, BC
.ContinueCount
);
1766 addCounters(BC
.BreakCount
, subtractCounters(LoopCount
, BodyCount
));
1768 if (OutCount
!= ParentCount
) {
1769 pushRegion(OutCount
);
1770 GapRegionCounter
= OutCount
;
1771 if (BodyHasTerminateStmt
)
1772 HasTerminateStmt
= true;
1775 // Create Branch Region around condition.
1776 if (!llvm::EnableSingleByteCoverage
)
1777 createBranchRegion(S
->getCond(), BodyCount
,
1778 subtractCounters(LoopCount
, BodyCount
));
1781 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt
*S
) {
1783 Visit(S
->getElement());
1785 Counter ParentCount
= getRegion().getCounter();
1786 Counter BodyCount
= getRegionCounter(S
);
1788 BreakContinueStack
.push_back(BreakContinue());
1789 extendRegion(S
->getBody());
1790 Counter BackedgeCount
= propagateCounts(BodyCount
, S
->getBody());
1791 BreakContinue BC
= BreakContinueStack
.pop_back_val();
1793 // The body count applies to the area immediately after the collection.
1794 auto Gap
= findGapAreaBetween(S
->getRParenLoc(), getStart(S
->getBody()));
1796 fillGapAreaWithCount(Gap
->getBegin(), Gap
->getEnd(), BodyCount
);
1799 addCounters(ParentCount
, BackedgeCount
, BC
.ContinueCount
);
1801 addCounters(BC
.BreakCount
, subtractCounters(LoopCount
, BodyCount
));
1802 if (OutCount
!= ParentCount
) {
1803 pushRegion(OutCount
);
1804 GapRegionCounter
= OutCount
;
1808 void VisitSwitchStmt(const SwitchStmt
*S
) {
1811 Visit(S
->getInit());
1812 Visit(S
->getCond());
1814 BreakContinueStack
.push_back(BreakContinue());
1816 const Stmt
*Body
= S
->getBody();
1818 if (const auto *CS
= dyn_cast
<CompoundStmt
>(Body
)) {
1819 if (!CS
->body_empty()) {
1820 // Make a region for the body of the switch. If the body starts with
1821 // a case, that case will reuse this region; otherwise, this covers
1822 // the unreachable code at the beginning of the switch body.
1823 size_t Index
= pushRegion(Counter::getZero(), getStart(CS
));
1824 getRegion().setGap(true);
1827 // Set the end for the body of the switch, if it isn't already set.
1828 for (size_t i
= RegionStack
.size(); i
!= Index
; --i
) {
1829 if (!RegionStack
[i
- 1].hasEndLoc())
1830 RegionStack
[i
- 1].setEndLoc(getEnd(CS
->body_back()));
1836 propagateCounts(Counter::getZero(), Body
);
1837 BreakContinue BC
= BreakContinueStack
.pop_back_val();
1839 if (!BreakContinueStack
.empty() && !llvm::EnableSingleByteCoverage
)
1840 BreakContinueStack
.back().ContinueCount
= addCounters(
1841 BreakContinueStack
.back().ContinueCount
, BC
.ContinueCount
);
1843 Counter ParentCount
= getRegion().getCounter();
1844 Counter ExitCount
= getRegionCounter(S
);
1845 SourceLocation ExitLoc
= getEnd(S
);
1846 pushRegion(ExitCount
);
1847 GapRegionCounter
= ExitCount
;
1849 // Ensure that handleFileExit recognizes when the end location is located
1850 // in a different file.
1851 MostRecentLocation
= getStart(S
);
1852 handleFileExit(ExitLoc
);
1854 // When single byte coverage mode is enabled, do not create branch region by
1856 if (llvm::EnableSingleByteCoverage
)
1859 // Create a Branch Region around each Case. Subtract the case's
1860 // counter from the Parent counter to track the "False" branch count.
1861 Counter CaseCountSum
;
1862 bool HasDefaultCase
= false;
1863 const SwitchCase
*Case
= S
->getSwitchCaseList();
1864 for (; Case
; Case
= Case
->getNextSwitchCase()) {
1865 HasDefaultCase
= HasDefaultCase
|| isa
<DefaultStmt
>(Case
);
1866 auto CaseCount
= getRegionCounter(Case
);
1867 CaseCountSum
= addCounters(CaseCountSum
, CaseCount
, /*Simplify=*/false);
1868 createSwitchCaseRegion(Case
, CaseCount
);
1870 // If no explicit default case exists, create a branch region to represent
1871 // the hidden branch, which will be added later by the CodeGen. This region
1872 // will be associated with the switch statement's condition.
1873 if (!HasDefaultCase
) {
1874 Counter DefaultCount
= subtractCounters(ParentCount
, CaseCountSum
);
1875 createBranchRegion(S
->getCond(), Counter::getZero(), DefaultCount
);
1879 void VisitSwitchCase(const SwitchCase
*S
) {
1882 SourceMappingRegion
&Parent
= getRegion();
1883 Counter Count
= llvm::EnableSingleByteCoverage
1884 ? getRegionCounter(S
)
1885 : addCounters(Parent
.getCounter(), getRegionCounter(S
));
1887 // Reuse the existing region if it starts at our label. This is typical of
1888 // the first case in a switch.
1889 if (Parent
.hasStartLoc() && Parent
.getBeginLoc() == getStart(S
))
1890 Parent
.setCounter(Count
);
1892 pushRegion(Count
, getStart(S
));
1894 GapRegionCounter
= Count
;
1896 if (const auto *CS
= dyn_cast
<CaseStmt
>(S
)) {
1897 Visit(CS
->getLHS());
1898 if (const Expr
*RHS
= CS
->getRHS())
1901 Visit(S
->getSubStmt());
1904 void coverIfConsteval(const IfStmt
*S
) {
1905 assert(S
->isConsteval());
1907 const auto *Then
= S
->getThen();
1908 const auto *Else
= S
->getElse();
1910 // It's better for llvm-cov to create a new region with same counter
1911 // so line-coverage can be properly calculated for lines containing
1912 // a skipped region (without it the line is marked uncovered)
1913 const Counter ParentCount
= getRegion().getCounter();
1917 if (S
->isNegatedConsteval()) {
1918 // ignore 'if consteval'
1919 markSkipped(S
->getIfLoc(), getStart(Then
));
1920 propagateCounts(ParentCount
, Then
);
1923 // ignore 'else <else>'
1924 markSkipped(getEnd(Then
), getEnd(Else
));
1927 assert(S
->isNonNegatedConsteval());
1928 // ignore 'if consteval <then> [else]'
1929 markSkipped(S
->getIfLoc(), Else
? getStart(Else
) : getEnd(Then
));
1932 propagateCounts(ParentCount
, Else
);
1936 void coverIfConstexpr(const IfStmt
*S
) {
1937 assert(S
->isConstexpr());
1939 // evaluate constant condition...
1942 ->EvaluateKnownConstInt(CVM
.getCodeGenModule().getContext())
1947 // I'm using 'propagateCounts' later as new region is better and allows me
1948 // to properly calculate line coverage in llvm-cov utility
1949 const Counter ParentCount
= getRegion().getCounter();
1951 // ignore 'if constexpr ('
1952 SourceLocation startOfSkipped
= S
->getIfLoc();
1954 if (const auto *Init
= S
->getInit()) {
1955 const auto start
= getStart(Init
);
1956 const auto end
= getEnd(Init
);
1958 // this check is to make sure typedef here which doesn't have valid source
1959 // location won't crash it
1960 if (start
.isValid() && end
.isValid()) {
1961 markSkipped(startOfSkipped
, start
);
1962 propagateCounts(ParentCount
, Init
);
1963 startOfSkipped
= getEnd(Init
);
1967 const auto *Then
= S
->getThen();
1968 const auto *Else
= S
->getElse();
1971 // ignore '<condition>)'
1972 markSkipped(startOfSkipped
, getStart(Then
));
1973 propagateCounts(ParentCount
, Then
);
1976 // ignore 'else <else>'
1977 markSkipped(getEnd(Then
), getEnd(Else
));
1979 // ignore '<condition>) <then> [else]'
1980 markSkipped(startOfSkipped
, Else
? getStart(Else
) : getEnd(Then
));
1983 propagateCounts(ParentCount
, Else
);
1987 void VisitIfStmt(const IfStmt
*S
) {
1988 // "if constexpr" and "if consteval" are not normal conditional statements,
1989 // their discarded statement should be skipped
1990 if (S
->isConsteval())
1991 return coverIfConsteval(S
);
1992 else if (S
->isConstexpr())
1993 return coverIfConstexpr(S
);
1997 Visit(S
->getInit());
1999 // Extend into the condition before we propagate through it below - this is
2000 // needed to handle macros that generate the "if" but not the condition.
2001 extendRegion(S
->getCond());
2003 Counter ParentCount
= getRegion().getCounter();
2004 Counter ThenCount
= llvm::EnableSingleByteCoverage
2005 ? getRegionCounter(S
->getThen())
2006 : getRegionCounter(S
);
2008 // Emitting a counter for the condition makes it easier to interpret the
2009 // counter for the body when looking at the coverage.
2010 propagateCounts(ParentCount
, S
->getCond());
2012 // The 'then' count applies to the area immediately after the condition.
2013 std::optional
<SourceRange
> Gap
=
2014 findGapAreaBetween(S
->getRParenLoc(), getStart(S
->getThen()));
2016 fillGapAreaWithCount(Gap
->getBegin(), Gap
->getEnd(), ThenCount
);
2018 extendRegion(S
->getThen());
2019 Counter OutCount
= propagateCounts(ThenCount
, S
->getThen());
2022 if (!llvm::EnableSingleByteCoverage
)
2023 ElseCount
= subtractCounters(ParentCount
, ThenCount
);
2024 else if (S
->getElse())
2025 ElseCount
= getRegionCounter(S
->getElse());
2027 if (const Stmt
*Else
= S
->getElse()) {
2028 bool ThenHasTerminateStmt
= HasTerminateStmt
;
2029 HasTerminateStmt
= false;
2030 // The 'else' count applies to the area immediately after the 'then'.
2031 std::optional
<SourceRange
> Gap
=
2032 findGapAreaBetween(getEnd(S
->getThen()), getStart(Else
));
2034 fillGapAreaWithCount(Gap
->getBegin(), Gap
->getEnd(), ElseCount
);
2037 Counter ElseOutCount
= propagateCounts(ElseCount
, Else
);
2038 if (!llvm::EnableSingleByteCoverage
)
2039 OutCount
= addCounters(OutCount
, ElseOutCount
);
2041 if (ThenHasTerminateStmt
)
2042 HasTerminateStmt
= true;
2043 } else if (!llvm::EnableSingleByteCoverage
)
2044 OutCount
= addCounters(OutCount
, ElseCount
);
2046 if (llvm::EnableSingleByteCoverage
)
2047 OutCount
= getRegionCounter(S
);
2049 if (OutCount
!= ParentCount
) {
2050 pushRegion(OutCount
);
2051 GapRegionCounter
= OutCount
;
2054 if (!llvm::EnableSingleByteCoverage
)
2055 // Create Branch Region around condition.
2056 createBranchRegion(S
->getCond(), ThenCount
,
2057 subtractCounters(ParentCount
, ThenCount
));
2060 void VisitCXXTryStmt(const CXXTryStmt
*S
) {
2062 // Handle macros that generate the "try" but not the rest.
2063 extendRegion(S
->getTryBlock());
2065 Counter ParentCount
= getRegion().getCounter();
2066 propagateCounts(ParentCount
, S
->getTryBlock());
2068 for (unsigned I
= 0, E
= S
->getNumHandlers(); I
< E
; ++I
)
2069 Visit(S
->getHandler(I
));
2071 Counter ExitCount
= getRegionCounter(S
);
2072 pushRegion(ExitCount
);
2075 void VisitCXXCatchStmt(const CXXCatchStmt
*S
) {
2076 propagateCounts(getRegionCounter(S
), S
->getHandlerBlock());
2079 void VisitAbstractConditionalOperator(const AbstractConditionalOperator
*E
) {
2082 Counter ParentCount
= getRegion().getCounter();
2083 Counter TrueCount
= llvm::EnableSingleByteCoverage
2084 ? getRegionCounter(E
->getTrueExpr())
2085 : getRegionCounter(E
);
2088 if (const auto *BCO
= dyn_cast
<BinaryConditionalOperator
>(E
)) {
2089 propagateCounts(ParentCount
, BCO
->getCommon());
2090 OutCount
= TrueCount
;
2092 propagateCounts(ParentCount
, E
->getCond());
2093 // The 'then' count applies to the area immediately after the condition.
2095 findGapAreaBetween(E
->getQuestionLoc(), getStart(E
->getTrueExpr()));
2097 fillGapAreaWithCount(Gap
->getBegin(), Gap
->getEnd(), TrueCount
);
2099 extendRegion(E
->getTrueExpr());
2100 OutCount
= propagateCounts(TrueCount
, E
->getTrueExpr());
2103 extendRegion(E
->getFalseExpr());
2104 Counter FalseCount
= llvm::EnableSingleByteCoverage
2105 ? getRegionCounter(E
->getFalseExpr())
2106 : subtractCounters(ParentCount
, TrueCount
);
2108 Counter FalseOutCount
= propagateCounts(FalseCount
, E
->getFalseExpr());
2109 if (llvm::EnableSingleByteCoverage
)
2110 OutCount
= getRegionCounter(E
);
2112 OutCount
= addCounters(OutCount
, FalseOutCount
);
2114 if (OutCount
!= ParentCount
) {
2115 pushRegion(OutCount
);
2116 GapRegionCounter
= OutCount
;
2119 // Create Branch Region around condition.
2120 if (!llvm::EnableSingleByteCoverage
)
2121 createBranchRegion(E
->getCond(), TrueCount
,
2122 subtractCounters(ParentCount
, TrueCount
));
2125 void createOrCancelDecision(const BinaryOperator
*E
, unsigned Since
) {
2126 unsigned NumConds
= MCDCBuilder
.getTotalConditionsAndReset(E
);
2130 // Extract [ID, Conds] to construct the graph.
2131 llvm::SmallVector
<mcdc::ConditionIDs
> CondIDs(NumConds
);
2132 for (const auto &SR
: ArrayRef(SourceRegions
).slice(Since
)) {
2133 if (SR
.isMCDCBranch()) {
2134 auto [ID
, Conds
] = SR
.getMCDCBranchParams();
2135 CondIDs
[ID
] = Conds
;
2139 // Construct the graph and calculate `Indices`.
2140 mcdc::TVIdxBuilder
Builder(CondIDs
);
2141 unsigned NumTVs
= Builder
.NumTestVectors
;
2142 unsigned MaxTVs
= CVM
.getCodeGenModule().getCodeGenOpts().MCDCMaxTVs
;
2143 assert(MaxTVs
< mcdc::TVIdxBuilder::HardMaxTVs
);
2145 if (NumTVs
> MaxTVs
) {
2146 // NumTVs exceeds MaxTVs -- warn and cancel the Decision.
2147 cancelDecision(E
, Since
, NumTVs
, MaxTVs
);
2151 // Update the state for CodeGenPGO
2152 assert(MCDCState
.DecisionByStmt
.contains(E
));
2153 MCDCState
.DecisionByStmt
[E
] = {
2154 MCDCState
.BitmapBits
, // Top
2155 std::move(Builder
.Indices
),
2158 auto DecisionParams
= mcdc::DecisionParameters
{
2159 MCDCState
.BitmapBits
+= NumTVs
, // Tail
2163 // Create MCDC Decision Region.
2164 createDecisionRegion(E
, DecisionParams
);
2167 // Warn and cancel the Decision.
2168 void cancelDecision(const BinaryOperator
*E
, unsigned Since
, int NumTVs
,
2170 auto &Diag
= CVM
.getCodeGenModule().getDiags();
2172 Diag
.getCustomDiagID(DiagnosticsEngine::Warning
,
2173 "unsupported MC/DC boolean expression; "
2174 "number of test vectors (%0) exceeds max (%1). "
2175 "Expression will not be covered");
2176 Diag
.Report(E
->getBeginLoc(), DiagID
) << NumTVs
<< MaxTVs
;
2178 // Restore MCDCBranch to Branch.
2179 for (auto &SR
: MutableArrayRef(SourceRegions
).slice(Since
)) {
2180 assert(!SR
.isMCDCDecision() && "Decision shouldn't be seen here");
2181 if (SR
.isMCDCBranch())
2182 SR
.resetMCDCParams();
2185 // Tell CodeGenPGO not to instrument.
2186 MCDCState
.DecisionByStmt
.erase(E
);
2189 /// Check if E belongs to system headers.
2190 bool isExprInSystemHeader(const BinaryOperator
*E
) const {
2191 return (!SystemHeadersCoverage
&&
2192 SM
.isInSystemHeader(SM
.getSpellingLoc(E
->getOperatorLoc())) &&
2193 SM
.isInSystemHeader(SM
.getSpellingLoc(E
->getBeginLoc())) &&
2194 SM
.isInSystemHeader(SM
.getSpellingLoc(E
->getEndLoc())));
2197 void VisitBinLAnd(const BinaryOperator
*E
) {
2198 if (isExprInSystemHeader(E
)) {
2199 LeafExprSet
.insert(E
);
2203 bool IsRootNode
= MCDCBuilder
.isIdle();
2205 unsigned SourceRegionsSince
= SourceRegions
.size();
2207 // Keep track of Binary Operator and assign MCDC condition IDs.
2208 MCDCBuilder
.pushAndAssignIDs(E
);
2210 extendRegion(E
->getLHS());
2211 propagateCounts(getRegion().getCounter(), E
->getLHS());
2212 handleFileExit(getEnd(E
->getLHS()));
2214 // Track LHS True/False Decision.
2215 const auto DecisionLHS
= MCDCBuilder
.pop();
2217 // Counter tracks the right hand side of a logical and operator.
2218 extendRegion(E
->getRHS());
2219 propagateCounts(getRegionCounter(E
), E
->getRHS());
2221 // Track RHS True/False Decision.
2222 const auto DecisionRHS
= MCDCBuilder
.back();
2224 // Extract the RHS's Execution Counter.
2225 Counter RHSExecCnt
= getRegionCounter(E
);
2227 // Extract the RHS's "True" Instance Counter.
2228 Counter RHSTrueCnt
= getRegionCounter(E
->getRHS());
2230 // Extract the Parent Region Counter.
2231 Counter ParentCnt
= getRegion().getCounter();
2233 // Create Branch Region around LHS condition.
2234 if (!llvm::EnableSingleByteCoverage
)
2235 createBranchRegion(E
->getLHS(), RHSExecCnt
,
2236 subtractCounters(ParentCnt
, RHSExecCnt
), DecisionLHS
);
2238 // Create Branch Region around RHS condition.
2239 if (!llvm::EnableSingleByteCoverage
)
2240 createBranchRegion(E
->getRHS(), RHSTrueCnt
,
2241 subtractCounters(RHSExecCnt
, RHSTrueCnt
), DecisionRHS
);
2243 // Create MCDC Decision Region if at top-level (root).
2245 createOrCancelDecision(E
, SourceRegionsSince
);
2248 // Determine whether the right side of OR operation need to be visited.
2249 bool shouldVisitRHS(const Expr
*LHS
) {
2250 bool LHSIsTrue
= false;
2251 bool LHSIsConst
= false;
2252 if (!LHS
->isValueDependent())
2253 LHSIsConst
= LHS
->EvaluateAsBooleanCondition(
2254 LHSIsTrue
, CVM
.getCodeGenModule().getContext());
2255 return !LHSIsConst
|| (LHSIsConst
&& !LHSIsTrue
);
2258 void VisitBinLOr(const BinaryOperator
*E
) {
2259 if (isExprInSystemHeader(E
)) {
2260 LeafExprSet
.insert(E
);
2264 bool IsRootNode
= MCDCBuilder
.isIdle();
2266 unsigned SourceRegionsSince
= SourceRegions
.size();
2268 // Keep track of Binary Operator and assign MCDC condition IDs.
2269 MCDCBuilder
.pushAndAssignIDs(E
);
2271 extendRegion(E
->getLHS());
2272 Counter OutCount
= propagateCounts(getRegion().getCounter(), E
->getLHS());
2273 handleFileExit(getEnd(E
->getLHS()));
2275 // Track LHS True/False Decision.
2276 const auto DecisionLHS
= MCDCBuilder
.pop();
2278 // Counter tracks the right hand side of a logical or operator.
2279 extendRegion(E
->getRHS());
2280 propagateCounts(getRegionCounter(E
), E
->getRHS());
2282 // Track RHS True/False Decision.
2283 const auto DecisionRHS
= MCDCBuilder
.back();
2285 // Extract the RHS's Execution Counter.
2286 Counter RHSExecCnt
= getRegionCounter(E
);
2288 // Extract the RHS's "False" Instance Counter.
2289 Counter RHSFalseCnt
= getRegionCounter(E
->getRHS());
2291 if (!shouldVisitRHS(E
->getLHS())) {
2292 GapRegionCounter
= OutCount
;
2295 // Extract the Parent Region Counter.
2296 Counter ParentCnt
= getRegion().getCounter();
2298 // Create Branch Region around LHS condition.
2299 if (!llvm::EnableSingleByteCoverage
)
2300 createBranchRegion(E
->getLHS(), subtractCounters(ParentCnt
, RHSExecCnt
),
2301 RHSExecCnt
, DecisionLHS
);
2303 // Create Branch Region around RHS condition.
2304 if (!llvm::EnableSingleByteCoverage
)
2305 createBranchRegion(E
->getRHS(), subtractCounters(RHSExecCnt
, RHSFalseCnt
),
2306 RHSFalseCnt
, DecisionRHS
);
2308 // Create MCDC Decision Region if at top-level (root).
2310 createOrCancelDecision(E
, SourceRegionsSince
);
2313 void VisitLambdaExpr(const LambdaExpr
*LE
) {
2314 // Lambdas are treated as their own functions for now, so we shouldn't
2315 // propagate counts into them.
2318 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr
*AILE
) {
2319 Visit(AILE
->getCommonExpr()->getSourceExpr());
2322 void VisitPseudoObjectExpr(const PseudoObjectExpr
*POE
) {
2323 // Just visit syntatic expression as this is what users actually write.
2324 VisitStmt(POE
->getSyntacticForm());
2327 void VisitOpaqueValueExpr(const OpaqueValueExpr
* OVE
) {
2328 if (OVE
->isUnique())
2329 Visit(OVE
->getSourceExpr());
2333 } // end anonymous namespace
2335 static void dump(llvm::raw_ostream
&OS
, StringRef FunctionName
,
2336 ArrayRef
<CounterExpression
> Expressions
,
2337 ArrayRef
<CounterMappingRegion
> Regions
) {
2338 OS
<< FunctionName
<< ":\n";
2339 CounterMappingContext
Ctx(Expressions
);
2340 for (const auto &R
: Regions
) {
2343 case CounterMappingRegion::CodeRegion
:
2345 case CounterMappingRegion::ExpansionRegion
:
2348 case CounterMappingRegion::SkippedRegion
:
2351 case CounterMappingRegion::GapRegion
:
2354 case CounterMappingRegion::BranchRegion
:
2355 case CounterMappingRegion::MCDCBranchRegion
:
2358 case CounterMappingRegion::MCDCDecisionRegion
:
2363 OS
<< "File " << R
.FileID
<< ", " << R
.LineStart
<< ":" << R
.ColumnStart
2364 << " -> " << R
.LineEnd
<< ":" << R
.ColumnEnd
<< " = ";
2366 if (const auto *DecisionParams
=
2367 std::get_if
<mcdc::DecisionParameters
>(&R
.MCDCParams
)) {
2368 OS
<< "M:" << DecisionParams
->BitmapIdx
;
2369 OS
<< ", C:" << DecisionParams
->NumConditions
;
2371 Ctx
.dump(R
.Count
, OS
);
2373 if (R
.Kind
== CounterMappingRegion::BranchRegion
||
2374 R
.Kind
== CounterMappingRegion::MCDCBranchRegion
) {
2376 Ctx
.dump(R
.FalseCount
, OS
);
2380 if (const auto *BranchParams
=
2381 std::get_if
<mcdc::BranchParameters
>(&R
.MCDCParams
)) {
2382 OS
<< " [" << BranchParams
->ID
+ 1 << ","
2383 << BranchParams
->Conds
[true] + 1;
2384 OS
<< "," << BranchParams
->Conds
[false] + 1 << "] ";
2387 if (R
.Kind
== CounterMappingRegion::ExpansionRegion
)
2388 OS
<< " (Expanded file = " << R
.ExpandedFileID
<< ")";
2393 CoverageMappingModuleGen::CoverageMappingModuleGen(
2394 CodeGenModule
&CGM
, CoverageSourceInfo
&SourceInfo
)
2395 : CGM(CGM
), SourceInfo(SourceInfo
) {}
2397 std::string
CoverageMappingModuleGen::getCurrentDirname() {
2398 if (!CGM
.getCodeGenOpts().CoverageCompilationDir
.empty())
2399 return CGM
.getCodeGenOpts().CoverageCompilationDir
;
2401 SmallString
<256> CWD
;
2402 llvm::sys::fs::current_path(CWD
);
2403 return CWD
.str().str();
2406 std::string
CoverageMappingModuleGen::normalizeFilename(StringRef Filename
) {
2407 llvm::SmallString
<256> Path(Filename
);
2408 llvm::sys::path::remove_dots(Path
, /*remove_dot_dot=*/true);
2410 /// Traverse coverage prefix map in reverse order because prefix replacements
2411 /// are applied in reverse order starting from the last one when multiple
2412 /// prefix replacement options are provided.
2413 for (const auto &[From
, To
] :
2414 llvm::reverse(CGM
.getCodeGenOpts().CoveragePrefixMap
)) {
2415 if (llvm::sys::path::replace_path_prefix(Path
, From
, To
))
2418 return Path
.str().str();
2421 static std::string
getInstrProfSection(const CodeGenModule
&CGM
,
2422 llvm::InstrProfSectKind SK
) {
2423 return llvm::getInstrProfSectionName(
2424 SK
, CGM
.getContext().getTargetInfo().getTriple().getObjectFormat());
2427 void CoverageMappingModuleGen::emitFunctionMappingRecord(
2428 const FunctionInfo
&Info
, uint64_t FilenamesRef
) {
2429 llvm::LLVMContext
&Ctx
= CGM
.getLLVMContext();
2431 // Assign a name to the function record. This is used to merge duplicates.
2432 std::string FuncRecordName
= "__covrec_" + llvm::utohexstr(Info
.NameHash
);
2434 // A dummy description for a function included-but-not-used in a TU can be
2435 // replaced by full description provided by a different TU. The two kinds of
2436 // descriptions play distinct roles: therefore, assign them different names
2437 // to prevent `linkonce_odr` merging.
2439 FuncRecordName
+= "u";
2441 // Create the function record type.
2442 const uint64_t NameHash
= Info
.NameHash
;
2443 const uint64_t FuncHash
= Info
.FuncHash
;
2444 const std::string
&CoverageMapping
= Info
.CoverageMapping
;
2445 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2446 llvm::Type
*FunctionRecordTypes
[] = {
2447 #include "llvm/ProfileData/InstrProfData.inc"
2449 auto *FunctionRecordTy
=
2450 llvm::StructType::get(Ctx
, ArrayRef(FunctionRecordTypes
),
2453 // Create the function record constant.
2454 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2455 llvm::Constant
*FunctionRecordVals
[] = {
2456 #include "llvm/ProfileData/InstrProfData.inc"
2458 auto *FuncRecordConstant
=
2459 llvm::ConstantStruct::get(FunctionRecordTy
, ArrayRef(FunctionRecordVals
));
2461 // Create the function record global.
2462 auto *FuncRecord
= new llvm::GlobalVariable(
2463 CGM
.getModule(), FunctionRecordTy
, /*isConstant=*/true,
2464 llvm::GlobalValue::LinkOnceODRLinkage
, FuncRecordConstant
,
2466 FuncRecord
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
2467 FuncRecord
->setSection(getInstrProfSection(CGM
, llvm::IPSK_covfun
));
2468 FuncRecord
->setAlignment(llvm::Align(8));
2469 if (CGM
.supportsCOMDAT())
2470 FuncRecord
->setComdat(CGM
.getModule().getOrInsertComdat(FuncRecordName
));
2472 // Make sure the data doesn't get deleted.
2473 CGM
.addUsedGlobal(FuncRecord
);
2476 void CoverageMappingModuleGen::addFunctionMappingRecord(
2477 llvm::GlobalVariable
*NamePtr
, StringRef NameValue
, uint64_t FuncHash
,
2478 const std::string
&CoverageMapping
, bool IsUsed
) {
2479 const uint64_t NameHash
= llvm::IndexedInstrProf::ComputeHash(NameValue
);
2480 FunctionRecords
.push_back({NameHash
, FuncHash
, CoverageMapping
, IsUsed
});
2483 FunctionNames
.push_back(NamePtr
);
2485 if (CGM
.getCodeGenOpts().DumpCoverageMapping
) {
2486 // Dump the coverage mapping data for this function by decoding the
2487 // encoded data. This allows us to dump the mapping regions which were
2488 // also processed by the CoverageMappingWriter which performs
2489 // additional minimization operations such as reducing the number of
2491 llvm::SmallVector
<std::string
, 16> FilenameStrs
;
2492 std::vector
<StringRef
> Filenames
;
2493 std::vector
<CounterExpression
> Expressions
;
2494 std::vector
<CounterMappingRegion
> Regions
;
2495 FilenameStrs
.resize(FileEntries
.size() + 1);
2496 FilenameStrs
[0] = normalizeFilename(getCurrentDirname());
2497 for (const auto &Entry
: FileEntries
) {
2498 auto I
= Entry
.second
;
2499 FilenameStrs
[I
] = normalizeFilename(Entry
.first
.getName());
2501 ArrayRef
<std::string
> FilenameRefs
= llvm::ArrayRef(FilenameStrs
);
2502 RawCoverageMappingReader
Reader(CoverageMapping
, FilenameRefs
, Filenames
,
2503 Expressions
, Regions
);
2506 dump(llvm::outs(), NameValue
, Expressions
, Regions
);
2510 void CoverageMappingModuleGen::emit() {
2511 if (FunctionRecords
.empty())
2513 llvm::LLVMContext
&Ctx
= CGM
.getLLVMContext();
2514 auto *Int32Ty
= llvm::Type::getInt32Ty(Ctx
);
2516 // Create the filenames and merge them with coverage mappings
2517 llvm::SmallVector
<std::string
, 16> FilenameStrs
;
2518 FilenameStrs
.resize(FileEntries
.size() + 1);
2519 // The first filename is the current working directory.
2520 FilenameStrs
[0] = normalizeFilename(getCurrentDirname());
2521 for (const auto &Entry
: FileEntries
) {
2522 auto I
= Entry
.second
;
2523 FilenameStrs
[I
] = normalizeFilename(Entry
.first
.getName());
2526 std::string Filenames
;
2528 llvm::raw_string_ostream
OS(Filenames
);
2529 CoverageFilenamesSectionWriter(FilenameStrs
).write(OS
);
2531 auto *FilenamesVal
=
2532 llvm::ConstantDataArray::getString(Ctx
, Filenames
, false);
2533 const int64_t FilenamesRef
= llvm::IndexedInstrProf::ComputeHash(Filenames
);
2535 // Emit the function records.
2536 for (const FunctionInfo
&Info
: FunctionRecords
)
2537 emitFunctionMappingRecord(Info
, FilenamesRef
);
2539 const unsigned NRecords
= 0;
2540 const size_t FilenamesSize
= Filenames
.size();
2541 const unsigned CoverageMappingSize
= 0;
2542 llvm::Type
*CovDataHeaderTypes
[] = {
2543 #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2544 #include "llvm/ProfileData/InstrProfData.inc"
2546 auto CovDataHeaderTy
=
2547 llvm::StructType::get(Ctx
, ArrayRef(CovDataHeaderTypes
));
2548 llvm::Constant
*CovDataHeaderVals
[] = {
2549 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2550 #include "llvm/ProfileData/InstrProfData.inc"
2552 auto CovDataHeaderVal
=
2553 llvm::ConstantStruct::get(CovDataHeaderTy
, ArrayRef(CovDataHeaderVals
));
2555 // Create the coverage data record
2556 llvm::Type
*CovDataTypes
[] = {CovDataHeaderTy
, FilenamesVal
->getType()};
2557 auto CovDataTy
= llvm::StructType::get(Ctx
, ArrayRef(CovDataTypes
));
2558 llvm::Constant
*TUDataVals
[] = {CovDataHeaderVal
, FilenamesVal
};
2559 auto CovDataVal
= llvm::ConstantStruct::get(CovDataTy
, ArrayRef(TUDataVals
));
2560 auto CovData
= new llvm::GlobalVariable(
2561 CGM
.getModule(), CovDataTy
, true, llvm::GlobalValue::PrivateLinkage
,
2562 CovDataVal
, llvm::getCoverageMappingVarName());
2564 CovData
->setSection(getInstrProfSection(CGM
, llvm::IPSK_covmap
));
2565 CovData
->setAlignment(llvm::Align(8));
2567 // Make sure the data doesn't get deleted.
2568 CGM
.addUsedGlobal(CovData
);
2569 // Create the deferred function records array
2570 if (!FunctionNames
.empty()) {
2571 auto NamesArrTy
= llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx
),
2572 FunctionNames
.size());
2573 auto NamesArrVal
= llvm::ConstantArray::get(NamesArrTy
, FunctionNames
);
2574 // This variable will *NOT* be emitted to the object file. It is used
2575 // to pass the list of names referenced to codegen.
2576 new llvm::GlobalVariable(CGM
.getModule(), NamesArrTy
, true,
2577 llvm::GlobalValue::InternalLinkage
, NamesArrVal
,
2578 llvm::getCoverageUnusedNamesVarName());
2582 unsigned CoverageMappingModuleGen::getFileID(FileEntryRef File
) {
2583 return FileEntries
.try_emplace(File
, FileEntries
.size() + 1).first
->second
;
2586 void CoverageMappingGen::emitCounterMapping(const Decl
*D
,
2587 llvm::raw_ostream
&OS
) {
2588 assert(CounterMap
&& MCDCState
);
2589 CounterCoverageMappingBuilder
Walker(CVM
, *CounterMap
, *MCDCState
, SM
,
2591 Walker
.VisitDecl(D
);
2595 void CoverageMappingGen::emitEmptyMapping(const Decl
*D
,
2596 llvm::raw_ostream
&OS
) {
2597 EmptyCoverageMappingBuilder
Walker(CVM
, SM
, LangOpts
);
2598 Walker
.VisitDecl(D
);