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"
36 llvm::cl::desc(
"Enable single byte coverage"),
37 llvm::cl::Hidden, llvm::cl::init(
false));
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);
48 "system-headers-coverage",
49 cl::desc(
"Enable collecting coverage from system headers"), cl::init(
false),
54using namespace CodeGen;
69 if (Tok.
getKind() != clang::tok::eod)
79 PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
80 SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
84 SkippedRanges.push_back({
Range, RangeKind, PrevTokLoc});
101 if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
102 SkippedRanges.back().NextTokLoc =
Loc;
107class SourceMappingRegion {
112 std::optional<Counter> FalseCount;
115 mcdc::Parameters MCDCParams;
118 std::optional<SourceLocation> LocStart;
121 std::optional<SourceLocation> LocEnd;
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),
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(); }
167 assert(LocStart &&
"Region has no start location");
171 bool hasEndLoc()
const {
return LocEnd.has_value(); }
174 assert(
Loc.
isValid() &&
"Setting an invalid end location");
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(); }
215struct SpellingRegion {
220 unsigned ColumnStart;
230 LineStart =
SM.getSpellingLineNumber(LocStart);
231 ColumnStart =
SM.getSpellingColumnNumber(LocStart);
232 LineEnd =
SM.getSpellingLineNumber(LocEnd);
233 ColumnEnd =
SM.getSpellingColumnNumber(LocEnd);
237 : SpellingRegion(
SM, R.getBeginLoc(), R.getEndLoc()) {}
241 bool isInSourceOrder()
const {
242 return (LineStart < LineEnd) ||
243 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
249class CoverageMappingBuilder {
257 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
264 std::vector<SourceMappingRegion> SourceRegions;
271 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
276 : CVM(CVM),
SM(
SM), LangOpts(LangOpts) {}
291 return SM.getLocForStartOfFile(
SM.getFileID(
Loc));
298 SM.getFileOffset(
Loc));
299 return SM.getLocForEndOfFile(
SM.getFileID(
Loc));
309 std::pair<SourceLocation, std::optional<SourceLocation>>
311 std::optional<SourceLocation> EndLoc = std::nullopt;
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);
325 bool AcceptScratch =
true) {
327 return SM.getIncludeLoc(
SM.getFileID(
Loc));
328 Loc =
SM.getImmediateExpansionRange(
Loc).getBegin();
331 return getNonScratchExpansionLoc(
Loc).first;
336 return SM.getBufferName(
SM.getSpellingLoc(
Loc)) ==
"<built-in>";
342 Loc = getIncludeOrExpansionLoc(
Loc);
352 while (
SM.isMacroArgExpansion(
Loc) || isInBuiltin(
Loc))
353 Loc =
SM.getImmediateExpansionRange(
Loc).getBegin();
360 while (
SM.isMacroArgExpansion(
Loc) || isInBuiltin(
Loc))
361 Loc =
SM.getImmediateExpansionRange(
Loc).getBegin();
362 return getPreciseTokenLocEnd(
Loc);
371 FileIDMapping.clear();
373 llvm::SmallSet<FileID, 8>
Visited;
375 for (
auto &Region : SourceRegions) {
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());
389 auto BeginLoc =
SM.getSpellingLoc(
Loc);
390 auto EndLoc =
SM.getSpellingLoc(Region.getEndLoc());
391 if (
SM.isWrittenInSameFile(BeginLoc, EndLoc)) {
393 Region.setStartLoc(
Loc);
394 Region.setEndLoc(
SM.getFileLoc(Region.getEndLoc()));
403 !
SM.isInSystemHeader(
SM.getSpellingLoc(
Loc)));
409 FileLocs.push_back(std::make_pair(
Loc, Depth));
411 llvm::stable_sort(FileLocs, llvm::less_second());
413 for (
const auto &FL : FileLocs) {
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));
429 auto Mapping = FileIDMapping.find(
SM.getFileID(
Loc));
430 if (Mapping != FileIDMapping.end())
431 return Mapping->second.first;
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())
462 void gatherSkippedRegions() {
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);
477 for (
auto &I : SkippedRanges) {
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,
501 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
502 Region.LineEnd <= FileLineRanges[*CovFileID].second)
503 MappingRegions.push_back(Region);
509 void emitSourceRegions(
const SourceRegionFilter &Filter) {
510 for (
const auto &Region : SourceRegions) {
511 assert(Region.hasEndLoc() &&
"incomplete region");
514 assert(
SM.getFileID(LocStart).isValid() &&
"region in invalid file");
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);
528 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
529 "Don't suppress the condition in non-file regions");
534 assert(
SM.isWrittenInSameFile(LocStart, LocEnd) &&
535 "region spans multiple files");
541 if (
Filter.count(std::make_pair(LocStart, LocEnd))) {
542 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
543 "Don't suppress the condition");
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));
577 SourceRegionFilter emitExpansionRegions() {
578 SourceRegionFilter
Filter;
579 for (
const auto &FM : FileIDMapping) {
581 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc,
false);
585 auto ParentFileID = getCoverageFileID(ParentLoc);
588 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
589 assert(ExpandedFileID &&
"expansion in uncovered file");
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));
608struct EmptyCoverageMappingBuilder :
public CoverageMappingBuilder {
611 : CoverageMappingBuilder(CVM,
SM, LangOpts) {}
613 void VisitDecl(
const Decl *
D) {
619 if (!
SM.isWrittenInSameFile(Start, End)) {
622 FileID StartFileID =
SM.getFileID(Start);
623 FileID EndFileID =
SM.getFileID(End);
624 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
625 Start = getIncludeOrExpansionLoc(Start);
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);
641 void write(llvm::raw_ostream &OS) {
643 gatherFileIDs(FileIDMapping);
644 emitSourceRegions(SourceRegionFilter());
646 if (MappingRegions.empty())
649 CoverageMappingWriter Writer(FileIDMapping, {}, MappingRegions);
662struct MCDCCoverageBuilder {
756 const Stmt *DecisionStmt =
nullptr;
757 mcdc::ConditionID NextID = 0;
758 bool NotMapped =
false;
762 static constexpr mcdc::ConditionIDs DecisionStackSentinel{-1, -1};
766 return E->getOpcode() == BO_LAnd;
771 : CGM(CGM), DecisionStack(1, DecisionStackSentinel),
772 MCDCState(MCDCState) {}
777 bool isIdle()
const {
return (NextID == 0 && !NotMapped); }
782 bool isBuilding()
const {
return (NextID > 0); }
785 void setCondID(
const Expr *Cond, mcdc::ConditionID
ID) {
791 mcdc::ConditionID getCondID(
const Expr *Cond)
const {
792 auto I = MCDCState.
BranchByStmt.find(CodeGenFunction::stripCond(Cond));
800 const mcdc::ConditionIDs &back()
const {
return DecisionStack.back(); }
823 const mcdc::ConditionIDs &ParentDecision = DecisionStack.back();
828 if (MCDCState.
BranchByStmt.contains(CodeGenFunction::stripCond(
E)))
829 setCondID(
E->getLHS(), getCondID(
E));
831 setCondID(
E->getLHS(), NextID++);
834 mcdc::ConditionID RHSid = NextID++;
835 setCondID(
E->getRHS(), RHSid);
839 DecisionStack.push_back({ParentDecision[
false], RHSid});
841 DecisionStack.push_back({RHSid, ParentDecision[
true]});
845 mcdc::ConditionIDs pop() {
847 return DecisionStackSentinel;
849 assert(DecisionStack.size() > 1);
850 return DecisionStack.pop_back_val();
860 assert(DecisionStack.size() == 1);
870 unsigned TotalConds = NextID;
881struct CounterCoverageMappingBuilder
882 :
public CoverageMappingBuilder,
885 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
894 llvm::DenseSet<const Stmt *> LeafExprSet;
897 MCDCCoverageBuilder MCDCBuilder;
899 CounterExpressionBuilder Builder;
908 bool HasTerminateStmt =
false;
911 Counter GapRegionCounter;
914 Counter subtractCounters(Counter LHS, Counter RHS,
bool Simplify =
true) {
916 "cannot add counters when single byte coverage mode is enabled");
917 return Builder.subtract(LHS, RHS, Simplify);
921 Counter addCounters(Counter LHS, Counter RHS,
bool Simplify =
true) {
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) {
930 "cannot add counters when single byte coverage mode is enabled");
931 return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
937 Counter getRegionCounter(
const Stmt *S) {
938 return Counter::getCounter(CounterMap[S]);
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;
957 assert((!StartLoc || StartLoc->isValid()) &&
"Start location is not valid");
958 assert((!EndLoc || EndLoc->isValid()) &&
"End location is not valid");
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;
985 Loc = getIncludeOrExpansionLoc(
Loc);
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())) {
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;
1019 assert(
SM.isWrittenInSameFile(NestedLoc, EndLoc));
1021 if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
1022 SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
1025 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
1027 llvm::report_fatal_error(
1028 "File exit not handled before popRegions");
1039 assert(
SM.isWrittenInSameFile(StartLoc, NestedLoc));
1041 if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
1042 SourceRegions.emplace_back(Region.getCounter(), StartLoc,
1045 StartLoc = getIncludeOrExpansionLoc(StartLoc);
1047 llvm::report_fatal_error(
1048 "File exit not handled before popRegions");
1052 Region.setStartLoc(StartLoc);
1053 Region.setEndLoc(EndLoc);
1056 MostRecentLocation = EndLoc;
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();
1074 assert(!RegionStack.empty() &&
"statement has no region");
1075 return RegionStack.back();
1080 Counter propagateCounts(Counter TopCount,
const Stmt *S,
1081 bool VisitChildren =
true) {
1084 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
1087 Counter ExitCount =
getRegion().getCounter();
1092 if (
SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
1093 MostRecentLocation = EndLoc;
1102 void createBranchRegion(
const Expr *
C, Counter TrueCnt, Counter FalseCnt,
1103 const mcdc::ConditionIDs &Conds = {}) {
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};
1129 if (Result.Val.getInt().getBoolValue())
1130 FalseCnt = Counter::getZero();
1132 TrueCnt = Counter::getZero();
1135 pushRegion(TrueCnt, getStart(
C), getEnd(
C), FalseCnt, BranchParams));
1142 void createDecisionRegion(
const Expr *
C,
1143 const mcdc::DecisionParameters &DecisionParams) {
1144 popRegions(pushRegion(DecisionParams, getStart(
C), getEnd(
C)));
1150 Counter createSwitchCaseRegion(
const SwitchCase *SC, Counter ParentCount) {
1154 Counter TrueCnt = getRegionCounter(SC);
1155 popRegions(pushRegion(TrueCnt, getStart(SC), SC->
getColonLoc(),
1156 subtractCounters(ParentCount, TrueCnt)));
1163 bool isBranch =
false) {
1164 return llvm::any_of(
1165 llvm::reverse(SourceRegions), [&](
const SourceMappingRegion &Region) {
1166 return Region.getBeginLoc() == StartLoc &&
1167 Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
1175 MostRecentLocation = EndLoc;
1182 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
1183 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
1184 MostRecentLocation,
getRegion().isBranch()))
1185 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
1195 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
1201 FileID ParentFile =
SM.getFileID(LCA);
1202 while (!isNestedIn(MostRecentLocation, ParentFile)) {
1203 LCA = getIncludeOrExpansionLoc(LCA);
1204 if (LCA.
isInvalid() ||
SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
1207 MostRecentLocation = NewLoc;
1210 ParentFile =
SM.getFileID(LCA);
1213 llvm::SmallSet<SourceLocation, 8> StartLocs;
1214 std::optional<Counter> ParentCounter;
1215 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
1216 if (!I.hasStartLoc())
1219 if (!isNestedIn(
Loc, ParentFile)) {
1220 ParentCounter = I.getCounter();
1224 while (!
SM.isInFileID(
Loc, ParentFile)) {
1228 if (StartLocs.insert(
Loc).second) {
1230 SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(),
1231 I.getMCDCParams(),
Loc,
1232 getEndOfFileOrMacro(
Loc), I.isBranch());
1234 SourceRegions.emplace_back(I.getCounter(),
Loc,
1235 getEndOfFileOrMacro(
Loc));
1237 Loc = getIncludeOrExpansionLoc(
Loc);
1239 I.setStartLoc(getPreciseTokenLocEnd(
Loc));
1242 if (ParentCounter) {
1247 while (isNestedIn(
Loc, ParentFile)) {
1249 if (StartLocs.insert(FileStart).second) {
1250 SourceRegions.emplace_back(*ParentCounter, FileStart,
1251 getEndOfFileOrMacro(
Loc));
1252 assert(SpellingRegion(
SM, SourceRegions.back()).isInSourceOrder());
1254 Loc = getIncludeOrExpansionLoc(
Loc);
1258 MostRecentLocation = NewLoc;
1262 void extendRegion(
const Stmt *S) {
1263 SourceMappingRegion &Region =
getRegion();
1266 handleFileExit(StartLoc);
1267 if (!Region.hasStartLoc())
1268 Region.setStartLoc(StartLoc);
1272 void terminateRegion(
const Stmt *S) {
1274 SourceMappingRegion &Region =
getRegion();
1276 if (!Region.hasEndLoc())
1277 Region.setEndLoc(EndLoc);
1278 pushRegion(Counter::getZero());
1279 HasTerminateStmt =
true;
1283 std::optional<SourceRange> findGapAreaBetween(
SourceLocation AfterLoc,
1289 return std::nullopt;
1294 FileID FID =
SM.getFileID(AfterLoc);
1300 size_t StartDepth = locationDepth(AfterLoc);
1301 size_t EndDepth = locationDepth(BeforeLoc);
1302 while (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1303 bool UnnestStart = StartDepth >= EndDepth;
1304 bool UnnestEnd = EndDepth >= StartDepth;
1306 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1309 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1314 assert(
SM.isWrittenInSameFile(AfterLoc,
1315 getEndOfFileOrMacro(AfterLoc)));
1317 AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1319 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1324 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1328 return std::nullopt;
1329 if (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1330 !SpellingRegion(
SM, AfterLoc, BeforeLoc).isInSourceOrder())
1331 return std::nullopt;
1332 return {{AfterLoc, BeforeLoc}};
1338 if (StartLoc == EndLoc)
1340 assert(SpellingRegion(
SM, StartLoc, EndLoc).isInSourceOrder());
1341 handleFileExit(StartLoc);
1342 size_t Index = pushRegion(Count, StartLoc, EndLoc);
1344 handleFileExit(EndLoc);
1350 std::optional<SourceRange> findAreaStartingFromTo(
SourceLocation StartingLoc,
1354 FileID FID =
SM.getFileID(StartingLoc);
1360 size_t StartDepth = locationDepth(StartingLoc);
1361 size_t EndDepth = locationDepth(BeforeLoc);
1362 while (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc)) {
1363 bool UnnestStart = StartDepth >= EndDepth;
1364 bool UnnestEnd = EndDepth >= StartDepth;
1366 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1369 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1374 assert(
SM.isWrittenInSameFile(StartingLoc,
1375 getStartOfFileOrMacro(StartingLoc)));
1377 StartingLoc = getIncludeOrExpansionLoc(StartingLoc);
1378 assert(StartingLoc.
isValid());
1385 return std::nullopt;
1386 if (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc) ||
1387 !SpellingRegion(
SM, StartingLoc, BeforeLoc).isInSourceOrder())
1388 return std::nullopt;
1389 return {{StartingLoc, BeforeLoc}};
1393 const auto Skipped = findAreaStartingFromTo(StartLoc, BeforeLoc);
1398 const auto NewStartLoc = Skipped->getBegin();
1399 const auto EndLoc = Skipped->getEnd();
1401 if (NewStartLoc == EndLoc)
1403 assert(SpellingRegion(
SM, NewStartLoc, EndLoc).isInSourceOrder());
1404 handleFileExit(NewStartLoc);
1405 size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
1407 handleFileExit(EndLoc);
1412 struct BreakContinue {
1414 Counter ContinueCount;
1418 CounterCoverageMappingBuilder(
1420 llvm::DenseMap<const Stmt *, unsigned> &CounterMap,
1422 : CoverageMappingBuilder(CVM,
SM, LangOpts), CounterMap(CounterMap),
1423 MCDCState(MCDCState), MCDCBuilder(CVM.getCodeGenModule(), MCDCState) {}
1426 void write(llvm::raw_ostream &OS) {
1428 gatherFileIDs(VirtualFileMapping);
1429 SourceRegionFilter
Filter = emitExpansionRegions();
1430 emitSourceRegions(Filter);
1431 gatherSkippedRegions();
1433 if (MappingRegions.empty())
1436 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1441 void VisitStmt(
const Stmt *S) {
1442 if (S->getBeginLoc().isValid())
1444 const Stmt *LastStmt =
nullptr;
1445 bool SaveTerminateStmt = HasTerminateStmt;
1446 HasTerminateStmt =
false;
1447 GapRegionCounter = Counter::getZero();
1448 for (
const Stmt *Child : S->children())
1452 if (LastStmt && HasTerminateStmt) {
1453 auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1455 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1457 SaveTerminateStmt =
true;
1458 HasTerminateStmt =
false;
1463 if (SaveTerminateStmt)
1464 HasTerminateStmt =
true;
1465 handleFileExit(getEnd(S));
1468 void VisitDecl(
const Decl *
D) {
1474 SM.isInSystemHeader(
SM.getSpellingLoc(getStart(Body))))
1481 Counter BodyCounter = getRegionCounter(Body);
1483 if (
auto *Method = dyn_cast<CXXMethodDecl>(
D))
1485 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(
D)) {
1489 if (getStart(
Init).isValid() && getEnd(
Init).isValid())
1490 propagateCounts(BodyCounter,
Init);
1495 propagateCounts(BodyCounter, Body,
1497 assert(RegionStack.empty() &&
"Regions entered but never exited");
1502 if (S->getRetValue())
1503 Visit(S->getRetValue());
1509 Visit(S->getBody());
1514 if (S->getOperand())
1515 Visit(S->getOperand());
1520 Visit(
E->getOperand());
1525 if (
E->getSubExpr())
1526 Visit(
E->getSubExpr());
1530 void VisitGotoStmt(
const GotoStmt *S) { terminateRegion(S); }
1532 void VisitLabelStmt(
const LabelStmt *S) {
1533 Counter LabelCount = getRegionCounter(S);
1536 handleFileExit(Start);
1537 pushRegion(LabelCount, Start);
1538 Visit(S->getSubStmt());
1541 void VisitBreakStmt(
const BreakStmt *S) {
1542 assert(!BreakContinueStack.empty() &&
"break not in a loop or switch!");
1544 BreakContinueStack.back().BreakCount = addCounters(
1545 BreakContinueStack.back().BreakCount,
getRegion().getCounter());
1552 assert(!BreakContinueStack.empty() &&
"continue stmt not in a loop!");
1554 BreakContinueStack.back().ContinueCount = addCounters(
1555 BreakContinueStack.back().ContinueCount,
getRegion().getCounter());
1569 void VisitWhileStmt(
const WhileStmt *S) {
1572 Counter ParentCount =
getRegion().getCounter();
1574 ? getRegionCounter(S->getBody())
1575 : getRegionCounter(S);
1578 BreakContinueStack.push_back(BreakContinue());
1579 extendRegion(S->getBody());
1580 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1581 BreakContinue BC = BreakContinueStack.pop_back_val();
1583 bool BodyHasTerminateStmt = HasTerminateStmt;
1584 HasTerminateStmt =
false;
1589 ? getRegionCounter(S->getCond())
1590 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1591 propagateCounts(CondCount, S->getCond());
1592 adjustForOutOfOrderTraversal(getEnd(S));
1595 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1597 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1601 ? getRegionCounter(S)
1602 : addCounters(BC.BreakCount,
1603 subtractCounters(CondCount, BodyCount));
1605 if (OutCount != ParentCount) {
1606 pushRegion(OutCount);
1607 GapRegionCounter = OutCount;
1608 if (BodyHasTerminateStmt)
1609 HasTerminateStmt =
true;
1614 createBranchRegion(S->getCond(), BodyCount,
1615 subtractCounters(CondCount, BodyCount));
1618 void VisitDoStmt(
const DoStmt *S) {
1621 Counter ParentCount =
getRegion().getCounter();
1623 ? getRegionCounter(S->getBody())
1624 : getRegionCounter(S);
1626 BreakContinueStack.push_back(BreakContinue());
1627 extendRegion(S->getBody());
1629 Counter BackedgeCount;
1631 propagateCounts(BodyCount, S->getBody());
1634 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1636 BreakContinue BC = BreakContinueStack.pop_back_val();
1638 bool BodyHasTerminateStmt = HasTerminateStmt;
1639 HasTerminateStmt =
false;
1642 ? getRegionCounter(S->getCond())
1643 : addCounters(BackedgeCount, BC.ContinueCount);
1644 propagateCounts(CondCount, S->getCond());
1648 ? getRegionCounter(S)
1649 : addCounters(BC.BreakCount,
1650 subtractCounters(CondCount, BodyCount));
1651 if (OutCount != ParentCount) {
1652 pushRegion(OutCount);
1653 GapRegionCounter = OutCount;
1658 createBranchRegion(S->getCond(), BodyCount,
1659 subtractCounters(CondCount, BodyCount));
1661 if (BodyHasTerminateStmt)
1662 HasTerminateStmt =
true;
1665 void VisitForStmt(
const ForStmt *S) {
1668 Visit(S->getInit());
1670 Counter ParentCount =
getRegion().getCounter();
1672 ? getRegionCounter(S->getBody())
1673 : getRegionCounter(S);
1677 BreakContinueStack.emplace_back();
1680 BreakContinueStack.emplace_back();
1681 extendRegion(S->getBody());
1682 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1683 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1685 bool BodyHasTerminateStmt = HasTerminateStmt;
1686 HasTerminateStmt =
false;
1690 BreakContinue IncrementBC;
1691 if (
const Stmt *Inc = S->getInc()) {
1694 IncCount = getRegionCounter(S->getInc());
1696 IncCount = addCounters(BackedgeCount, BodyBC.ContinueCount);
1697 propagateCounts(IncCount, Inc);
1698 IncrementBC = BreakContinueStack.pop_back_val();
1704 ? getRegionCounter(S->getCond())
1706 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1707 IncrementBC.ContinueCount);
1709 if (
const Expr *Cond = S->getCond()) {
1710 propagateCounts(CondCount, Cond);
1711 adjustForOutOfOrderTraversal(getEnd(S));
1715 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1717 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1721 ? getRegionCounter(S)
1722 : addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1723 subtractCounters(CondCount, BodyCount));
1724 if (OutCount != ParentCount) {
1725 pushRegion(OutCount);
1726 GapRegionCounter = OutCount;
1727 if (BodyHasTerminateStmt)
1728 HasTerminateStmt =
true;
1733 createBranchRegion(S->getCond(), BodyCount,
1734 subtractCounters(CondCount, BodyCount));
1740 Visit(S->getInit());
1741 Visit(S->getLoopVarStmt());
1742 Visit(S->getRangeStmt());
1744 Counter ParentCount =
getRegion().getCounter();
1746 ? getRegionCounter(S->getBody())
1747 : getRegionCounter(S);
1749 BreakContinueStack.push_back(BreakContinue());
1750 extendRegion(S->getBody());
1751 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1752 BreakContinue BC = BreakContinueStack.pop_back_val();
1754 bool BodyHasTerminateStmt = HasTerminateStmt;
1755 HasTerminateStmt =
false;
1758 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1760 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1765 OutCount = getRegionCounter(S);
1767 LoopCount = addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1769 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1771 if (OutCount != ParentCount) {
1772 pushRegion(OutCount);
1773 GapRegionCounter = OutCount;
1774 if (BodyHasTerminateStmt)
1775 HasTerminateStmt =
true;
1780 createBranchRegion(S->getCond(), BodyCount,
1781 subtractCounters(LoopCount, BodyCount));
1786 Visit(S->getElement());
1788 Counter ParentCount =
getRegion().getCounter();
1789 Counter BodyCount = getRegionCounter(S);
1791 BreakContinueStack.push_back(BreakContinue());
1792 extendRegion(S->getBody());
1793 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1794 BreakContinue BC = BreakContinueStack.pop_back_val();
1797 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1799 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1802 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1804 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1805 if (OutCount != ParentCount) {
1806 pushRegion(OutCount);
1807 GapRegionCounter = OutCount;
1814 Visit(S->getInit());
1815 Visit(S->getCond());
1817 BreakContinueStack.push_back(BreakContinue());
1819 const Stmt *Body = S->getBody();
1821 if (
const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1822 if (!CS->body_empty()) {
1826 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1831 for (
size_t i = RegionStack.size(); i != Index; --i) {
1832 if (!RegionStack[i - 1].hasEndLoc())
1833 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1839 propagateCounts(Counter::getZero(), Body);
1840 BreakContinue BC = BreakContinueStack.pop_back_val();
1843 BreakContinueStack.back().ContinueCount = addCounters(
1844 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1846 Counter ParentCount =
getRegion().getCounter();
1847 Counter ExitCount = getRegionCounter(S);
1849 pushRegion(ExitCount);
1850 GapRegionCounter = ExitCount;
1854 MostRecentLocation = getStart(S);
1855 handleFileExit(ExitLoc);
1864 Counter CaseCountSum;
1865 bool HasDefaultCase =
false;
1866 const SwitchCase *Case = S->getSwitchCaseList();
1868 HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1869 auto CaseCount = createSwitchCaseRegion(Case, ParentCount);
1870 CaseCountSum = addCounters(CaseCountSum, CaseCount,
false);
1875 if (!HasDefaultCase) {
1880 addCounters(CaseCountSum, Counter::getZero(),
true);
1883 Counter SwitchFalse = subtractCounters(ParentCount, CaseCountSum);
1884 createBranchRegion(S->getCond(), CaseCountSum, SwitchFalse);
1893 ? getRegionCounter(S)
1894 : addCounters(
Parent.getCounter(), getRegionCounter(S));
1898 if (
Parent.hasStartLoc() &&
Parent.getBeginLoc() == getStart(S))
1899 Parent.setCounter(Count);
1901 pushRegion(Count, getStart(S));
1903 GapRegionCounter = Count;
1905 if (
const auto *CS = dyn_cast<CaseStmt>(S)) {
1906 Visit(CS->getLHS());
1907 if (
const Expr *RHS = CS->getRHS())
1910 Visit(S->getSubStmt());
1913 void coverIfConsteval(
const IfStmt *S) {
1914 assert(S->isConsteval());
1916 const auto *Then = S->getThen();
1917 const auto *Else = S->getElse();
1922 const Counter ParentCount =
getRegion().getCounter();
1926 if (S->isNegatedConsteval()) {
1928 markSkipped(S->getIfLoc(), getStart(Then));
1929 propagateCounts(ParentCount, Then);
1933 markSkipped(getEnd(Then), getEnd(Else));
1936 assert(S->isNonNegatedConsteval());
1938 markSkipped(S->getIfLoc(), Else ? getStart(Else) : getEnd(Then));
1941 propagateCounts(ParentCount, Else);
1945 void coverIfConstexpr(
const IfStmt *S) {
1946 assert(S->isConstexpr());
1958 const Counter ParentCount =
getRegion().getCounter();
1963 if (
const auto *
Init = S->getInit()) {
1964 const auto start = getStart(
Init);
1965 const auto end = getEnd(
Init);
1969 if (start.isValid() && end.isValid()) {
1970 markSkipped(startOfSkipped, start);
1971 propagateCounts(ParentCount,
Init);
1972 startOfSkipped = getEnd(
Init);
1976 const auto *Then = S->getThen();
1977 const auto *Else = S->getElse();
1981 markSkipped(startOfSkipped, getStart(Then));
1982 propagateCounts(ParentCount, Then);
1986 markSkipped(getEnd(Then), getEnd(Else));
1989 markSkipped(startOfSkipped, Else ? getStart(Else) : getEnd(Then));
1992 propagateCounts(ParentCount, Else);
1996 void VisitIfStmt(
const IfStmt *S) {
1999 if (S->isConsteval())
2000 return coverIfConsteval(S);
2001 else if (S->isConstexpr())
2002 return coverIfConstexpr(S);
2006 Visit(S->getInit());
2010 extendRegion(S->getCond());
2012 Counter ParentCount =
getRegion().getCounter();
2014 ? getRegionCounter(S->getThen())
2015 : getRegionCounter(S);
2019 propagateCounts(ParentCount, S->getCond());
2022 std::optional<SourceRange> Gap =
2023 findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
2025 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
2027 extendRegion(S->getThen());
2028 Counter OutCount = propagateCounts(ThenCount, S->getThen());
2032 ElseCount = subtractCounters(ParentCount, ThenCount);
2033 else if (S->getElse())
2034 ElseCount = getRegionCounter(S->getElse());
2036 if (
const Stmt *Else = S->getElse()) {
2037 bool ThenHasTerminateStmt = HasTerminateStmt;
2038 HasTerminateStmt =
false;
2040 std::optional<SourceRange> Gap =
2041 findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
2043 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
2046 Counter ElseOutCount = propagateCounts(ElseCount, Else);
2048 OutCount = addCounters(OutCount, ElseOutCount);
2050 if (ThenHasTerminateStmt)
2051 HasTerminateStmt =
true;
2053 OutCount = addCounters(OutCount, ElseCount);
2056 OutCount = getRegionCounter(S);
2058 if (OutCount != ParentCount) {
2059 pushRegion(OutCount);
2060 GapRegionCounter = OutCount;
2065 createBranchRegion(S->getCond(), ThenCount,
2066 subtractCounters(ParentCount, ThenCount));
2072 extendRegion(S->getTryBlock());
2074 Counter ParentCount =
getRegion().getCounter();
2075 propagateCounts(ParentCount, S->getTryBlock());
2077 for (
unsigned I = 0,
E = S->getNumHandlers(); I <
E; ++I)
2078 Visit(S->getHandler(I));
2080 Counter ExitCount = getRegionCounter(S);
2081 pushRegion(ExitCount);
2085 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
2091 Counter ParentCount =
getRegion().getCounter();
2093 ? getRegionCounter(
E->getTrueExpr())
2094 : getRegionCounter(
E);
2097 if (
const auto *BCO = dyn_cast<BinaryConditionalOperator>(
E)) {
2098 propagateCounts(ParentCount, BCO->getCommon());
2099 OutCount = TrueCount;
2101 propagateCounts(ParentCount,
E->getCond());
2104 findGapAreaBetween(
E->getQuestionLoc(), getStart(
E->getTrueExpr()));
2106 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
2108 extendRegion(
E->getTrueExpr());
2109 OutCount = propagateCounts(TrueCount,
E->getTrueExpr());
2112 extendRegion(
E->getFalseExpr());
2114 ? getRegionCounter(
E->getFalseExpr())
2115 : subtractCounters(ParentCount, TrueCount);
2117 Counter FalseOutCount = propagateCounts(FalseCount,
E->getFalseExpr());
2119 OutCount = getRegionCounter(
E);
2121 OutCount = addCounters(OutCount, FalseOutCount);
2123 if (OutCount != ParentCount) {
2124 pushRegion(OutCount);
2125 GapRegionCounter = OutCount;
2130 createBranchRegion(
E->getCond(), TrueCount,
2131 subtractCounters(ParentCount, TrueCount));
2134 void createOrCancelDecision(
const BinaryOperator *
E,
unsigned Since) {
2135 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(
E);
2141 for (
const auto &SR :
ArrayRef(SourceRegions).slice(Since)) {
2142 if (SR.isMCDCBranch()) {
2143 auto [
ID, Conds] = SR.getMCDCBranchParams();
2144 CondIDs[
ID] = Conds;
2149 mcdc::TVIdxBuilder Builder(CondIDs);
2150 unsigned NumTVs = Builder.NumTestVectors;
2152 assert(MaxTVs < mcdc::TVIdxBuilder::HardMaxTVs);
2154 if (NumTVs > MaxTVs) {
2156 cancelDecision(
E, Since, NumTVs, MaxTVs);
2164 std::move(Builder.Indices),
2167 auto DecisionParams = mcdc::DecisionParameters{
2173 createDecisionRegion(
E, DecisionParams);
2177 void cancelDecision(
const BinaryOperator *
E,
unsigned Since,
int NumTVs,
2182 "unsupported MC/DC boolean expression; "
2183 "number of test vectors (%0) exceeds max (%1). "
2184 "Expression will not be covered");
2189 assert(!SR.isMCDCDecision() &&
"Decision shouldn't be seen here");
2190 if (SR.isMCDCBranch())
2191 SR.resetMCDCParams();
2201 SM.isInSystemHeader(
SM.getSpellingLoc(
E->getOperatorLoc())) &&
2207 if (isExprInSystemHeader(
E)) {
2208 LeafExprSet.insert(
E);
2212 bool IsRootNode = MCDCBuilder.isIdle();
2214 unsigned SourceRegionsSince = SourceRegions.size();
2217 MCDCBuilder.pushAndAssignIDs(
E);
2219 extendRegion(
E->getLHS());
2220 propagateCounts(
getRegion().getCounter(),
E->getLHS());
2221 handleFileExit(getEnd(
E->getLHS()));
2224 const auto DecisionLHS = MCDCBuilder.pop();
2227 extendRegion(
E->getRHS());
2228 propagateCounts(getRegionCounter(
E),
E->getRHS());
2231 const auto DecisionRHS = MCDCBuilder.back();
2234 Counter RHSExecCnt = getRegionCounter(
E);
2237 Counter RHSTrueCnt = getRegionCounter(
E->getRHS());
2240 Counter ParentCnt =
getRegion().getCounter();
2244 createBranchRegion(
E->getLHS(), RHSExecCnt,
2245 subtractCounters(ParentCnt, RHSExecCnt), DecisionLHS);
2249 createBranchRegion(
E->getRHS(), RHSTrueCnt,
2250 subtractCounters(RHSExecCnt, RHSTrueCnt), DecisionRHS);
2254 createOrCancelDecision(
E, SourceRegionsSince);
2258 bool shouldVisitRHS(
const Expr *LHS) {
2259 bool LHSIsTrue =
false;
2260 bool LHSIsConst =
false;
2264 return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
2268 if (isExprInSystemHeader(
E)) {
2269 LeafExprSet.insert(
E);
2273 bool IsRootNode = MCDCBuilder.isIdle();
2275 unsigned SourceRegionsSince = SourceRegions.size();
2278 MCDCBuilder.pushAndAssignIDs(
E);
2280 extendRegion(
E->getLHS());
2281 Counter OutCount = propagateCounts(
getRegion().getCounter(),
E->getLHS());
2282 handleFileExit(getEnd(
E->getLHS()));
2285 const auto DecisionLHS = MCDCBuilder.pop();
2288 extendRegion(
E->getRHS());
2289 propagateCounts(getRegionCounter(
E),
E->getRHS());
2292 const auto DecisionRHS = MCDCBuilder.back();
2295 Counter RHSExecCnt = getRegionCounter(
E);
2298 Counter RHSFalseCnt = getRegionCounter(
E->getRHS());
2300 if (!shouldVisitRHS(
E->getLHS())) {
2301 GapRegionCounter = OutCount;
2305 Counter ParentCnt =
getRegion().getCounter();
2309 createBranchRegion(
E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
2310 RHSExecCnt, DecisionLHS);
2314 createBranchRegion(
E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
2315 RHSFalseCnt, DecisionRHS);
2319 createOrCancelDecision(
E, SourceRegionsSince);
2344static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
2347 OS << FunctionName <<
":\n";
2348 CounterMappingContext Ctx(Expressions);
2349 for (
const auto &R : Regions) {
2352 case CounterMappingRegion::CodeRegion:
2354 case CounterMappingRegion::ExpansionRegion:
2357 case CounterMappingRegion::SkippedRegion:
2360 case CounterMappingRegion::GapRegion:
2363 case CounterMappingRegion::BranchRegion:
2364 case CounterMappingRegion::MCDCBranchRegion:
2367 case CounterMappingRegion::MCDCDecisionRegion:
2372 OS <<
"File " << R.FileID <<
", " << R.LineStart <<
":" << R.ColumnStart
2373 <<
" -> " << R.LineEnd <<
":" << R.ColumnEnd <<
" = ";
2375 if (
const auto *DecisionParams =
2376 std::get_if<mcdc::DecisionParameters>(&R.MCDCParams)) {
2377 OS <<
"M:" << DecisionParams->BitmapIdx;
2378 OS <<
", C:" << DecisionParams->NumConditions;
2380 Ctx.dump(R.Count, OS);
2384 Ctx.dump(R.FalseCount, OS);
2388 if (
const auto *BranchParams =
2389 std::get_if<mcdc::BranchParameters>(&R.MCDCParams)) {
2390 OS <<
" [" << BranchParams->ID + 1 <<
","
2391 << BranchParams->Conds[
true] + 1;
2392 OS <<
"," << BranchParams->Conds[
false] + 1 <<
"] ";
2395 if (R.Kind == CounterMappingRegion::ExpansionRegion)
2396 OS <<
" (Expanded file = " << R.ExpandedFileID <<
")";
2403 : CGM(CGM), SourceInfo(SourceInfo) {}
2405std::string CoverageMappingModuleGen::getCurrentDirname() {
2410 llvm::sys::fs::current_path(CWD);
2411 return CWD.str().str();
2414std::string CoverageMappingModuleGen::normalizeFilename(StringRef
Filename) {
2416 llvm::sys::path::remove_dots(
Path,
true);
2421 for (
const auto &[From, To] :
2423 if (llvm::sys::path::replace_path_prefix(
Path, From, To))
2426 return Path.str().str();
2430 llvm::InstrProfSectKind SK) {
2431 return llvm::getInstrProfSectionName(
2435void CoverageMappingModuleGen::emitFunctionMappingRecord(
2436 const FunctionInfo &Info, uint64_t FilenamesRef) {
2440 std::string FuncRecordName =
"__covrec_" + llvm::utohexstr(Info.NameHash);
2447 FuncRecordName +=
"u";
2450 const uint64_t NameHash = Info.NameHash;
2451 const uint64_t FuncHash = Info.FuncHash;
2452 const std::string &CoverageMapping = Info.CoverageMapping;
2453#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2454 llvm::Type *FunctionRecordTypes[] = {
2455#include "llvm/ProfileData/InstrProfData.inc"
2457 auto *FunctionRecordTy =
2458 llvm::StructType::get(Ctx,
ArrayRef(FunctionRecordTypes),
2462#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2463 llvm::Constant *FunctionRecordVals[] = {
2464 #include "llvm/ProfileData/InstrProfData.inc"
2466 auto *FuncRecordConstant =
2467 llvm::ConstantStruct::get(FunctionRecordTy,
ArrayRef(FunctionRecordVals));
2470 auto *FuncRecord =
new llvm::GlobalVariable(
2471 CGM.
getModule(), FunctionRecordTy,
true,
2472 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2474 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2476 FuncRecord->setAlignment(llvm::Align(8));
2478 FuncRecord->setComdat(CGM.
getModule().getOrInsertComdat(FuncRecordName));
2485 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2486 const std::string &CoverageMapping,
bool IsUsed) {
2487 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2488 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2491 FunctionNames.push_back(NamePtr);
2500 std::vector<StringRef> Filenames;
2501 std::vector<CounterExpression> Expressions;
2502 std::vector<CounterMappingRegion> Regions;
2503 FilenameStrs.resize(FileEntries.size() + 1);
2504 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2505 for (
const auto &Entry : FileEntries) {
2506 auto I = Entry.second;
2507 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2510 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
2511 Expressions, Regions);
2514 dump(llvm::outs(), NameValue, Expressions, Regions);
2519 if (FunctionRecords.empty())
2522 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
2526 FilenameStrs.resize(FileEntries.size() + 1);
2528 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2529 for (
const auto &Entry : FileEntries) {
2530 auto I = Entry.second;
2531 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2534 std::string Filenames;
2536 llvm::raw_string_ostream OS(Filenames);
2537 CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
2539 auto *FilenamesVal =
2540 llvm::ConstantDataArray::getString(Ctx, Filenames,
false);
2541 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
2544 for (
const FunctionInfo &Info : FunctionRecords)
2545 emitFunctionMappingRecord(Info, FilenamesRef);
2547 const unsigned NRecords = 0;
2548 const size_t FilenamesSize = Filenames.size();
2549 const unsigned CoverageMappingSize = 0;
2550 llvm::Type *CovDataHeaderTypes[] = {
2551#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2552#include "llvm/ProfileData/InstrProfData.inc"
2554 auto CovDataHeaderTy =
2555 llvm::StructType::get(Ctx,
ArrayRef(CovDataHeaderTypes));
2556 llvm::Constant *CovDataHeaderVals[] = {
2557#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2558#include "llvm/ProfileData/InstrProfData.inc"
2560 auto CovDataHeaderVal =
2561 llvm::ConstantStruct::get(CovDataHeaderTy,
ArrayRef(CovDataHeaderVals));
2564 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2565 auto CovDataTy = llvm::StructType::get(Ctx,
ArrayRef(CovDataTypes));
2566 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2567 auto CovDataVal = llvm::ConstantStruct::get(CovDataTy,
ArrayRef(TUDataVals));
2568 auto CovData =
new llvm::GlobalVariable(
2569 CGM.
getModule(), CovDataTy,
true, llvm::GlobalValue::PrivateLinkage,
2570 CovDataVal, llvm::getCoverageMappingVarName());
2573 CovData->setAlignment(llvm::Align(8));
2578 if (!FunctionNames.empty()) {
2579 auto NamesArrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx),
2580 FunctionNames.size());
2581 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
2584 new llvm::GlobalVariable(CGM.
getModule(), NamesArrTy,
true,
2585 llvm::GlobalValue::InternalLinkage, NamesArrVal,
2586 llvm::getCoverageUnusedNamesVarName());
2591 return FileEntries.try_emplace(
File, FileEntries.size() + 1).first->second;
2595 llvm::raw_ostream &OS) {
2596 assert(CounterMap && MCDCState);
2597 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCState,
SM,
2599 Walker.VisitDecl(
D);
2604 llvm::raw_ostream &OS) {
2605 EmptyCoverageMappingBuilder Walker(CVM,
SM, LangOpts);
2606 Walker.VisitDecl(
D);
Defines the Diagnostic-related interfaces.
static const MemRegion * getRegion(const CallEvent &Call, const MutexDescriptor &Descriptor, bool IsLock)
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)
llvm::DenseSet< const void * > Visited
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
const TargetInfo & getTargetInfo() const
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
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".
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]).
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
DiagnosticsEngine & getDiags() 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...
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 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 getEndLoc() const LLVM_READONLY
SourceLocation getBeginLoc() const LLVM_READONLY
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)
cl::opt< bool > SystemHeadersCoverage
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.