20#include "llvm/ADT/DenseSet.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"
39 llvm::cl::desc(
"Enable single byte coverage"),
40 llvm::cl::Hidden, llvm::cl::init(
false));
44 "emptyline-comment-coverage",
45 llvm::cl::desc(
"Emit emptylines and comment lines as skipped regions (only "
46 "disable it on test)"),
47 llvm::cl::init(
true), llvm::cl::Hidden);
50 "system-headers-coverage",
51 llvm::cl::desc(
"Enable collecting coverage from system headers"),
52 llvm::cl::init(
false), llvm::cl::Hidden);
55using namespace CodeGen;
56using namespace llvm::coverage;
70 if (Tok.
getKind() != clang::tok::eod)
80 PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
81 SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
85 SkippedRanges.push_back({
Range, RangeKind, PrevTokLoc});
102 if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
103 SkippedRanges.back().NextTokLoc =
Loc;
108class SourceMappingRegion {
113 std::optional<Counter> FalseCount;
116 mcdc::Parameters MCDCParams;
119 std::optional<SourceLocation> LocStart;
122 std::optional<SourceLocation> LocEnd;
133 SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart,
134 std::optional<SourceLocation> LocEnd,
135 bool GapRegion =
false)
136 : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
137 SkippedRegion(
false) {}
139 SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount,
140 mcdc::Parameters MCDCParams,
141 std::optional<SourceLocation> LocStart,
142 std::optional<SourceLocation> LocEnd,
143 bool GapRegion =
false)
144 : Count(Count), FalseCount(FalseCount), MCDCParams(MCDCParams),
145 LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
146 SkippedRegion(
false) {}
148 SourceMappingRegion(mcdc::Parameters MCDCParams,
149 std::optional<SourceLocation> LocStart,
150 std::optional<SourceLocation> LocEnd)
151 : MCDCParams(MCDCParams), LocStart(LocStart), LocEnd(LocEnd),
154 const Counter &getCounter()
const {
return Count; }
156 const Counter &getFalseCounter()
const {
157 assert(FalseCount &&
"Region has no alternate counter");
161 void setCounter(Counter
C) { Count =
C; }
163 bool hasStartLoc()
const {
return LocStart.has_value(); }
168 assert(LocStart &&
"Region has no start location");
172 bool hasEndLoc()
const {
return LocEnd.has_value(); }
175 assert(
Loc.
isValid() &&
"Setting an invalid end location");
180 assert(LocEnd &&
"Region has no end location");
184 bool isGap()
const {
return GapRegion; }
186 void setGap(
bool Gap) { GapRegion = Gap; }
188 bool isSkipped()
const {
return SkippedRegion; }
190 void setSkipped(
bool Skipped) { SkippedRegion = Skipped; }
192 bool isBranch()
const {
return FalseCount.has_value(); }
194 bool isMCDCDecision()
const {
195 return std::holds_alternative<mcdc::DecisionParameters>(MCDCParams);
198 const auto &getMCDCDecisionParams()
const {
199 return mcdc::getParams<const mcdc::DecisionParameters>(MCDCParams);
202 const mcdc::Parameters &getMCDCParams()
const {
return MCDCParams; }
206struct SpellingRegion {
211 unsigned ColumnStart;
221 LineStart =
SM.getSpellingLineNumber(LocStart);
222 ColumnStart =
SM.getSpellingColumnNumber(LocStart);
223 LineEnd =
SM.getSpellingLineNumber(LocEnd);
224 ColumnEnd =
SM.getSpellingColumnNumber(LocEnd);
228 : SpellingRegion(
SM, R.getBeginLoc(), R.getEndLoc()) {}
232 bool isInSourceOrder()
const {
233 return (LineStart < LineEnd) ||
234 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
240class CoverageMappingBuilder {
248 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
255 std::vector<SourceMappingRegion> SourceRegions;
262 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
267 : CVM(CVM),
SM(
SM), LangOpts(LangOpts) {}
282 return SM.getLocForStartOfFile(
SM.getFileID(
Loc));
289 SM.getFileOffset(
Loc));
290 return SM.getLocForEndOfFile(
SM.getFileID(
Loc));
296 :
SM.getIncludeLoc(
SM.getFileID(
Loc));
301 return SM.getBufferName(
SM.getSpellingLoc(
Loc)) ==
"<built-in>";
307 Loc = getIncludeOrExpansionLoc(
Loc);
317 while (
SM.isMacroArgExpansion(
Loc) || isInBuiltin(
Loc))
318 Loc =
SM.getImmediateExpansionRange(
Loc).getBegin();
325 while (
SM.isMacroArgExpansion(
Loc) || isInBuiltin(
Loc))
326 Loc =
SM.getImmediateExpansionRange(
Loc).getBegin();
327 return getPreciseTokenLocEnd(
Loc);
336 FileIDMapping.clear();
338 llvm::SmallSet<FileID, 8>
Visited;
340 for (
auto &Region : SourceRegions) {
345 auto BeginLoc =
SM.getSpellingLoc(
Loc);
346 auto EndLoc =
SM.getSpellingLoc(Region.getEndLoc());
347 if (
SM.isWrittenInSameFile(BeginLoc, EndLoc)) {
349 Region.setStartLoc(
Loc);
350 Region.setEndLoc(
SM.getFileLoc(Region.getEndLoc()));
359 !
SM.isInSystemHeader(
SM.getSpellingLoc(
Loc)));
365 FileLocs.push_back(std::make_pair(
Loc, Depth));
367 llvm::stable_sort(FileLocs, llvm::less_second());
369 for (
const auto &FL : FileLocs) {
371 FileID SpellingFile =
SM.getDecomposedSpellingLoc(
Loc).first;
372 auto Entry =
SM.getFileEntryRefForID(SpellingFile);
376 FileIDMapping[
SM.getFileID(
Loc)] = std::make_pair(Mapping.size(),
Loc);
377 Mapping.push_back(CVM.
getFileID(*Entry));
385 auto Mapping = FileIDMapping.find(
SM.getFileID(
Loc));
386 if (Mapping != FileIDMapping.end())
387 return Mapping->second.first;
401 SpellingRegion SR{
SM, LocStart, LocEnd};
403 if (PrevTokLoc.
isValid() &&
SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
404 SR.LineStart ==
SM.getSpellingLineNumber(PrevTokLoc))
406 if (NextTokLoc.
isValid() &&
SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
407 SR.LineEnd ==
SM.getSpellingLineNumber(NextTokLoc)) {
411 if (SR.isInSourceOrder())
418 void gatherSkippedRegions() {
422 FileLineRanges.resize(
423 FileIDMapping.size(),
424 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
425 for (
const auto &R : MappingRegions) {
426 FileLineRanges[R.FileID].first =
427 std::min(FileLineRanges[R.FileID].first, R.LineStart);
428 FileLineRanges[R.FileID].second =
429 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
433 for (
auto &I : SkippedRanges) {
437 assert(
SM.isWrittenInSameFile(LocStart, LocEnd) &&
438 "region spans multiple files");
440 auto CovFileID = getCoverageFileID(LocStart);
443 std::optional<SpellingRegion> SR;
445 SR = adjustSkippedRange(
SM, LocStart, LocEnd, I.PrevTokLoc,
447 else if (I.isPPIfElse() || I.isEmptyLine())
448 SR = {
SM, LocStart, LocEnd};
452 auto Region = CounterMappingRegion::makeSkipped(
453 *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
457 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
458 Region.LineEnd <= FileLineRanges[*CovFileID].second)
459 MappingRegions.push_back(Region);
465 void emitSourceRegions(
const SourceRegionFilter &Filter) {
466 for (
const auto &Region : SourceRegions) {
467 assert(Region.hasEndLoc() &&
"incomplete region");
470 assert(
SM.getFileID(LocStart).isValid() &&
"region in invalid file");
475 SM.isInSystemHeader(
SM.getSpellingLoc(LocStart)))
478 auto CovFileID = getCoverageFileID(LocStart);
484 assert(
SM.isWrittenInSameFile(LocStart, LocEnd) &&
485 "region spans multiple files");
491 if (
Filter.count(std::make_pair(LocStart, LocEnd)))
495 SpellingRegion SR{
SM, LocStart, LocEnd};
496 assert(SR.isInSourceOrder() &&
"region start and end out of order");
498 if (Region.isGap()) {
499 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
500 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
501 SR.LineEnd, SR.ColumnEnd));
502 }
else if (Region.isSkipped()) {
503 MappingRegions.push_back(CounterMappingRegion::makeSkipped(
504 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd,
506 }
else if (Region.isBranch()) {
507 MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
508 Region.getCounter(), Region.getFalseCounter(), *CovFileID,
509 SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd,
510 Region.getMCDCParams()));
511 }
else if (Region.isMCDCDecision()) {
512 MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion(
513 Region.getMCDCDecisionParams(), *CovFileID, SR.LineStart,
514 SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
516 MappingRegions.push_back(CounterMappingRegion::makeRegion(
517 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
518 SR.LineEnd, SR.ColumnEnd));
524 SourceRegionFilter emitExpansionRegions() {
525 SourceRegionFilter
Filter;
526 for (
const auto &FM : FileIDMapping) {
532 auto ParentFileID = getCoverageFileID(ParentLoc);
535 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
536 assert(ExpandedFileID &&
"expansion in uncovered file");
539 assert(
SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
540 "region spans multiple files");
541 Filter.insert(std::make_pair(ParentLoc, LocEnd));
543 SpellingRegion SR{
SM, ParentLoc, LocEnd};
544 assert(SR.isInSourceOrder() &&
"region start and end out of order");
545 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
546 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
547 SR.LineEnd, SR.ColumnEnd));
555struct EmptyCoverageMappingBuilder :
public CoverageMappingBuilder {
558 : CoverageMappingBuilder(CVM,
SM, LangOpts) {}
560 void VisitDecl(
const Decl *D) {
566 if (!
SM.isWrittenInSameFile(Start, End)) {
569 FileID StartFileID =
SM.getFileID(Start);
570 FileID EndFileID =
SM.getFileID(End);
571 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
572 Start = getIncludeOrExpansionLoc(Start);
574 "Declaration start location not nested within a known region");
575 StartFileID =
SM.getFileID(Start);
577 while (StartFileID != EndFileID) {
578 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
579 assert(End.isValid() &&
580 "Declaration end location not nested within a known region");
581 EndFileID =
SM.getFileID(End);
584 SourceRegions.emplace_back(Counter(), Start, End);
588 void write(llvm::raw_ostream &OS) {
590 gatherFileIDs(FileIDMapping);
591 emitSourceRegions(SourceRegionFilter());
593 if (MappingRegions.empty())
596 CoverageMappingWriter Writer(FileIDMapping, std::nullopt, MappingRegions);
609struct MCDCCoverageBuilder {
703 mcdc::ConditionID NextID = 0;
704 bool NotMapped =
false;
708 static constexpr mcdc::ConditionIDs DecisionStackSentinel{-1, -1};
717 : CGM(CGM), DecisionStack(1, DecisionStackSentinel),
718 MCDCState(MCDCState) {}
723 bool isIdle()
const {
return (NextID == 0 && !NotMapped); }
728 bool isBuilding()
const {
return (NextID > 0); }
731 void setCondID(
const Expr *Cond, mcdc::ConditionID
ID) {
736 mcdc::ConditionID getCondID(
const Expr *Cond)
const {
737 auto I = MCDCState.
BranchByStmt.find(CodeGenFunction::stripCond(Cond));
745 const mcdc::ConditionIDs &back()
const {
return DecisionStack.back(); }
756 !MCDCState.
DecisionByStmt.contains(CodeGenFunction::stripCond(E)))
763 const mcdc::ConditionIDs &ParentDecision = DecisionStack.back();
768 if (MCDCState.
BranchByStmt.contains(CodeGenFunction::stripCond(E)))
769 setCondID(E->
getLHS(), getCondID(E));
771 setCondID(E->
getLHS(), NextID++);
774 mcdc::ConditionID RHSid = NextID++;
775 setCondID(E->
getRHS(), RHSid);
779 DecisionStack.push_back({ParentDecision[
false], RHSid});
781 DecisionStack.push_back({RHSid, ParentDecision[
true]});
785 mcdc::ConditionIDs pop() {
787 return DecisionStackSentinel;
789 assert(DecisionStack.size() > 1);
790 return DecisionStack.pop_back_val();
800 assert(DecisionStack.size() == 1);
810 unsigned TotalConds = NextID;
821struct CounterCoverageMappingBuilder
822 :
public CoverageMappingBuilder,
825 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
837 MCDCCoverageBuilder MCDCBuilder;
839 CounterExpressionBuilder Builder;
848 bool HasTerminateStmt =
false;
851 Counter GapRegionCounter;
854 Counter subtractCounters(Counter LHS, Counter RHS,
bool Simplify =
true) {
856 "cannot add counters when single byte coverage mode is enabled");
857 return Builder.subtract(LHS, RHS, Simplify);
861 Counter addCounters(Counter LHS, Counter RHS,
bool Simplify =
true) {
863 "cannot add counters when single byte coverage mode is enabled");
864 return Builder.add(LHS, RHS, Simplify);
867 Counter addCounters(Counter C1, Counter C2, Counter C3,
868 bool Simplify =
true) {
870 "cannot add counters when single byte coverage mode is enabled");
871 return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
877 Counter getRegionCounter(
const Stmt *S) {
878 return Counter::getCounter(CounterMap[S]);
885 size_t pushRegion(Counter Count,
886 std::optional<SourceLocation> StartLoc = std::nullopt,
887 std::optional<SourceLocation> EndLoc = std::nullopt,
888 std::optional<Counter> FalseCount = std::nullopt,
889 const mcdc::Parameters &BranchParams = std::monostate()) {
891 if (StartLoc && !FalseCount) {
892 MostRecentLocation = *StartLoc;
897 assert((!StartLoc || StartLoc->isValid()) &&
"Start location is not valid");
898 assert((!EndLoc || EndLoc->isValid()) &&
"End location is not valid");
904 if (StartLoc && StartLoc->isInvalid())
905 StartLoc = std::nullopt;
906 if (EndLoc && EndLoc->isInvalid())
907 EndLoc = std::nullopt;
908 RegionStack.emplace_back(Count, FalseCount, BranchParams, StartLoc, EndLoc);
910 return RegionStack.size() - 1;
913 size_t pushRegion(
const mcdc::DecisionParameters &DecisionParams,
914 std::optional<SourceLocation> StartLoc = std::nullopt,
915 std::optional<SourceLocation> EndLoc = std::nullopt) {
917 RegionStack.emplace_back(DecisionParams, StartLoc, EndLoc);
919 return RegionStack.size() - 1;
925 Loc = getIncludeOrExpansionLoc(
Loc);
935 void popRegions(
size_t ParentIndex) {
936 assert(RegionStack.size() >= ParentIndex &&
"parent not in stack");
937 while (RegionStack.size() > ParentIndex) {
938 SourceMappingRegion &Region = RegionStack.back();
939 if (Region.hasStartLoc() &&
940 (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
944 : RegionStack[ParentIndex].getEndLoc();
945 bool isBranch = Region.isBranch();
946 size_t StartDepth = locationDepth(StartLoc);
947 size_t EndDepth = locationDepth(EndLoc);
948 while (!
SM.isWrittenInSameFile(StartLoc, EndLoc)) {
949 bool UnnestStart = StartDepth >= EndDepth;
950 bool UnnestEnd = EndDepth >= StartDepth;
959 assert(
SM.isWrittenInSameFile(NestedLoc, EndLoc));
961 if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
962 SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
965 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
967 llvm::report_fatal_error(
968 "File exit not handled before popRegions");
979 assert(
SM.isWrittenInSameFile(StartLoc, NestedLoc));
981 if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
982 SourceRegions.emplace_back(Region.getCounter(), StartLoc,
985 StartLoc = getIncludeOrExpansionLoc(StartLoc);
987 llvm::report_fatal_error(
988 "File exit not handled before popRegions");
992 Region.setStartLoc(StartLoc);
993 Region.setEndLoc(EndLoc);
996 MostRecentLocation = EndLoc;
999 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
1000 EndLoc == getEndOfFileOrMacro(EndLoc))
1001 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
1004 assert(
SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
1005 assert(SpellingRegion(
SM, Region).isInSourceOrder());
1006 SourceRegions.push_back(Region);
1008 RegionStack.pop_back();
1014 assert(!RegionStack.empty() &&
"statement has no region");
1015 return RegionStack.back();
1020 Counter propagateCounts(Counter TopCount,
const Stmt *S,
1021 bool VisitChildren =
true) {
1024 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
1027 Counter ExitCount =
getRegion().getCounter();
1032 if (
SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
1033 MostRecentLocation = EndLoc;
1039 bool ConditionFoldsToBool(
const Expr *Cond) {
1048 void createBranchRegion(
const Expr *
C, Counter TrueCnt, Counter FalseCnt,
1049 const mcdc::ConditionIDs &Conds = {}) {
1060 if (CodeGenFunction::isInstrumentedCondition(
C) ||
1061 LeafExprSet.count(CodeGenFunction::stripCond(
C))) {
1062 mcdc::Parameters BranchParams;
1063 mcdc::ConditionID
ID = MCDCBuilder.getCondID(
C);
1065 BranchParams = mcdc::BranchParameters{
ID, Conds};
1073 if (ConditionFoldsToBool(
C))
1074 popRegions(pushRegion(Counter::getZero(), getStart(
C), getEnd(
C),
1075 Counter::getZero(), BranchParams));
1078 popRegions(pushRegion(TrueCnt, getStart(
C), getEnd(
C), FalseCnt,
1086 void createDecisionRegion(
const Expr *
C,
1087 const mcdc::DecisionParameters &DecisionParams) {
1088 popRegions(pushRegion(DecisionParams, getStart(
C), getEnd(
C)));
1093 void createSwitchCaseRegion(
const SwitchCase *SC, Counter TrueCnt,
1098 popRegions(pushRegion(TrueCnt, getStart(SC), SC->
getColonLoc(), FalseCnt));
1104 bool isBranch =
false) {
1105 return llvm::any_of(
1106 llvm::reverse(SourceRegions), [&](
const SourceMappingRegion &Region) {
1107 return Region.getBeginLoc() == StartLoc &&
1108 Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
1116 MostRecentLocation = EndLoc;
1123 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
1124 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
1125 MostRecentLocation,
getRegion().isBranch()))
1126 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
1136 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
1142 FileID ParentFile =
SM.getFileID(LCA);
1143 while (!isNestedIn(MostRecentLocation, ParentFile)) {
1144 LCA = getIncludeOrExpansionLoc(LCA);
1145 if (LCA.
isInvalid() ||
SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
1148 MostRecentLocation = NewLoc;
1151 ParentFile =
SM.getFileID(LCA);
1154 llvm::SmallSet<SourceLocation, 8> StartLocs;
1155 std::optional<Counter> ParentCounter;
1156 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
1157 if (!I.hasStartLoc())
1160 if (!isNestedIn(
Loc, ParentFile)) {
1161 ParentCounter = I.getCounter();
1165 while (!
SM.isInFileID(
Loc, ParentFile)) {
1169 if (StartLocs.insert(
Loc).second) {
1171 SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(),
1172 I.getMCDCParams(),
Loc,
1173 getEndOfFileOrMacro(
Loc), I.isBranch());
1175 SourceRegions.emplace_back(I.getCounter(),
Loc,
1176 getEndOfFileOrMacro(
Loc));
1178 Loc = getIncludeOrExpansionLoc(
Loc);
1180 I.setStartLoc(getPreciseTokenLocEnd(
Loc));
1183 if (ParentCounter) {
1188 while (isNestedIn(
Loc, ParentFile)) {
1190 if (StartLocs.insert(FileStart).second) {
1191 SourceRegions.emplace_back(*ParentCounter, FileStart,
1192 getEndOfFileOrMacro(
Loc));
1193 assert(SpellingRegion(
SM, SourceRegions.back()).isInSourceOrder());
1195 Loc = getIncludeOrExpansionLoc(
Loc);
1199 MostRecentLocation = NewLoc;
1203 void extendRegion(
const Stmt *S) {
1204 SourceMappingRegion &Region =
getRegion();
1207 handleFileExit(StartLoc);
1208 if (!Region.hasStartLoc())
1209 Region.setStartLoc(StartLoc);
1213 void terminateRegion(
const Stmt *S) {
1215 SourceMappingRegion &Region =
getRegion();
1217 if (!Region.hasEndLoc())
1218 Region.setEndLoc(EndLoc);
1219 pushRegion(Counter::getZero());
1220 HasTerminateStmt =
true;
1224 std::optional<SourceRange> findGapAreaBetween(
SourceLocation AfterLoc,
1230 return std::nullopt;
1235 FileID FID =
SM.getFileID(AfterLoc);
1241 size_t StartDepth = locationDepth(AfterLoc);
1242 size_t EndDepth = locationDepth(BeforeLoc);
1243 while (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1244 bool UnnestStart = StartDepth >= EndDepth;
1245 bool UnnestEnd = EndDepth >= StartDepth;
1247 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1250 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1255 assert(
SM.isWrittenInSameFile(AfterLoc,
1256 getEndOfFileOrMacro(AfterLoc)));
1258 AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1260 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1265 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1269 return std::nullopt;
1270 if (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1271 !SpellingRegion(
SM, AfterLoc, BeforeLoc).isInSourceOrder())
1272 return std::nullopt;
1273 return {{AfterLoc, BeforeLoc}};
1279 if (StartLoc == EndLoc)
1281 assert(SpellingRegion(
SM, StartLoc, EndLoc).isInSourceOrder());
1282 handleFileExit(StartLoc);
1283 size_t Index = pushRegion(Count, StartLoc, EndLoc);
1285 handleFileExit(EndLoc);
1291 std::optional<SourceRange> findAreaStartingFromTo(
SourceLocation StartingLoc,
1295 FileID FID =
SM.getFileID(StartingLoc);
1301 size_t StartDepth = locationDepth(StartingLoc);
1302 size_t EndDepth = locationDepth(BeforeLoc);
1303 while (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc)) {
1304 bool UnnestStart = StartDepth >= EndDepth;
1305 bool UnnestEnd = EndDepth >= StartDepth;
1307 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1310 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1315 assert(
SM.isWrittenInSameFile(StartingLoc,
1316 getStartOfFileOrMacro(StartingLoc)));
1318 StartingLoc = getIncludeOrExpansionLoc(StartingLoc);
1319 assert(StartingLoc.
isValid());
1326 return std::nullopt;
1327 if (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc) ||
1328 !SpellingRegion(
SM, StartingLoc, BeforeLoc).isInSourceOrder())
1329 return std::nullopt;
1330 return {{StartingLoc, BeforeLoc}};
1334 const auto Skipped = findAreaStartingFromTo(StartLoc, BeforeLoc);
1339 const auto NewStartLoc = Skipped->getBegin();
1340 const auto EndLoc = Skipped->getEnd();
1342 if (NewStartLoc == EndLoc)
1344 assert(SpellingRegion(
SM, NewStartLoc, EndLoc).isInSourceOrder());
1345 handleFileExit(NewStartLoc);
1346 size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
1348 handleFileExit(EndLoc);
1353 struct BreakContinue {
1355 Counter ContinueCount;
1359 CounterCoverageMappingBuilder(
1361 llvm::DenseMap<const Stmt *, unsigned> &CounterMap,
1363 : CoverageMappingBuilder(CVM,
SM, LangOpts), CounterMap(CounterMap),
1364 MCDCState(MCDCState), MCDCBuilder(CVM.getCodeGenModule(), MCDCState) {}
1367 void write(llvm::raw_ostream &OS) {
1369 gatherFileIDs(VirtualFileMapping);
1370 SourceRegionFilter
Filter = emitExpansionRegions();
1371 emitSourceRegions(Filter);
1372 gatherSkippedRegions();
1374 if (MappingRegions.empty())
1377 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1382 void VisitStmt(
const Stmt *S) {
1383 if (S->getBeginLoc().isValid())
1385 const Stmt *LastStmt =
nullptr;
1386 bool SaveTerminateStmt = HasTerminateStmt;
1387 HasTerminateStmt =
false;
1388 GapRegionCounter = Counter::getZero();
1389 for (
const Stmt *Child : S->children())
1393 if (LastStmt && HasTerminateStmt) {
1394 auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1396 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1398 SaveTerminateStmt =
true;
1399 HasTerminateStmt =
false;
1404 if (SaveTerminateStmt)
1405 HasTerminateStmt =
true;
1406 handleFileExit(getEnd(S));
1409 void VisitDecl(
const Decl *D) {
1415 SM.isInSystemHeader(
SM.getSpellingLoc(getStart(Body))))
1422 Counter BodyCounter = getRegionCounter(Body);
1424 if (
auto *Method = dyn_cast<CXXMethodDecl>(D))
1426 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1430 if (getStart(
Init).isValid() && getEnd(
Init).isValid())
1431 propagateCounts(BodyCounter,
Init);
1436 propagateCounts(BodyCounter, Body,
1438 assert(RegionStack.empty() &&
"Regions entered but never exited");
1443 if (S->getRetValue())
1444 Visit(S->getRetValue());
1450 Visit(S->getBody());
1455 if (S->getOperand())
1456 Visit(S->getOperand());
1471 void VisitGotoStmt(
const GotoStmt *S) { terminateRegion(S); }
1473 void VisitLabelStmt(
const LabelStmt *S) {
1474 Counter LabelCount = getRegionCounter(S);
1477 handleFileExit(Start);
1478 pushRegion(LabelCount, Start);
1479 Visit(S->getSubStmt());
1482 void VisitBreakStmt(
const BreakStmt *S) {
1483 assert(!BreakContinueStack.empty() &&
"break not in a loop or switch!");
1485 BreakContinueStack.back().BreakCount = addCounters(
1486 BreakContinueStack.back().BreakCount,
getRegion().getCounter());
1493 assert(!BreakContinueStack.empty() &&
"continue stmt not in a loop!");
1495 BreakContinueStack.back().ContinueCount = addCounters(
1496 BreakContinueStack.back().ContinueCount,
getRegion().getCounter());
1500 void VisitCallExpr(
const CallExpr *E) {
1510 void VisitWhileStmt(
const WhileStmt *S) {
1513 Counter ParentCount =
getRegion().getCounter();
1515 ? getRegionCounter(S->getBody())
1516 : getRegionCounter(S);
1519 BreakContinueStack.push_back(BreakContinue());
1520 extendRegion(S->getBody());
1521 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1522 BreakContinue BC = BreakContinueStack.pop_back_val();
1524 bool BodyHasTerminateStmt = HasTerminateStmt;
1525 HasTerminateStmt =
false;
1530 ? getRegionCounter(S->getCond())
1531 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1532 propagateCounts(CondCount, S->getCond());
1533 adjustForOutOfOrderTraversal(getEnd(S));
1536 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1538 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1542 ? getRegionCounter(S)
1543 : addCounters(BC.BreakCount,
1544 subtractCounters(CondCount, BodyCount));
1546 if (OutCount != ParentCount) {
1547 pushRegion(OutCount);
1548 GapRegionCounter = OutCount;
1549 if (BodyHasTerminateStmt)
1550 HasTerminateStmt =
true;
1555 createBranchRegion(S->getCond(), BodyCount,
1556 subtractCounters(CondCount, BodyCount));
1559 void VisitDoStmt(
const DoStmt *S) {
1562 Counter ParentCount =
getRegion().getCounter();
1564 ? getRegionCounter(S->getBody())
1565 : getRegionCounter(S);
1567 BreakContinueStack.push_back(BreakContinue());
1568 extendRegion(S->getBody());
1570 Counter BackedgeCount;
1572 propagateCounts(BodyCount, S->getBody());
1575 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1577 BreakContinue BC = BreakContinueStack.pop_back_val();
1579 bool BodyHasTerminateStmt = HasTerminateStmt;
1580 HasTerminateStmt =
false;
1583 ? getRegionCounter(S->getCond())
1584 : addCounters(BackedgeCount, BC.ContinueCount);
1585 propagateCounts(CondCount, S->getCond());
1589 ? getRegionCounter(S)
1590 : addCounters(BC.BreakCount,
1591 subtractCounters(CondCount, BodyCount));
1592 if (OutCount != ParentCount) {
1593 pushRegion(OutCount);
1594 GapRegionCounter = OutCount;
1599 createBranchRegion(S->getCond(), BodyCount,
1600 subtractCounters(CondCount, BodyCount));
1602 if (BodyHasTerminateStmt)
1603 HasTerminateStmt =
true;
1606 void VisitForStmt(
const ForStmt *S) {
1609 Visit(S->getInit());
1611 Counter ParentCount =
getRegion().getCounter();
1613 ? getRegionCounter(S->getBody())
1614 : getRegionCounter(S);
1618 BreakContinueStack.emplace_back();
1621 BreakContinueStack.emplace_back();
1622 extendRegion(S->getBody());
1623 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1624 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1626 bool BodyHasTerminateStmt = HasTerminateStmt;
1627 HasTerminateStmt =
false;
1631 BreakContinue IncrementBC;
1632 if (
const Stmt *Inc = S->getInc()) {
1635 IncCount = getRegionCounter(S->getInc());
1637 IncCount = addCounters(BackedgeCount, BodyBC.ContinueCount);
1638 propagateCounts(IncCount, Inc);
1639 IncrementBC = BreakContinueStack.pop_back_val();
1645 ? getRegionCounter(S->getCond())
1647 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1648 IncrementBC.ContinueCount);
1650 if (
const Expr *Cond = S->getCond()) {
1651 propagateCounts(CondCount, Cond);
1652 adjustForOutOfOrderTraversal(getEnd(S));
1656 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1658 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1662 ? getRegionCounter(S)
1663 : addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1664 subtractCounters(CondCount, BodyCount));
1665 if (OutCount != ParentCount) {
1666 pushRegion(OutCount);
1667 GapRegionCounter = OutCount;
1668 if (BodyHasTerminateStmt)
1669 HasTerminateStmt =
true;
1674 createBranchRegion(S->getCond(), BodyCount,
1675 subtractCounters(CondCount, BodyCount));
1681 Visit(S->getInit());
1682 Visit(S->getLoopVarStmt());
1683 Visit(S->getRangeStmt());
1685 Counter ParentCount =
getRegion().getCounter();
1687 ? getRegionCounter(S->getBody())
1688 : getRegionCounter(S);
1690 BreakContinueStack.push_back(BreakContinue());
1691 extendRegion(S->getBody());
1692 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1693 BreakContinue BC = BreakContinueStack.pop_back_val();
1695 bool BodyHasTerminateStmt = HasTerminateStmt;
1696 HasTerminateStmt =
false;
1699 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1701 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1706 OutCount = getRegionCounter(S);
1708 LoopCount = addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1710 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1712 if (OutCount != ParentCount) {
1713 pushRegion(OutCount);
1714 GapRegionCounter = OutCount;
1715 if (BodyHasTerminateStmt)
1716 HasTerminateStmt =
true;
1721 createBranchRegion(S->getCond(), BodyCount,
1722 subtractCounters(LoopCount, BodyCount));
1727 Visit(S->getElement());
1729 Counter ParentCount =
getRegion().getCounter();
1730 Counter BodyCount = getRegionCounter(S);
1732 BreakContinueStack.push_back(BreakContinue());
1733 extendRegion(S->getBody());
1734 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1735 BreakContinue BC = BreakContinueStack.pop_back_val();
1738 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1740 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1743 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1745 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1746 if (OutCount != ParentCount) {
1747 pushRegion(OutCount);
1748 GapRegionCounter = OutCount;
1755 Visit(S->getInit());
1756 Visit(S->getCond());
1758 BreakContinueStack.push_back(BreakContinue());
1760 const Stmt *Body = S->getBody();
1762 if (
const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1763 if (!CS->body_empty()) {
1767 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1772 for (
size_t i = RegionStack.size(); i != Index; --i) {
1773 if (!RegionStack[i - 1].hasEndLoc())
1774 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1780 propagateCounts(Counter::getZero(), Body);
1781 BreakContinue BC = BreakContinueStack.pop_back_val();
1784 BreakContinueStack.back().ContinueCount = addCounters(
1785 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1787 Counter ParentCount =
getRegion().getCounter();
1788 Counter ExitCount = getRegionCounter(S);
1790 pushRegion(ExitCount);
1791 GapRegionCounter = ExitCount;
1795 MostRecentLocation = getStart(S);
1796 handleFileExit(ExitLoc);
1805 Counter CaseCountSum;
1806 bool HasDefaultCase =
false;
1807 const SwitchCase *Case = S->getSwitchCaseList();
1809 HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1811 addCounters(CaseCountSum, getRegionCounter(Case),
false);
1812 createSwitchCaseRegion(
1813 Case, getRegionCounter(Case),
1814 subtractCounters(ParentCount, getRegionCounter(Case)));
1819 CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
1824 if (!HasDefaultCase) {
1825 Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1826 Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1827 createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1836 ? getRegionCounter(S)
1837 : addCounters(
Parent.getCounter(), getRegionCounter(S));
1841 if (
Parent.hasStartLoc() &&
Parent.getBeginLoc() == getStart(S))
1842 Parent.setCounter(Count);
1844 pushRegion(Count, getStart(S));
1846 GapRegionCounter = Count;
1848 if (
const auto *CS = dyn_cast<CaseStmt>(S)) {
1849 Visit(CS->getLHS());
1850 if (
const Expr *RHS = CS->getRHS())
1853 Visit(S->getSubStmt());
1856 void coverIfConsteval(
const IfStmt *S) {
1857 assert(S->isConsteval());
1859 const auto *Then = S->getThen();
1860 const auto *Else = S->getElse();
1865 const Counter ParentCount =
getRegion().getCounter();
1869 if (S->isNegatedConsteval()) {
1871 markSkipped(S->getIfLoc(), getStart(Then));
1872 propagateCounts(ParentCount, Then);
1876 markSkipped(getEnd(Then), getEnd(Else));
1879 assert(S->isNonNegatedConsteval());
1881 markSkipped(S->getIfLoc(), Else ? getStart(Else) : getEnd(Then));
1884 propagateCounts(ParentCount, Else);
1888 void coverIfConstexpr(
const IfStmt *S) {
1889 assert(S->isConstexpr());
1901 const Counter ParentCount =
getRegion().getCounter();
1906 if (
const auto *
Init = S->getInit()) {
1907 const auto start = getStart(
Init);
1908 const auto end = getEnd(
Init);
1912 if (start.isValid() && end.isValid()) {
1913 markSkipped(startOfSkipped, start);
1914 propagateCounts(ParentCount,
Init);
1915 startOfSkipped = getEnd(
Init);
1919 const auto *Then = S->getThen();
1920 const auto *Else = S->getElse();
1924 markSkipped(startOfSkipped, getStart(Then));
1925 propagateCounts(ParentCount, Then);
1929 markSkipped(getEnd(Then), getEnd(Else));
1932 markSkipped(startOfSkipped, Else ? getStart(Else) : getEnd(Then));
1935 propagateCounts(ParentCount, Else);
1939 void VisitIfStmt(
const IfStmt *S) {
1942 if (S->isConsteval())
1943 return coverIfConsteval(S);
1944 else if (S->isConstexpr())
1945 return coverIfConstexpr(S);
1949 Visit(S->getInit());
1953 extendRegion(S->getCond());
1955 Counter ParentCount =
getRegion().getCounter();
1957 ? getRegionCounter(S->getThen())
1958 : getRegionCounter(S);
1962 propagateCounts(ParentCount, S->getCond());
1965 std::optional<SourceRange> Gap =
1966 findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1968 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1970 extendRegion(S->getThen());
1971 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1975 ElseCount = subtractCounters(ParentCount, ThenCount);
1976 else if (S->getElse())
1977 ElseCount = getRegionCounter(S->getElse());
1979 if (
const Stmt *Else = S->getElse()) {
1980 bool ThenHasTerminateStmt = HasTerminateStmt;
1981 HasTerminateStmt =
false;
1983 std::optional<SourceRange> Gap =
1984 findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1986 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
1989 Counter ElseOutCount = propagateCounts(ElseCount, Else);
1991 OutCount = addCounters(OutCount, ElseOutCount);
1993 if (ThenHasTerminateStmt)
1994 HasTerminateStmt =
true;
1996 OutCount = addCounters(OutCount, ElseCount);
1999 OutCount = getRegionCounter(S);
2001 if (OutCount != ParentCount) {
2002 pushRegion(OutCount);
2003 GapRegionCounter = OutCount;
2008 createBranchRegion(S->getCond(), ThenCount,
2009 subtractCounters(ParentCount, ThenCount));
2015 extendRegion(S->getTryBlock());
2017 Counter ParentCount =
getRegion().getCounter();
2018 propagateCounts(ParentCount, S->getTryBlock());
2020 for (
unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
2021 Visit(S->getHandler(I));
2023 Counter ExitCount = getRegionCounter(S);
2024 pushRegion(ExitCount);
2028 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
2034 Counter ParentCount =
getRegion().getCounter();
2037 : getRegionCounter(E);
2040 if (
const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) {
2041 propagateCounts(ParentCount, BCO->getCommon());
2042 OutCount = TrueCount;
2044 propagateCounts(ParentCount, E->
getCond());
2049 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
2052 OutCount = propagateCounts(TrueCount, E->
getTrueExpr());
2058 : subtractCounters(ParentCount, TrueCount);
2060 Counter FalseOutCount = propagateCounts(FalseCount, E->
getFalseExpr());
2062 OutCount = getRegionCounter(E);
2064 OutCount = addCounters(OutCount, FalseOutCount);
2066 if (OutCount != ParentCount) {
2067 pushRegion(OutCount);
2068 GapRegionCounter = OutCount;
2073 createBranchRegion(E->
getCond(), TrueCount,
2074 subtractCounters(ParentCount, TrueCount));
2078 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
2082 auto DecisionParams = mcdc::DecisionParameters{
2088 createDecisionRegion(E, DecisionParams);
2100 if (isExprInSystemHeader(E)) {
2101 LeafExprSet.insert(E);
2105 bool IsRootNode = MCDCBuilder.isIdle();
2108 MCDCBuilder.pushAndAssignIDs(E);
2110 extendRegion(E->
getLHS());
2112 handleFileExit(getEnd(E->
getLHS()));
2115 const auto DecisionLHS = MCDCBuilder.pop();
2118 extendRegion(E->
getRHS());
2119 propagateCounts(getRegionCounter(E), E->
getRHS());
2122 const auto DecisionRHS = MCDCBuilder.back();
2125 Counter RHSExecCnt = getRegionCounter(E);
2128 Counter RHSTrueCnt = getRegionCounter(E->
getRHS());
2131 Counter ParentCnt =
getRegion().getCounter();
2135 createBranchRegion(E->
getLHS(), RHSExecCnt,
2136 subtractCounters(ParentCnt, RHSExecCnt), DecisionLHS);
2140 createBranchRegion(E->
getRHS(), RHSTrueCnt,
2141 subtractCounters(RHSExecCnt, RHSTrueCnt), DecisionRHS);
2149 bool shouldVisitRHS(
const Expr *LHS) {
2150 bool LHSIsTrue =
false;
2151 bool LHSIsConst =
false;
2155 return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
2159 if (isExprInSystemHeader(E)) {
2160 LeafExprSet.insert(E);
2164 bool IsRootNode = MCDCBuilder.isIdle();
2167 MCDCBuilder.pushAndAssignIDs(E);
2169 extendRegion(E->
getLHS());
2170 Counter OutCount = propagateCounts(
getRegion().getCounter(), E->
getLHS());
2171 handleFileExit(getEnd(E->
getLHS()));
2174 const auto DecisionLHS = MCDCBuilder.pop();
2177 extendRegion(E->
getRHS());
2178 propagateCounts(getRegionCounter(E), E->
getRHS());
2181 const auto DecisionRHS = MCDCBuilder.back();
2184 Counter RHSExecCnt = getRegionCounter(E);
2187 Counter RHSFalseCnt = getRegionCounter(E->
getRHS());
2189 if (!shouldVisitRHS(E->
getLHS())) {
2190 GapRegionCounter = OutCount;
2194 Counter ParentCnt =
getRegion().getCounter();
2198 createBranchRegion(E->
getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
2199 RHSExecCnt, DecisionLHS);
2203 createBranchRegion(E->
getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
2204 RHSFalseCnt, DecisionRHS);
2232static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
2235 OS << FunctionName <<
":\n";
2236 CounterMappingContext Ctx(Expressions);
2237 for (
const auto &R : Regions) {
2240 case CounterMappingRegion::CodeRegion:
2242 case CounterMappingRegion::ExpansionRegion:
2245 case CounterMappingRegion::SkippedRegion:
2248 case CounterMappingRegion::GapRegion:
2251 case CounterMappingRegion::BranchRegion:
2252 case CounterMappingRegion::MCDCBranchRegion:
2255 case CounterMappingRegion::MCDCDecisionRegion:
2260 OS <<
"File " << R.FileID <<
", " << R.LineStart <<
":" << R.ColumnStart
2261 <<
" -> " << R.LineEnd <<
":" << R.ColumnEnd <<
" = ";
2263 if (
const auto *DecisionParams =
2264 std::get_if<mcdc::DecisionParameters>(&R.MCDCParams)) {
2265 OS <<
"M:" << DecisionParams->BitmapIdx;
2266 OS <<
", C:" << DecisionParams->NumConditions;
2268 Ctx.dump(R.Count, OS);
2270 if (R.Kind == CounterMappingRegion::BranchRegion ||
2271 R.Kind == CounterMappingRegion::MCDCBranchRegion) {
2273 Ctx.dump(R.FalseCount, OS);
2277 if (
const auto *BranchParams =
2278 std::get_if<mcdc::BranchParameters>(&R.MCDCParams)) {
2279 OS <<
" [" << BranchParams->ID + 1 <<
","
2280 << BranchParams->Conds[
true] + 1;
2281 OS <<
"," << BranchParams->Conds[
false] + 1 <<
"] ";
2284 if (R.Kind == CounterMappingRegion::ExpansionRegion)
2285 OS <<
" (Expanded file = " << R.ExpandedFileID <<
")";
2292 : CGM(CGM), SourceInfo(SourceInfo) {}
2294std::string CoverageMappingModuleGen::getCurrentDirname() {
2299 llvm::sys::fs::current_path(CWD);
2300 return CWD.str().str();
2303std::string CoverageMappingModuleGen::normalizeFilename(StringRef
Filename) {
2305 llvm::sys::path::remove_dots(Path,
true);
2310 for (
const auto &[From, To] :
2312 if (llvm::sys::path::replace_path_prefix(Path, From, To))
2315 return Path.str().str();
2319 llvm::InstrProfSectKind SK) {
2320 return llvm::getInstrProfSectionName(
2324void CoverageMappingModuleGen::emitFunctionMappingRecord(
2325 const FunctionInfo &Info, uint64_t FilenamesRef) {
2329 std::string FuncRecordName =
"__covrec_" + llvm::utohexstr(Info.NameHash);
2336 FuncRecordName +=
"u";
2339 const uint64_t NameHash = Info.NameHash;
2340 const uint64_t FuncHash = Info.FuncHash;
2341 const std::string &CoverageMapping = Info.CoverageMapping;
2342#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2343 llvm::Type *FunctionRecordTypes[] = {
2344#include "llvm/ProfileData/InstrProfData.inc"
2346 auto *FunctionRecordTy =
2347 llvm::StructType::get(Ctx,
ArrayRef(FunctionRecordTypes),
2351#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2352 llvm::Constant *FunctionRecordVals[] = {
2353 #include "llvm/ProfileData/InstrProfData.inc"
2355 auto *FuncRecordConstant =
2356 llvm::ConstantStruct::get(FunctionRecordTy,
ArrayRef(FunctionRecordVals));
2359 auto *FuncRecord =
new llvm::GlobalVariable(
2360 CGM.
getModule(), FunctionRecordTy,
true,
2361 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2363 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2365 FuncRecord->setAlignment(llvm::Align(8));
2367 FuncRecord->setComdat(CGM.
getModule().getOrInsertComdat(FuncRecordName));
2374 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2375 const std::string &CoverageMapping,
bool IsUsed) {
2376 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2377 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2380 FunctionNames.push_back(NamePtr);
2389 std::vector<StringRef> Filenames;
2390 std::vector<CounterExpression> Expressions;
2391 std::vector<CounterMappingRegion> Regions;
2392 FilenameStrs.resize(FileEntries.size() + 1);
2393 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2394 for (
const auto &Entry : FileEntries) {
2395 auto I = Entry.second;
2396 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2399 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
2400 Expressions, Regions);
2403 dump(llvm::outs(), NameValue, Expressions, Regions);
2408 if (FunctionRecords.empty())
2411 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
2415 FilenameStrs.resize(FileEntries.size() + 1);
2417 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2418 for (
const auto &Entry : FileEntries) {
2419 auto I = Entry.second;
2420 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2423 std::string Filenames;
2425 llvm::raw_string_ostream OS(Filenames);
2426 CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
2428 auto *FilenamesVal =
2429 llvm::ConstantDataArray::getString(Ctx, Filenames,
false);
2430 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
2433 for (
const FunctionInfo &Info : FunctionRecords)
2434 emitFunctionMappingRecord(Info, FilenamesRef);
2436 const unsigned NRecords = 0;
2437 const size_t FilenamesSize = Filenames.size();
2438 const unsigned CoverageMappingSize = 0;
2439 llvm::Type *CovDataHeaderTypes[] = {
2440#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2441#include "llvm/ProfileData/InstrProfData.inc"
2443 auto CovDataHeaderTy =
2444 llvm::StructType::get(Ctx,
ArrayRef(CovDataHeaderTypes));
2445 llvm::Constant *CovDataHeaderVals[] = {
2446#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2447#include "llvm/ProfileData/InstrProfData.inc"
2449 auto CovDataHeaderVal =
2450 llvm::ConstantStruct::get(CovDataHeaderTy,
ArrayRef(CovDataHeaderVals));
2453 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2454 auto CovDataTy = llvm::StructType::get(Ctx,
ArrayRef(CovDataTypes));
2455 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2456 auto CovDataVal = llvm::ConstantStruct::get(CovDataTy,
ArrayRef(TUDataVals));
2457 auto CovData =
new llvm::GlobalVariable(
2458 CGM.
getModule(), CovDataTy,
true, llvm::GlobalValue::PrivateLinkage,
2459 CovDataVal, llvm::getCoverageMappingVarName());
2462 CovData->setAlignment(llvm::Align(8));
2467 if (!FunctionNames.empty()) {
2468 auto NamesArrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx),
2469 FunctionNames.size());
2470 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
2473 new llvm::GlobalVariable(CGM.
getModule(), NamesArrTy,
true,
2474 llvm::GlobalValue::InternalLinkage, NamesArrVal,
2475 llvm::getCoverageUnusedNamesVarName());
2480 auto It = FileEntries.find(
File);
2481 if (It != FileEntries.end())
2483 unsigned FileID = FileEntries.size() + 1;
2484 FileEntries.insert(std::make_pair(
File,
FileID));
2489 llvm::raw_ostream &OS) {
2490 assert(CounterMap && MCDCState);
2491 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCState,
SM,
2493 Walker.VisitDecl(D);
2498 llvm::raw_ostream &OS) {
2499 EmptyCoverageMappingBuilder Walker(CVM,
SM, LangOpts);
2500 Walker.VisitDecl(D);
Defines the Diagnostic-related interfaces.
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
llvm::cl::opt< bool > SystemHeadersCoverage
static std::string getInstrProfSection(const CodeGenModule &CGM, llvm::InstrProfSectKind SK)
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
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)
Defines the clang::FileManager interface and associated types.
llvm::DenseSet< const void * > Visited
const TargetInfo & getTargetInfo() const
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
SourceLocation getQuestionLoc() const
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Represents a loop initializing the elements of an array.
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
A builtin binary operation expression such as "x + y" or "x <= y".
SourceLocation getBeginLoc() const LLVM_READONLY
SourceLocation getOperatorLoc() const
SourceLocation getEndLoc() const LLVM_READONLY
BreakStmt - This represents a break.
CXXCatchStmt - This represents a C++ catch block.
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
A C++ throw-expression (C++ [except.throw]).
const Expr * getSubExpr() const
CXXTryStmt - A C++ try block, including all handlers.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
llvm::SmallVector< std::pair< std::string, std::string >, 0 > CoveragePrefixMap
Prefix replacement map for source-based code coverage to remap source file paths in coverage mapping.
std::string CoverageCompilationDir
The string to embed in coverage mapping as the current working directory.
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
ASTContext & getContext() const
bool supportsCOMDAT() const
const CodeGenOptions & getCodeGenOpts() const
llvm::LLVMContext & getLLVMContext()
void emitEmptyMapping(const Decl *D, llvm::raw_ostream &OS)
Emit the coverage mapping data for an unused function.
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...
Organizes the cross-function state that is used while generating code coverage mapping data.
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.
CoverageSourceInfo & getSourceInfo() const
static CoverageSourceInfo * setUpCoverageCallbacks(Preprocessor &PP)
CoverageMappingModuleGen(CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
void emit()
Emit the coverage mapping data for a translation unit.
CodeGenModule & getCodeGenModule()
Return an interface into CodeGenModule.
unsigned getFileID(FileEntryRef File)
Return the coverage mapping translation unit file id for the given file.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
ContinueStmt - This represents a continue.
Represents a 'co_return' statement in the C++ Coroutines TS.
Represents the body of a coroutine.
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Expr * getOperand() const
Stores additional source code information like skipped ranges which is required by the coverage mappi...
void SourceRangeSkipped(SourceRange Range, SourceLocation EndifLoc) override
Hook called when a source range is skipped.
void updateNextTokLoc(SourceLocation Loc)
void AddSkippedRange(SourceRange Range, SkippedRange::Kind RangeKind)
std::vector< SkippedRange > & getSkippedRanges()
bool HandleComment(Preprocessor &PP, SourceRange Range) override
SourceLocation PrevTokLoc
void HandleEmptyline(SourceRange Range) override
Decl - This represents one declaration (or definition), e.g.
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
DoStmt - This represents a 'do/while' stmt.
This represents one expression.
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,...
bool isValueDependent() const
Determines whether the value of this expression depends on.
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
ForStmt - This represents a 'for (init;cond;inc)' stmt.
GotoStmt - This represents a direct goto.
IfStmt - This represents an if/then/else.
LabelStmt - Represents a label, which has a substatement.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
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 ...
Represents Objective-C's collection statement.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
void addCommentHandler(CommentHandler *Handler)
Add the specified comment handler to the preprocessor.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
SourceManager & getSourceManager() const
void setPreprocessToken(bool Preprocess)
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.
void setEmptylineHandler(EmptylineHandler *Handler)
Set empty line handler.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
A (possibly-)qualified type.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
SourceLocation getExpansionLocStart() const
bool isFunctionMacroExpansion() const
SourceLocation getExpansionLocEnd() const
Stmt - This represents one statement.
SourceLocation getColonLoc() const
const SwitchCase * getNextSwitchCase() const
SwitchStmt - This represents a 'switch' stmt.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Token - This structure provides full information about a lexed token.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
tok::TokenKind getKind() const
WhileStmt - This represents a 'while' stmt.
The JSON file list parser is used to communicate input to InstallAPI.
FunctionType::ExtInfo getFunctionExtInfo(const Type &t)
Diagnostic wrappers for TextAPI types for error reporting.
cl::opt< bool > EnableSingleByteCoverage
Per-Function MC/DC state.
llvm::DenseMap< const Stmt *, Branch > BranchByStmt
llvm::DenseMap< const Stmt *, Decision > DecisionByStmt
EvalResult is a struct with detailed info about an evaluated expression.