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);
51 "system-headers-coverage",
52 cl::desc(
"Enable collecting coverage from system headers"), cl::init(
false),
57using namespace CodeGen;
72 if (Tok.
getKind() != clang::tok::eod)
82 PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
83 SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
87 SkippedRanges.push_back({
Range, RangeKind, PrevTokLoc});
104 if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
105 SkippedRanges.back().NextTokLoc =
Loc;
110class SourceMappingRegion {
115 std::optional<Counter> FalseCount;
118 mcdc::Parameters MCDCParams;
121 std::optional<SourceLocation> LocStart;
124 std::optional<SourceLocation> LocEnd;
135 SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart,
136 std::optional<SourceLocation> LocEnd,
137 bool GapRegion =
false)
138 : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
139 SkippedRegion(
false) {}
141 SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount,
142 mcdc::Parameters MCDCParams,
143 std::optional<SourceLocation> LocStart,
144 std::optional<SourceLocation> LocEnd,
145 bool GapRegion =
false)
146 : Count(Count), FalseCount(FalseCount), MCDCParams(MCDCParams),
147 LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
148 SkippedRegion(
false) {}
150 SourceMappingRegion(mcdc::Parameters MCDCParams,
151 std::optional<SourceLocation> LocStart,
152 std::optional<SourceLocation> LocEnd)
153 : MCDCParams(MCDCParams), LocStart(LocStart), LocEnd(LocEnd),
156 const Counter &getCounter()
const {
return Count; }
158 const Counter &getFalseCounter()
const {
159 assert(FalseCount &&
"Region has no alternate counter");
163 void setCounter(Counter
C) { Count =
C; }
165 bool hasStartLoc()
const {
return LocStart.has_value(); }
170 assert(LocStart &&
"Region has no start location");
174 bool hasEndLoc()
const {
return LocEnd.has_value(); }
177 assert(
Loc.
isValid() &&
"Setting an invalid end location");
182 assert(LocEnd &&
"Region has no end location");
186 bool isGap()
const {
return GapRegion; }
188 void setGap(
bool Gap) { GapRegion = Gap; }
190 bool isSkipped()
const {
return SkippedRegion; }
192 void setSkipped(
bool Skipped) { SkippedRegion = Skipped; }
194 bool isBranch()
const {
return FalseCount.has_value(); }
196 bool isMCDCBranch()
const {
197 return std::holds_alternative<mcdc::BranchParameters>(MCDCParams);
200 const auto &getMCDCBranchParams()
const {
201 return mcdc::getParams<const mcdc::BranchParameters>(MCDCParams);
204 bool isMCDCDecision()
const {
205 return std::holds_alternative<mcdc::DecisionParameters>(MCDCParams);
208 const auto &getMCDCDecisionParams()
const {
209 return mcdc::getParams<const mcdc::DecisionParameters>(MCDCParams);
212 const mcdc::Parameters &getMCDCParams()
const {
return MCDCParams; }
214 void resetMCDCParams() { MCDCParams = mcdc::Parameters(); }
218struct SpellingRegion {
223 unsigned ColumnStart;
233 LineStart =
SM.getSpellingLineNumber(LocStart);
234 ColumnStart =
SM.getSpellingColumnNumber(LocStart);
235 LineEnd =
SM.getSpellingLineNumber(LocEnd);
236 ColumnEnd =
SM.getSpellingColumnNumber(LocEnd);
240 : SpellingRegion(
SM, R.getBeginLoc(), R.getEndLoc()) {}
244 bool isInSourceOrder()
const {
245 return (LineStart < LineEnd) ||
246 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
252class CoverageMappingBuilder {
260 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
267 std::vector<SourceMappingRegion> SourceRegions;
274 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
279 : CVM(CVM),
SM(
SM), LangOpts(LangOpts) {}
294 return SM.getLocForStartOfFile(
SM.getFileID(
Loc));
301 SM.getFileOffset(
Loc));
302 return SM.getLocForEndOfFile(
SM.getFileID(
Loc));
312 std::pair<SourceLocation, std::optional<SourceLocation>>
314 std::optional<SourceLocation> EndLoc = std::nullopt;
316 SM.isWrittenInScratchSpace(
SM.getSpellingLoc(
Loc))) {
317 auto ExpansionRange =
SM.getImmediateExpansionRange(
Loc);
318 Loc = ExpansionRange.getBegin();
319 EndLoc = ExpansionRange.getEnd();
321 return std::make_pair(
Loc, EndLoc);
328 bool AcceptScratch =
true) {
330 return SM.getIncludeLoc(
SM.getFileID(
Loc));
331 Loc =
SM.getImmediateExpansionRange(
Loc).getBegin();
334 return getNonScratchExpansionLoc(
Loc).first;
339 return SM.getBufferName(
SM.getSpellingLoc(
Loc)) ==
"<built-in>";
345 Loc = getIncludeOrExpansionLoc(
Loc);
355 while (
SM.isMacroArgExpansion(
Loc) || isInBuiltin(
Loc))
356 Loc =
SM.getImmediateExpansionRange(
Loc).getBegin();
363 while (
SM.isMacroArgExpansion(
Loc) || isInBuiltin(
Loc))
364 Loc =
SM.getImmediateExpansionRange(
Loc).getBegin();
365 return getPreciseTokenLocEnd(
Loc);
374 FileIDMapping.clear();
376 llvm::SmallSet<FileID, 8>
Visited;
378 for (
auto &Region : SourceRegions) {
382 auto NonScratchExpansionLoc = getNonScratchExpansionLoc(
Loc);
383 auto EndLoc = NonScratchExpansionLoc.second;
384 if (EndLoc.has_value()) {
385 Loc = NonScratchExpansionLoc.first;
386 Region.setStartLoc(
Loc);
387 Region.setEndLoc(EndLoc.value());
392 auto BeginLoc =
SM.getSpellingLoc(
Loc);
393 auto EndLoc =
SM.getSpellingLoc(Region.getEndLoc());
394 if (
SM.isWrittenInSameFile(BeginLoc, EndLoc)) {
396 Region.setStartLoc(
Loc);
397 Region.setEndLoc(
SM.getFileLoc(Region.getEndLoc()));
406 !
SM.isInSystemHeader(
SM.getSpellingLoc(
Loc)));
412 FileLocs.push_back(std::make_pair(
Loc, Depth));
414 llvm::stable_sort(FileLocs, llvm::less_second());
416 for (
const auto &FL : FileLocs) {
418 FileID SpellingFile =
SM.getDecomposedSpellingLoc(
Loc).first;
419 auto Entry =
SM.getFileEntryRefForID(SpellingFile);
423 FileIDMapping[
SM.getFileID(
Loc)] = std::make_pair(Mapping.size(),
Loc);
424 Mapping.push_back(CVM.
getFileID(*Entry));
432 auto Mapping = FileIDMapping.find(
SM.getFileID(
Loc));
433 if (Mapping != FileIDMapping.end())
434 return Mapping->second.first;
448 SpellingRegion SR{
SM, LocStart, LocEnd};
450 if (PrevTokLoc.
isValid() &&
SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
451 SR.LineStart ==
SM.getSpellingLineNumber(PrevTokLoc))
453 if (NextTokLoc.
isValid() &&
SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
454 SR.LineEnd ==
SM.getSpellingLineNumber(NextTokLoc)) {
458 if (SR.isInSourceOrder())
465 void gatherSkippedRegions() {
469 FileLineRanges.resize(
470 FileIDMapping.size(),
471 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
472 for (
const auto &R : MappingRegions) {
473 FileLineRanges[R.FileID].first =
474 std::min(FileLineRanges[R.FileID].first, R.LineStart);
475 FileLineRanges[R.FileID].second =
476 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
480 for (
auto &I : SkippedRanges) {
484 assert(
SM.isWrittenInSameFile(LocStart, LocEnd) &&
485 "region spans multiple files");
487 auto CovFileID = getCoverageFileID(LocStart);
490 std::optional<SpellingRegion> SR;
492 SR = adjustSkippedRange(
SM, LocStart, LocEnd, I.PrevTokLoc,
494 else if (I.isPPIfElse() || I.isEmptyLine())
495 SR = {
SM, LocStart, LocEnd};
499 auto Region = CounterMappingRegion::makeSkipped(
500 *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
504 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
505 Region.LineEnd <= FileLineRanges[*CovFileID].second)
506 MappingRegions.push_back(Region);
512 void emitSourceRegions(
const SourceRegionFilter &Filter) {
513 for (
const auto &Region : SourceRegions) {
514 assert(Region.hasEndLoc() &&
"incomplete region");
517 assert(
SM.getFileID(LocStart).isValid() &&
"region in invalid file");
522 SM.isInSystemHeader(
SM.getSpellingLoc(LocStart))) {
523 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
524 "Don't suppress the condition in system headers");
528 auto CovFileID = getCoverageFileID(LocStart);
531 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
532 "Don't suppress the condition in non-file regions");
537 assert(
SM.isWrittenInSameFile(LocStart, LocEnd) &&
538 "region spans multiple files");
544 if (
Filter.count(std::make_pair(LocStart, LocEnd))) {
545 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
546 "Don't suppress the condition");
551 SpellingRegion SR{
SM, LocStart, LocEnd};
552 assert(SR.isInSourceOrder() &&
"region start and end out of order");
554 if (Region.isGap()) {
555 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
556 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
557 SR.LineEnd, SR.ColumnEnd));
558 }
else if (Region.isSkipped()) {
559 MappingRegions.push_back(CounterMappingRegion::makeSkipped(
560 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd,
562 }
else if (Region.isBranch()) {
563 MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
564 Region.getCounter(), Region.getFalseCounter(), *CovFileID,
565 SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd,
566 Region.getMCDCParams()));
567 }
else if (Region.isMCDCDecision()) {
568 MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion(
569 Region.getMCDCDecisionParams(), *CovFileID, SR.LineStart,
570 SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
572 MappingRegions.push_back(CounterMappingRegion::makeRegion(
573 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
574 SR.LineEnd, SR.ColumnEnd));
580 SourceRegionFilter emitExpansionRegions() {
581 SourceRegionFilter
Filter;
582 for (
const auto &FM : FileIDMapping) {
584 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc,
false);
588 auto ParentFileID = getCoverageFileID(ParentLoc);
591 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
592 assert(ExpandedFileID &&
"expansion in uncovered file");
595 assert(
SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
596 "region spans multiple files");
597 Filter.insert(std::make_pair(ParentLoc, LocEnd));
599 SpellingRegion SR{
SM, ParentLoc, LocEnd};
600 assert(SR.isInSourceOrder() &&
"region start and end out of order");
601 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
602 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
603 SR.LineEnd, SR.ColumnEnd));
611struct EmptyCoverageMappingBuilder :
public CoverageMappingBuilder {
614 : CoverageMappingBuilder(CVM,
SM, LangOpts) {}
616 void VisitDecl(
const Decl *
D) {
622 if (!
SM.isWrittenInSameFile(Start, End)) {
625 FileID StartFileID =
SM.getFileID(Start);
626 FileID EndFileID =
SM.getFileID(End);
627 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
628 Start = getIncludeOrExpansionLoc(Start);
630 "Declaration start location not nested within a known region");
631 StartFileID =
SM.getFileID(Start);
633 while (StartFileID != EndFileID) {
634 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
635 assert(End.isValid() &&
636 "Declaration end location not nested within a known region");
637 EndFileID =
SM.getFileID(End);
640 SourceRegions.emplace_back(Counter(), Start, End);
644 void write(llvm::raw_ostream &OS) {
646 gatherFileIDs(FileIDMapping);
647 emitSourceRegions(SourceRegionFilter());
649 if (MappingRegions.empty())
652 CoverageMappingWriter Writer(FileIDMapping, std::nullopt, MappingRegions);
665struct MCDCCoverageBuilder {
759 const Stmt *DecisionStmt =
nullptr;
760 mcdc::ConditionID NextID = 0;
761 bool NotMapped =
false;
765 static constexpr mcdc::ConditionIDs DecisionStackSentinel{-1, -1};
769 return E->getOpcode() == BO_LAnd;
774 : CGM(CGM), DecisionStack(1, DecisionStackSentinel),
775 MCDCState(MCDCState) {}
780 bool isIdle()
const {
return (NextID == 0 && !NotMapped); }
785 bool isBuilding()
const {
return (NextID > 0); }
788 void setCondID(
const Expr *Cond, mcdc::ConditionID
ID) {
794 mcdc::ConditionID getCondID(
const Expr *Cond)
const {
795 auto I = MCDCState.
BranchByStmt.find(CodeGenFunction::stripCond(Cond));
803 const mcdc::ConditionIDs &back()
const {
return DecisionStack.back(); }
826 const mcdc::ConditionIDs &ParentDecision = DecisionStack.back();
831 if (MCDCState.
BranchByStmt.contains(CodeGenFunction::stripCond(
E)))
832 setCondID(
E->getLHS(), getCondID(
E));
834 setCondID(
E->getLHS(), NextID++);
837 mcdc::ConditionID RHSid = NextID++;
838 setCondID(
E->getRHS(), RHSid);
842 DecisionStack.push_back({ParentDecision[
false], RHSid});
844 DecisionStack.push_back({RHSid, ParentDecision[
true]});
848 mcdc::ConditionIDs pop() {
850 return DecisionStackSentinel;
852 assert(DecisionStack.size() > 1);
853 return DecisionStack.pop_back_val();
863 assert(DecisionStack.size() == 1);
873 unsigned TotalConds = NextID;
884struct CounterCoverageMappingBuilder
885 :
public CoverageMappingBuilder,
888 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
897 llvm::DenseSet<const Stmt *> LeafExprSet;
900 MCDCCoverageBuilder MCDCBuilder;
902 CounterExpressionBuilder Builder;
911 bool HasTerminateStmt =
false;
914 Counter GapRegionCounter;
917 Counter subtractCounters(Counter LHS, Counter RHS,
bool Simplify =
true) {
919 "cannot add counters when single byte coverage mode is enabled");
920 return Builder.subtract(LHS, RHS, Simplify);
924 Counter addCounters(Counter LHS, Counter RHS,
bool Simplify =
true) {
926 "cannot add counters when single byte coverage mode is enabled");
927 return Builder.add(LHS, RHS, Simplify);
930 Counter addCounters(Counter C1, Counter C2, Counter C3,
931 bool Simplify =
true) {
933 "cannot add counters when single byte coverage mode is enabled");
934 return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
940 Counter getRegionCounter(
const Stmt *S) {
941 return Counter::getCounter(CounterMap[S]);
948 size_t pushRegion(Counter Count,
949 std::optional<SourceLocation> StartLoc = std::nullopt,
950 std::optional<SourceLocation> EndLoc = std::nullopt,
951 std::optional<Counter> FalseCount = std::nullopt,
952 const mcdc::Parameters &BranchParams = std::monostate()) {
954 if (StartLoc && !FalseCount) {
955 MostRecentLocation = *StartLoc;
960 assert((!StartLoc || StartLoc->isValid()) &&
"Start location is not valid");
961 assert((!EndLoc || EndLoc->isValid()) &&
"End location is not valid");
967 if (StartLoc && StartLoc->isInvalid())
968 StartLoc = std::nullopt;
969 if (EndLoc && EndLoc->isInvalid())
970 EndLoc = std::nullopt;
971 RegionStack.emplace_back(Count, FalseCount, BranchParams, StartLoc, EndLoc);
973 return RegionStack.size() - 1;
976 size_t pushRegion(
const mcdc::DecisionParameters &DecisionParams,
977 std::optional<SourceLocation> StartLoc = std::nullopt,
978 std::optional<SourceLocation> EndLoc = std::nullopt) {
980 RegionStack.emplace_back(DecisionParams, StartLoc, EndLoc);
982 return RegionStack.size() - 1;
988 Loc = getIncludeOrExpansionLoc(
Loc);
998 void popRegions(
size_t ParentIndex) {
999 assert(RegionStack.size() >= ParentIndex &&
"parent not in stack");
1000 while (RegionStack.size() > ParentIndex) {
1001 SourceMappingRegion &Region = RegionStack.back();
1002 if (Region.hasStartLoc() &&
1003 (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
1006 ? Region.getEndLoc()
1007 : RegionStack[ParentIndex].getEndLoc();
1008 bool isBranch = Region.isBranch();
1009 size_t StartDepth = locationDepth(StartLoc);
1010 size_t EndDepth = locationDepth(EndLoc);
1011 while (!
SM.isWrittenInSameFile(StartLoc, EndLoc)) {
1012 bool UnnestStart = StartDepth >= EndDepth;
1013 bool UnnestEnd = EndDepth >= StartDepth;
1022 assert(
SM.isWrittenInSameFile(NestedLoc, EndLoc));
1024 if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
1025 SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
1028 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
1030 llvm::report_fatal_error(
1031 "File exit not handled before popRegions");
1042 assert(
SM.isWrittenInSameFile(StartLoc, NestedLoc));
1044 if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
1045 SourceRegions.emplace_back(Region.getCounter(), StartLoc,
1048 StartLoc = getIncludeOrExpansionLoc(StartLoc);
1050 llvm::report_fatal_error(
1051 "File exit not handled before popRegions");
1055 Region.setStartLoc(StartLoc);
1056 Region.setEndLoc(EndLoc);
1059 MostRecentLocation = EndLoc;
1062 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
1063 EndLoc == getEndOfFileOrMacro(EndLoc))
1064 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
1067 assert(
SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
1068 assert(SpellingRegion(
SM, Region).isInSourceOrder());
1069 SourceRegions.push_back(Region);
1071 RegionStack.pop_back();
1077 assert(!RegionStack.empty() &&
"statement has no region");
1078 return RegionStack.back();
1083 Counter propagateCounts(Counter TopCount,
const Stmt *S,
1084 bool VisitChildren =
true) {
1087 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
1090 Counter ExitCount =
getRegion().getCounter();
1095 if (
SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
1096 MostRecentLocation = EndLoc;
1102 bool ConditionFoldsToBool(
const Expr *Cond) {
1111 void createBranchRegion(
const Expr *
C, Counter TrueCnt, Counter FalseCnt,
1112 const mcdc::ConditionIDs &Conds = {}) {
1123 if (CodeGenFunction::isInstrumentedCondition(
C) ||
1124 LeafExprSet.count(CodeGenFunction::stripCond(
C))) {
1125 mcdc::Parameters BranchParams;
1126 mcdc::ConditionID
ID = MCDCBuilder.getCondID(
C);
1128 BranchParams = mcdc::BranchParameters{
ID, Conds};
1136 if (ConditionFoldsToBool(
C))
1137 popRegions(pushRegion(Counter::getZero(), getStart(
C), getEnd(
C),
1138 Counter::getZero(), BranchParams));
1141 popRegions(pushRegion(TrueCnt, getStart(
C), getEnd(
C), FalseCnt,
1149 void createDecisionRegion(
const Expr *
C,
1150 const mcdc::DecisionParameters &DecisionParams) {
1151 popRegions(pushRegion(DecisionParams, getStart(
C), getEnd(
C)));
1156 void createSwitchCaseRegion(
const SwitchCase *SC, Counter TrueCnt,
1161 popRegions(pushRegion(TrueCnt, getStart(SC), SC->
getColonLoc(), FalseCnt));
1167 bool isBranch =
false) {
1168 return llvm::any_of(
1169 llvm::reverse(SourceRegions), [&](
const SourceMappingRegion &Region) {
1170 return Region.getBeginLoc() == StartLoc &&
1171 Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
1179 MostRecentLocation = EndLoc;
1186 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
1187 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
1188 MostRecentLocation,
getRegion().isBranch()))
1189 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
1199 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
1205 FileID ParentFile =
SM.getFileID(LCA);
1206 while (!isNestedIn(MostRecentLocation, ParentFile)) {
1207 LCA = getIncludeOrExpansionLoc(LCA);
1208 if (LCA.
isInvalid() ||
SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
1211 MostRecentLocation = NewLoc;
1214 ParentFile =
SM.getFileID(LCA);
1217 llvm::SmallSet<SourceLocation, 8> StartLocs;
1218 std::optional<Counter> ParentCounter;
1219 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
1220 if (!I.hasStartLoc())
1223 if (!isNestedIn(
Loc, ParentFile)) {
1224 ParentCounter = I.getCounter();
1228 while (!
SM.isInFileID(
Loc, ParentFile)) {
1232 if (StartLocs.insert(
Loc).second) {
1234 SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(),
1235 I.getMCDCParams(),
Loc,
1236 getEndOfFileOrMacro(
Loc), I.isBranch());
1238 SourceRegions.emplace_back(I.getCounter(),
Loc,
1239 getEndOfFileOrMacro(
Loc));
1241 Loc = getIncludeOrExpansionLoc(
Loc);
1243 I.setStartLoc(getPreciseTokenLocEnd(
Loc));
1246 if (ParentCounter) {
1251 while (isNestedIn(
Loc, ParentFile)) {
1253 if (StartLocs.insert(FileStart).second) {
1254 SourceRegions.emplace_back(*ParentCounter, FileStart,
1255 getEndOfFileOrMacro(
Loc));
1256 assert(SpellingRegion(
SM, SourceRegions.back()).isInSourceOrder());
1258 Loc = getIncludeOrExpansionLoc(
Loc);
1262 MostRecentLocation = NewLoc;
1266 void extendRegion(
const Stmt *S) {
1267 SourceMappingRegion &Region =
getRegion();
1270 handleFileExit(StartLoc);
1271 if (!Region.hasStartLoc())
1272 Region.setStartLoc(StartLoc);
1276 void terminateRegion(
const Stmt *S) {
1278 SourceMappingRegion &Region =
getRegion();
1280 if (!Region.hasEndLoc())
1281 Region.setEndLoc(EndLoc);
1282 pushRegion(Counter::getZero());
1283 HasTerminateStmt =
true;
1287 std::optional<SourceRange> findGapAreaBetween(
SourceLocation AfterLoc,
1293 return std::nullopt;
1298 FileID FID =
SM.getFileID(AfterLoc);
1304 size_t StartDepth = locationDepth(AfterLoc);
1305 size_t EndDepth = locationDepth(BeforeLoc);
1306 while (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1307 bool UnnestStart = StartDepth >= EndDepth;
1308 bool UnnestEnd = EndDepth >= StartDepth;
1310 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1313 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1318 assert(
SM.isWrittenInSameFile(AfterLoc,
1319 getEndOfFileOrMacro(AfterLoc)));
1321 AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1323 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1328 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1332 return std::nullopt;
1333 if (!
SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1334 !SpellingRegion(
SM, AfterLoc, BeforeLoc).isInSourceOrder())
1335 return std::nullopt;
1336 return {{AfterLoc, BeforeLoc}};
1342 if (StartLoc == EndLoc)
1344 assert(SpellingRegion(
SM, StartLoc, EndLoc).isInSourceOrder());
1345 handleFileExit(StartLoc);
1346 size_t Index = pushRegion(Count, StartLoc, EndLoc);
1348 handleFileExit(EndLoc);
1354 std::optional<SourceRange> findAreaStartingFromTo(
SourceLocation StartingLoc,
1358 FileID FID =
SM.getFileID(StartingLoc);
1364 size_t StartDepth = locationDepth(StartingLoc);
1365 size_t EndDepth = locationDepth(BeforeLoc);
1366 while (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc)) {
1367 bool UnnestStart = StartDepth >= EndDepth;
1368 bool UnnestEnd = EndDepth >= StartDepth;
1370 assert(
SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1373 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1378 assert(
SM.isWrittenInSameFile(StartingLoc,
1379 getStartOfFileOrMacro(StartingLoc)));
1381 StartingLoc = getIncludeOrExpansionLoc(StartingLoc);
1382 assert(StartingLoc.
isValid());
1389 return std::nullopt;
1390 if (!
SM.isWrittenInSameFile(StartingLoc, BeforeLoc) ||
1391 !SpellingRegion(
SM, StartingLoc, BeforeLoc).isInSourceOrder())
1392 return std::nullopt;
1393 return {{StartingLoc, BeforeLoc}};
1397 const auto Skipped = findAreaStartingFromTo(StartLoc, BeforeLoc);
1402 const auto NewStartLoc = Skipped->getBegin();
1403 const auto EndLoc = Skipped->getEnd();
1405 if (NewStartLoc == EndLoc)
1407 assert(SpellingRegion(
SM, NewStartLoc, EndLoc).isInSourceOrder());
1408 handleFileExit(NewStartLoc);
1409 size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
1411 handleFileExit(EndLoc);
1416 struct BreakContinue {
1418 Counter ContinueCount;
1422 CounterCoverageMappingBuilder(
1424 llvm::DenseMap<const Stmt *, unsigned> &CounterMap,
1426 : CoverageMappingBuilder(CVM,
SM, LangOpts), CounterMap(CounterMap),
1427 MCDCState(MCDCState), MCDCBuilder(CVM.getCodeGenModule(), MCDCState) {}
1430 void write(llvm::raw_ostream &OS) {
1432 gatherFileIDs(VirtualFileMapping);
1433 SourceRegionFilter
Filter = emitExpansionRegions();
1434 emitSourceRegions(Filter);
1435 gatherSkippedRegions();
1437 if (MappingRegions.empty())
1440 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1445 void VisitStmt(
const Stmt *S) {
1446 if (S->getBeginLoc().isValid())
1448 const Stmt *LastStmt =
nullptr;
1449 bool SaveTerminateStmt = HasTerminateStmt;
1450 HasTerminateStmt =
false;
1451 GapRegionCounter = Counter::getZero();
1452 for (
const Stmt *Child : S->children())
1456 if (LastStmt && HasTerminateStmt) {
1457 auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1459 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1461 SaveTerminateStmt =
true;
1462 HasTerminateStmt =
false;
1467 if (SaveTerminateStmt)
1468 HasTerminateStmt =
true;
1469 handleFileExit(getEnd(S));
1472 void VisitDecl(
const Decl *
D) {
1478 SM.isInSystemHeader(
SM.getSpellingLoc(getStart(Body))))
1485 Counter BodyCounter = getRegionCounter(Body);
1487 if (
auto *Method = dyn_cast<CXXMethodDecl>(
D))
1489 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(
D)) {
1493 if (getStart(
Init).isValid() && getEnd(
Init).isValid())
1494 propagateCounts(BodyCounter,
Init);
1499 propagateCounts(BodyCounter, Body,
1501 assert(RegionStack.empty() &&
"Regions entered but never exited");
1506 if (S->getRetValue())
1507 Visit(S->getRetValue());
1513 Visit(S->getBody());
1518 if (S->getOperand())
1519 Visit(S->getOperand());
1524 Visit(
E->getOperand());
1529 if (
E->getSubExpr())
1530 Visit(
E->getSubExpr());
1534 void VisitGotoStmt(
const GotoStmt *S) { terminateRegion(S); }
1536 void VisitLabelStmt(
const LabelStmt *S) {
1537 Counter LabelCount = getRegionCounter(S);
1540 handleFileExit(Start);
1541 pushRegion(LabelCount, Start);
1542 Visit(S->getSubStmt());
1545 void VisitBreakStmt(
const BreakStmt *S) {
1546 assert(!BreakContinueStack.empty() &&
"break not in a loop or switch!");
1548 BreakContinueStack.back().BreakCount = addCounters(
1549 BreakContinueStack.back().BreakCount,
getRegion().getCounter());
1556 assert(!BreakContinueStack.empty() &&
"continue stmt not in a loop!");
1558 BreakContinueStack.back().ContinueCount = addCounters(
1559 BreakContinueStack.back().ContinueCount,
getRegion().getCounter());
1573 void VisitWhileStmt(
const WhileStmt *S) {
1576 Counter ParentCount =
getRegion().getCounter();
1578 ? getRegionCounter(S->getBody())
1579 : getRegionCounter(S);
1582 BreakContinueStack.push_back(BreakContinue());
1583 extendRegion(S->getBody());
1584 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1585 BreakContinue BC = BreakContinueStack.pop_back_val();
1587 bool BodyHasTerminateStmt = HasTerminateStmt;
1588 HasTerminateStmt =
false;
1593 ? getRegionCounter(S->getCond())
1594 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1595 propagateCounts(CondCount, S->getCond());
1596 adjustForOutOfOrderTraversal(getEnd(S));
1599 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1601 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1605 ? getRegionCounter(S)
1606 : addCounters(BC.BreakCount,
1607 subtractCounters(CondCount, BodyCount));
1609 if (OutCount != ParentCount) {
1610 pushRegion(OutCount);
1611 GapRegionCounter = OutCount;
1612 if (BodyHasTerminateStmt)
1613 HasTerminateStmt =
true;
1618 createBranchRegion(S->getCond(), BodyCount,
1619 subtractCounters(CondCount, BodyCount));
1622 void VisitDoStmt(
const DoStmt *S) {
1625 Counter ParentCount =
getRegion().getCounter();
1627 ? getRegionCounter(S->getBody())
1628 : getRegionCounter(S);
1630 BreakContinueStack.push_back(BreakContinue());
1631 extendRegion(S->getBody());
1633 Counter BackedgeCount;
1635 propagateCounts(BodyCount, S->getBody());
1638 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1640 BreakContinue BC = BreakContinueStack.pop_back_val();
1642 bool BodyHasTerminateStmt = HasTerminateStmt;
1643 HasTerminateStmt =
false;
1646 ? getRegionCounter(S->getCond())
1647 : addCounters(BackedgeCount, BC.ContinueCount);
1648 propagateCounts(CondCount, S->getCond());
1652 ? getRegionCounter(S)
1653 : addCounters(BC.BreakCount,
1654 subtractCounters(CondCount, BodyCount));
1655 if (OutCount != ParentCount) {
1656 pushRegion(OutCount);
1657 GapRegionCounter = OutCount;
1662 createBranchRegion(S->getCond(), BodyCount,
1663 subtractCounters(CondCount, BodyCount));
1665 if (BodyHasTerminateStmt)
1666 HasTerminateStmt =
true;
1669 void VisitForStmt(
const ForStmt *S) {
1672 Visit(S->getInit());
1674 Counter ParentCount =
getRegion().getCounter();
1676 ? getRegionCounter(S->getBody())
1677 : getRegionCounter(S);
1681 BreakContinueStack.emplace_back();
1684 BreakContinueStack.emplace_back();
1685 extendRegion(S->getBody());
1686 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1687 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1689 bool BodyHasTerminateStmt = HasTerminateStmt;
1690 HasTerminateStmt =
false;
1694 BreakContinue IncrementBC;
1695 if (
const Stmt *Inc = S->getInc()) {
1698 IncCount = getRegionCounter(S->getInc());
1700 IncCount = addCounters(BackedgeCount, BodyBC.ContinueCount);
1701 propagateCounts(IncCount, Inc);
1702 IncrementBC = BreakContinueStack.pop_back_val();
1708 ? getRegionCounter(S->getCond())
1710 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1711 IncrementBC.ContinueCount);
1713 if (
const Expr *Cond = S->getCond()) {
1714 propagateCounts(CondCount, Cond);
1715 adjustForOutOfOrderTraversal(getEnd(S));
1719 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1721 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1725 ? getRegionCounter(S)
1726 : addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1727 subtractCounters(CondCount, BodyCount));
1728 if (OutCount != ParentCount) {
1729 pushRegion(OutCount);
1730 GapRegionCounter = OutCount;
1731 if (BodyHasTerminateStmt)
1732 HasTerminateStmt =
true;
1737 createBranchRegion(S->getCond(), BodyCount,
1738 subtractCounters(CondCount, BodyCount));
1744 Visit(S->getInit());
1745 Visit(S->getLoopVarStmt());
1746 Visit(S->getRangeStmt());
1748 Counter ParentCount =
getRegion().getCounter();
1750 ? getRegionCounter(S->getBody())
1751 : getRegionCounter(S);
1753 BreakContinueStack.push_back(BreakContinue());
1754 extendRegion(S->getBody());
1755 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1756 BreakContinue BC = BreakContinueStack.pop_back_val();
1758 bool BodyHasTerminateStmt = HasTerminateStmt;
1759 HasTerminateStmt =
false;
1762 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1764 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1769 OutCount = getRegionCounter(S);
1771 LoopCount = addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1773 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1775 if (OutCount != ParentCount) {
1776 pushRegion(OutCount);
1777 GapRegionCounter = OutCount;
1778 if (BodyHasTerminateStmt)
1779 HasTerminateStmt =
true;
1784 createBranchRegion(S->getCond(), BodyCount,
1785 subtractCounters(LoopCount, BodyCount));
1790 Visit(S->getElement());
1792 Counter ParentCount =
getRegion().getCounter();
1793 Counter BodyCount = getRegionCounter(S);
1795 BreakContinueStack.push_back(BreakContinue());
1796 extendRegion(S->getBody());
1797 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1798 BreakContinue BC = BreakContinueStack.pop_back_val();
1801 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1803 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1806 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1808 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1809 if (OutCount != ParentCount) {
1810 pushRegion(OutCount);
1811 GapRegionCounter = OutCount;
1818 Visit(S->getInit());
1819 Visit(S->getCond());
1821 BreakContinueStack.push_back(BreakContinue());
1823 const Stmt *Body = S->getBody();
1825 if (
const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1826 if (!CS->body_empty()) {
1830 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1835 for (
size_t i = RegionStack.size(); i != Index; --i) {
1836 if (!RegionStack[i - 1].hasEndLoc())
1837 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1843 propagateCounts(Counter::getZero(), Body);
1844 BreakContinue BC = BreakContinueStack.pop_back_val();
1847 BreakContinueStack.back().ContinueCount = addCounters(
1848 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1850 Counter ParentCount =
getRegion().getCounter();
1851 Counter ExitCount = getRegionCounter(S);
1853 pushRegion(ExitCount);
1854 GapRegionCounter = ExitCount;
1858 MostRecentLocation = getStart(S);
1859 handleFileExit(ExitLoc);
1868 Counter CaseCountSum;
1869 bool HasDefaultCase =
false;
1870 const SwitchCase *Case = S->getSwitchCaseList();
1872 HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1874 addCounters(CaseCountSum, getRegionCounter(Case),
false);
1875 createSwitchCaseRegion(
1876 Case, getRegionCounter(Case),
1877 subtractCounters(ParentCount, getRegionCounter(Case)));
1882 CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
1887 if (!HasDefaultCase) {
1888 Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1889 Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1890 createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1899 ? getRegionCounter(S)
1900 : addCounters(
Parent.getCounter(), getRegionCounter(S));
1904 if (
Parent.hasStartLoc() &&
Parent.getBeginLoc() == getStart(S))
1905 Parent.setCounter(Count);
1907 pushRegion(Count, getStart(S));
1909 GapRegionCounter = Count;
1911 if (
const auto *CS = dyn_cast<CaseStmt>(S)) {
1912 Visit(CS->getLHS());
1913 if (
const Expr *RHS = CS->getRHS())
1916 Visit(S->getSubStmt());
1919 void coverIfConsteval(
const IfStmt *S) {
1920 assert(S->isConsteval());
1922 const auto *Then = S->getThen();
1923 const auto *Else = S->getElse();
1928 const Counter ParentCount =
getRegion().getCounter();
1932 if (S->isNegatedConsteval()) {
1934 markSkipped(S->getIfLoc(), getStart(Then));
1935 propagateCounts(ParentCount, Then);
1939 markSkipped(getEnd(Then), getEnd(Else));
1942 assert(S->isNonNegatedConsteval());
1944 markSkipped(S->getIfLoc(), Else ? getStart(Else) : getEnd(Then));
1947 propagateCounts(ParentCount, Else);
1951 void coverIfConstexpr(
const IfStmt *S) {
1952 assert(S->isConstexpr());
1964 const Counter ParentCount =
getRegion().getCounter();
1969 if (
const auto *
Init = S->getInit()) {
1970 const auto start = getStart(
Init);
1971 const auto end = getEnd(
Init);
1975 if (start.isValid() && end.isValid()) {
1976 markSkipped(startOfSkipped, start);
1977 propagateCounts(ParentCount,
Init);
1978 startOfSkipped = getEnd(
Init);
1982 const auto *Then = S->getThen();
1983 const auto *Else = S->getElse();
1987 markSkipped(startOfSkipped, getStart(Then));
1988 propagateCounts(ParentCount, Then);
1992 markSkipped(getEnd(Then), getEnd(Else));
1995 markSkipped(startOfSkipped, Else ? getStart(Else) : getEnd(Then));
1998 propagateCounts(ParentCount, Else);
2002 void VisitIfStmt(
const IfStmt *S) {
2005 if (S->isConsteval())
2006 return coverIfConsteval(S);
2007 else if (S->isConstexpr())
2008 return coverIfConstexpr(S);
2012 Visit(S->getInit());
2016 extendRegion(S->getCond());
2018 Counter ParentCount =
getRegion().getCounter();
2020 ? getRegionCounter(S->getThen())
2021 : getRegionCounter(S);
2025 propagateCounts(ParentCount, S->getCond());
2028 std::optional<SourceRange> Gap =
2029 findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
2031 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
2033 extendRegion(S->getThen());
2034 Counter OutCount = propagateCounts(ThenCount, S->getThen());
2038 ElseCount = subtractCounters(ParentCount, ThenCount);
2039 else if (S->getElse())
2040 ElseCount = getRegionCounter(S->getElse());
2042 if (
const Stmt *Else = S->getElse()) {
2043 bool ThenHasTerminateStmt = HasTerminateStmt;
2044 HasTerminateStmt =
false;
2046 std::optional<SourceRange> Gap =
2047 findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
2049 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
2052 Counter ElseOutCount = propagateCounts(ElseCount, Else);
2054 OutCount = addCounters(OutCount, ElseOutCount);
2056 if (ThenHasTerminateStmt)
2057 HasTerminateStmt =
true;
2059 OutCount = addCounters(OutCount, ElseCount);
2062 OutCount = getRegionCounter(S);
2064 if (OutCount != ParentCount) {
2065 pushRegion(OutCount);
2066 GapRegionCounter = OutCount;
2071 createBranchRegion(S->getCond(), ThenCount,
2072 subtractCounters(ParentCount, ThenCount));
2078 extendRegion(S->getTryBlock());
2080 Counter ParentCount =
getRegion().getCounter();
2081 propagateCounts(ParentCount, S->getTryBlock());
2083 for (
unsigned I = 0,
E = S->getNumHandlers(); I <
E; ++I)
2084 Visit(S->getHandler(I));
2086 Counter ExitCount = getRegionCounter(S);
2087 pushRegion(ExitCount);
2091 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
2097 Counter ParentCount =
getRegion().getCounter();
2099 ? getRegionCounter(
E->getTrueExpr())
2100 : getRegionCounter(
E);
2103 if (
const auto *BCO = dyn_cast<BinaryConditionalOperator>(
E)) {
2104 propagateCounts(ParentCount, BCO->getCommon());
2105 OutCount = TrueCount;
2107 propagateCounts(ParentCount,
E->getCond());
2110 findGapAreaBetween(
E->getQuestionLoc(), getStart(
E->getTrueExpr()));
2112 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
2114 extendRegion(
E->getTrueExpr());
2115 OutCount = propagateCounts(TrueCount,
E->getTrueExpr());
2118 extendRegion(
E->getFalseExpr());
2120 ? getRegionCounter(
E->getFalseExpr())
2121 : subtractCounters(ParentCount, TrueCount);
2123 Counter FalseOutCount = propagateCounts(FalseCount,
E->getFalseExpr());
2125 OutCount = getRegionCounter(
E);
2127 OutCount = addCounters(OutCount, FalseOutCount);
2129 if (OutCount != ParentCount) {
2130 pushRegion(OutCount);
2131 GapRegionCounter = OutCount;
2136 createBranchRegion(
E->getCond(), TrueCount,
2137 subtractCounters(ParentCount, TrueCount));
2140 void createOrCancelDecision(
const BinaryOperator *
E,
unsigned Since) {
2141 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(
E);
2147 for (
const auto &SR :
ArrayRef(SourceRegions).slice(Since)) {
2148 if (SR.isMCDCBranch()) {
2149 auto [
ID, Conds] = SR.getMCDCBranchParams();
2150 CondIDs[
ID] = Conds;
2155 mcdc::TVIdxBuilder Builder(CondIDs);
2156 unsigned NumTVs = Builder.NumTestVectors;
2158 assert(MaxTVs < mcdc::TVIdxBuilder::HardMaxTVs);
2160 if (NumTVs > MaxTVs) {
2162 cancelDecision(
E, Since, NumTVs, MaxTVs);
2170 std::move(Builder.Indices),
2173 auto DecisionParams = mcdc::DecisionParameters{
2179 createDecisionRegion(
E, DecisionParams);
2183 void cancelDecision(
const BinaryOperator *
E,
unsigned Since,
int NumTVs,
2188 "unsupported MC/DC boolean expression; "
2189 "number of test vectors (%0) exceeds max (%1). "
2190 "Expression will not be covered");
2195 assert(!SR.isMCDCDecision() &&
"Decision shouldn't be seen here");
2196 if (SR.isMCDCBranch())
2197 SR.resetMCDCParams();
2207 SM.isInSystemHeader(
SM.getSpellingLoc(
E->getOperatorLoc())) &&
2213 if (isExprInSystemHeader(
E)) {
2214 LeafExprSet.insert(
E);
2218 bool IsRootNode = MCDCBuilder.isIdle();
2220 unsigned SourceRegionsSince = SourceRegions.size();
2223 MCDCBuilder.pushAndAssignIDs(
E);
2225 extendRegion(
E->getLHS());
2226 propagateCounts(
getRegion().getCounter(),
E->getLHS());
2227 handleFileExit(getEnd(
E->getLHS()));
2230 const auto DecisionLHS = MCDCBuilder.pop();
2233 extendRegion(
E->getRHS());
2234 propagateCounts(getRegionCounter(
E),
E->getRHS());
2237 const auto DecisionRHS = MCDCBuilder.back();
2240 Counter RHSExecCnt = getRegionCounter(
E);
2243 Counter RHSTrueCnt = getRegionCounter(
E->getRHS());
2246 Counter ParentCnt =
getRegion().getCounter();
2250 createBranchRegion(
E->getLHS(), RHSExecCnt,
2251 subtractCounters(ParentCnt, RHSExecCnt), DecisionLHS);
2255 createBranchRegion(
E->getRHS(), RHSTrueCnt,
2256 subtractCounters(RHSExecCnt, RHSTrueCnt), DecisionRHS);
2260 createOrCancelDecision(
E, SourceRegionsSince);
2264 bool shouldVisitRHS(
const Expr *LHS) {
2265 bool LHSIsTrue =
false;
2266 bool LHSIsConst =
false;
2270 return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
2274 if (isExprInSystemHeader(
E)) {
2275 LeafExprSet.insert(
E);
2279 bool IsRootNode = MCDCBuilder.isIdle();
2281 unsigned SourceRegionsSince = SourceRegions.size();
2284 MCDCBuilder.pushAndAssignIDs(
E);
2286 extendRegion(
E->getLHS());
2287 Counter OutCount = propagateCounts(
getRegion().getCounter(),
E->getLHS());
2288 handleFileExit(getEnd(
E->getLHS()));
2291 const auto DecisionLHS = MCDCBuilder.pop();
2294 extendRegion(
E->getRHS());
2295 propagateCounts(getRegionCounter(
E),
E->getRHS());
2298 const auto DecisionRHS = MCDCBuilder.back();
2301 Counter RHSExecCnt = getRegionCounter(
E);
2304 Counter RHSFalseCnt = getRegionCounter(
E->getRHS());
2306 if (!shouldVisitRHS(
E->getLHS())) {
2307 GapRegionCounter = OutCount;
2311 Counter ParentCnt =
getRegion().getCounter();
2315 createBranchRegion(
E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
2316 RHSExecCnt, DecisionLHS);
2320 createBranchRegion(
E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
2321 RHSFalseCnt, DecisionRHS);
2325 createOrCancelDecision(
E, SourceRegionsSince);
2350static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
2353 OS << FunctionName <<
":\n";
2354 CounterMappingContext Ctx(Expressions);
2355 for (
const auto &R : Regions) {
2358 case CounterMappingRegion::CodeRegion:
2360 case CounterMappingRegion::ExpansionRegion:
2363 case CounterMappingRegion::SkippedRegion:
2366 case CounterMappingRegion::GapRegion:
2369 case CounterMappingRegion::BranchRegion:
2370 case CounterMappingRegion::MCDCBranchRegion:
2373 case CounterMappingRegion::MCDCDecisionRegion:
2378 OS <<
"File " << R.FileID <<
", " << R.LineStart <<
":" << R.ColumnStart
2379 <<
" -> " << R.LineEnd <<
":" << R.ColumnEnd <<
" = ";
2381 if (
const auto *DecisionParams =
2382 std::get_if<mcdc::DecisionParameters>(&R.MCDCParams)) {
2383 OS <<
"M:" << DecisionParams->BitmapIdx;
2384 OS <<
", C:" << DecisionParams->NumConditions;
2386 Ctx.dump(R.Count, OS);
2388 if (R.Kind == CounterMappingRegion::BranchRegion ||
2389 R.Kind == CounterMappingRegion::MCDCBranchRegion) {
2391 Ctx.dump(R.FalseCount, OS);
2395 if (
const auto *BranchParams =
2396 std::get_if<mcdc::BranchParameters>(&R.MCDCParams)) {
2397 OS <<
" [" << BranchParams->ID + 1 <<
","
2398 << BranchParams->Conds[
true] + 1;
2399 OS <<
"," << BranchParams->Conds[
false] + 1 <<
"] ";
2402 if (R.Kind == CounterMappingRegion::ExpansionRegion)
2403 OS <<
" (Expanded file = " << R.ExpandedFileID <<
")";
2410 : CGM(CGM), SourceInfo(SourceInfo) {}
2412std::string CoverageMappingModuleGen::getCurrentDirname() {
2417 llvm::sys::fs::current_path(CWD);
2418 return CWD.str().str();
2421std::string CoverageMappingModuleGen::normalizeFilename(StringRef
Filename) {
2423 llvm::sys::path::remove_dots(
Path,
true);
2428 for (
const auto &[From, To] :
2430 if (llvm::sys::path::replace_path_prefix(
Path, From, To))
2433 return Path.str().str();
2437 llvm::InstrProfSectKind SK) {
2438 return llvm::getInstrProfSectionName(
2442void CoverageMappingModuleGen::emitFunctionMappingRecord(
2443 const FunctionInfo &Info, uint64_t FilenamesRef) {
2447 std::string FuncRecordName =
"__covrec_" + llvm::utohexstr(Info.NameHash);
2454 FuncRecordName +=
"u";
2457 const uint64_t NameHash = Info.NameHash;
2458 const uint64_t FuncHash = Info.FuncHash;
2459 const std::string &CoverageMapping = Info.CoverageMapping;
2460#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2461 llvm::Type *FunctionRecordTypes[] = {
2462#include "llvm/ProfileData/InstrProfData.inc"
2464 auto *FunctionRecordTy =
2465 llvm::StructType::get(Ctx,
ArrayRef(FunctionRecordTypes),
2469#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2470 llvm::Constant *FunctionRecordVals[] = {
2471 #include "llvm/ProfileData/InstrProfData.inc"
2473 auto *FuncRecordConstant =
2474 llvm::ConstantStruct::get(FunctionRecordTy,
ArrayRef(FunctionRecordVals));
2477 auto *FuncRecord =
new llvm::GlobalVariable(
2478 CGM.
getModule(), FunctionRecordTy,
true,
2479 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2481 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2483 FuncRecord->setAlignment(llvm::Align(8));
2485 FuncRecord->setComdat(CGM.
getModule().getOrInsertComdat(FuncRecordName));
2492 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2493 const std::string &CoverageMapping,
bool IsUsed) {
2494 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2495 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2498 FunctionNames.push_back(NamePtr);
2507 std::vector<StringRef> Filenames;
2508 std::vector<CounterExpression> Expressions;
2509 std::vector<CounterMappingRegion> Regions;
2510 FilenameStrs.resize(FileEntries.size() + 1);
2511 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2512 for (
const auto &Entry : FileEntries) {
2513 auto I = Entry.second;
2514 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2517 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
2518 Expressions, Regions);
2521 dump(llvm::outs(), NameValue, Expressions, Regions);
2526 if (FunctionRecords.empty())
2529 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
2533 FilenameStrs.resize(FileEntries.size() + 1);
2535 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2536 for (
const auto &Entry : FileEntries) {
2537 auto I = Entry.second;
2538 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2541 std::string Filenames;
2543 llvm::raw_string_ostream OS(Filenames);
2544 CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
2546 auto *FilenamesVal =
2547 llvm::ConstantDataArray::getString(Ctx, Filenames,
false);
2548 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
2551 for (
const FunctionInfo &Info : FunctionRecords)
2552 emitFunctionMappingRecord(Info, FilenamesRef);
2554 const unsigned NRecords = 0;
2555 const size_t FilenamesSize = Filenames.size();
2556 const unsigned CoverageMappingSize = 0;
2557 llvm::Type *CovDataHeaderTypes[] = {
2558#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2559#include "llvm/ProfileData/InstrProfData.inc"
2561 auto CovDataHeaderTy =
2562 llvm::StructType::get(Ctx,
ArrayRef(CovDataHeaderTypes));
2563 llvm::Constant *CovDataHeaderVals[] = {
2564#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2565#include "llvm/ProfileData/InstrProfData.inc"
2567 auto CovDataHeaderVal =
2568 llvm::ConstantStruct::get(CovDataHeaderTy,
ArrayRef(CovDataHeaderVals));
2571 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2572 auto CovDataTy = llvm::StructType::get(Ctx,
ArrayRef(CovDataTypes));
2573 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2574 auto CovDataVal = llvm::ConstantStruct::get(CovDataTy,
ArrayRef(TUDataVals));
2575 auto CovData =
new llvm::GlobalVariable(
2576 CGM.
getModule(), CovDataTy,
true, llvm::GlobalValue::PrivateLinkage,
2577 CovDataVal, llvm::getCoverageMappingVarName());
2580 CovData->setAlignment(llvm::Align(8));
2585 if (!FunctionNames.empty()) {
2586 auto NamesArrTy = llvm::ArrayType::get(llvm::PointerType::getUnqual(Ctx),
2587 FunctionNames.size());
2588 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
2591 new llvm::GlobalVariable(CGM.
getModule(), NamesArrTy,
true,
2592 llvm::GlobalValue::InternalLinkage, NamesArrVal,
2593 llvm::getCoverageUnusedNamesVarName());
2598 auto It = FileEntries.find(
File);
2599 if (It != FileEntries.end())
2601 unsigned FileID = FileEntries.size() + 1;
2602 FileEntries.insert(std::make_pair(
File,
FileID));
2607 llvm::raw_ostream &OS) {
2608 assert(CounterMap && MCDCState);
2609 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCState,
SM,
2611 Walker.VisitDecl(
D);
2616 llvm::raw_ostream &OS) {
2617 EmptyCoverageMappingBuilder Walker(CVM,
SM, LangOpts);
2618 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)
Defines the clang::FileManager interface and associated types.
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 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 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.