1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2ee02499aSAlex Lorenz //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ee02499aSAlex Lorenz //
7ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
8ee02499aSAlex Lorenz //
9ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator
10ee02499aSAlex Lorenz //
11ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
12ee02499aSAlex Lorenz
13ee02499aSAlex Lorenz #include "CoverageMappingGen.h"
14ee02499aSAlex Lorenz #include "CodeGenFunction.h"
15ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h"
16dd1ea9deSVedant Kumar #include "clang/Basic/Diagnostic.h"
17e08464fbSReid Kleckner #include "clang/Basic/FileManager.h"
18dd1ea9deSVedant Kumar #include "clang/Frontend/FrontendDiagnostic.h"
19ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
20e08464fbSReid Kleckner #include "llvm/ADT/Optional.h"
21bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h"
22ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h"
23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
24b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
260d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
27ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
2814f8fb68SVedant Kumar #include "llvm/Support/Path.h"
29ee02499aSAlex Lorenz
30dd1ea9deSVedant Kumar // This selects the coverage mapping format defined when `InstrProfData.inc`
31dd1ea9deSVedant Kumar // is textually included.
32dd1ea9deSVedant Kumar #define COVMAP_V3
33dd1ea9deSVedant Kumar
349caa3fbeSZequan Wu static llvm::cl::opt<bool> EmptyLineCommentCoverage(
359caa3fbeSZequan Wu "emptyline-comment-coverage",
369caa3fbeSZequan Wu llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
379caa3fbeSZequan Wu "disable it on test)"),
389caa3fbeSZequan Wu llvm::cl::init(true), llvm::cl::Hidden);
399caa3fbeSZequan Wu
40ee02499aSAlex Lorenz using namespace clang;
41ee02499aSAlex Lorenz using namespace CodeGen;
42ee02499aSAlex Lorenz using namespace llvm::coverage;
43ee02499aSAlex Lorenz
44b46176bbSZequan Wu CoverageSourceInfo *
setUpCoverageCallbacks(Preprocessor & PP)45b46176bbSZequan Wu CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
469caa3fbeSZequan Wu CoverageSourceInfo *CoverageInfo =
479caa3fbeSZequan Wu new CoverageSourceInfo(PP.getSourceManager());
48b46176bbSZequan Wu PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
499caa3fbeSZequan Wu if (EmptyLineCommentCoverage) {
50b46176bbSZequan Wu PP.addCommentHandler(CoverageInfo);
519caa3fbeSZequan Wu PP.setEmptylineHandler(CoverageInfo);
52b46176bbSZequan Wu PP.setPreprocessToken(true);
53b46176bbSZequan Wu PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
54b46176bbSZequan Wu // Update previous token location.
55b46176bbSZequan Wu CoverageInfo->PrevTokLoc = Tok.getLocation();
5684fffa67SZequan Wu if (Tok.getKind() != clang::tok::eod)
57b46176bbSZequan Wu CoverageInfo->updateNextTokLoc(Tok.getLocation());
58b46176bbSZequan Wu });
599caa3fbeSZequan Wu }
60b46176bbSZequan Wu return CoverageInfo;
61b46176bbSZequan Wu }
62b46176bbSZequan Wu
AddSkippedRange(SourceRange Range,SkippedRange::Kind RangeKind)63e6a76a49SBruno Cardoso Lopes void CoverageSourceInfo::AddSkippedRange(SourceRange Range,
64e6a76a49SBruno Cardoso Lopes SkippedRange::Kind RangeKind) {
659caa3fbeSZequan Wu if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
669caa3fbeSZequan Wu PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
679caa3fbeSZequan Wu SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
689caa3fbeSZequan Wu Range.getBegin()))
699caa3fbeSZequan Wu SkippedRanges.back().Range.setEnd(Range.getEnd());
709caa3fbeSZequan Wu else
71e6a76a49SBruno Cardoso Lopes SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
729caa3fbeSZequan Wu }
739caa3fbeSZequan Wu
SourceRangeSkipped(SourceRange Range,SourceLocation)743919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
75e6a76a49SBruno Cardoso Lopes AddSkippedRange(Range, SkippedRange::PPIfElse);
769caa3fbeSZequan Wu }
779caa3fbeSZequan Wu
HandleEmptyline(SourceRange Range)789caa3fbeSZequan Wu void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
79e6a76a49SBruno Cardoso Lopes AddSkippedRange(Range, SkippedRange::EmptyLine);
80b46176bbSZequan Wu }
81b46176bbSZequan Wu
HandleComment(Preprocessor & PP,SourceRange Range)82b46176bbSZequan Wu bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
83e6a76a49SBruno Cardoso Lopes AddSkippedRange(Range, SkippedRange::Comment);
84b46176bbSZequan Wu return false;
85b46176bbSZequan Wu }
86b46176bbSZequan Wu
updateNextTokLoc(SourceLocation Loc)87b46176bbSZequan Wu void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
889caa3fbeSZequan Wu if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
89b46176bbSZequan Wu SkippedRanges.back().NextTokLoc = Loc;
90ee02499aSAlex Lorenz }
91ee02499aSAlex Lorenz
92ee02499aSAlex Lorenz namespace {
93ee02499aSAlex Lorenz
949fc8faf9SAdrian Prantl /// A region of source code that can be mapped to a counter.
9509c7179bSJustin Bogner class SourceMappingRegion {
969f2967bcSAlan Phipps /// Primary Counter that is also used for Branch Regions for "True" branches.
97ee02499aSAlex Lorenz Counter Count;
98ee02499aSAlex Lorenz
999f2967bcSAlan Phipps /// Secondary Counter used for Branch Regions for "False" branches.
1009f2967bcSAlan Phipps Optional<Counter> FalseCount;
1019f2967bcSAlan Phipps
1029fc8faf9SAdrian Prantl /// The region's starting location.
103bf42cfd7SJustin Bogner Optional<SourceLocation> LocStart;
104ee02499aSAlex Lorenz
1059fc8faf9SAdrian Prantl /// The region's ending location.
106bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd;
107ee02499aSAlex Lorenz
108a1c4deb7SVedant Kumar /// Whether this region is a gap region. The count from a gap region is set
109a1c4deb7SVedant Kumar /// as the line execution count if there are no other regions on the line.
110a1c4deb7SVedant Kumar bool GapRegion;
111a1c4deb7SVedant Kumar
11209c7179bSJustin Bogner public:
SourceMappingRegion(Counter Count,Optional<SourceLocation> LocStart,Optional<SourceLocation> LocEnd,bool GapRegion=false)113bf42cfd7SJustin Bogner SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
1149783e209SZequan Wu Optional<SourceLocation> LocEnd, bool GapRegion = false)
1159783e209SZequan Wu : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion) {
1169783e209SZequan Wu }
117ee02499aSAlex Lorenz
SourceMappingRegion(Counter Count,Optional<Counter> FalseCount,Optional<SourceLocation> LocStart,Optional<SourceLocation> LocEnd,bool GapRegion=false)1189f2967bcSAlan Phipps SourceMappingRegion(Counter Count, Optional<Counter> FalseCount,
1199f2967bcSAlan Phipps Optional<SourceLocation> LocStart,
1209783e209SZequan Wu Optional<SourceLocation> LocEnd, bool GapRegion = false)
1219f2967bcSAlan Phipps : Count(Count), FalseCount(FalseCount), LocStart(LocStart),
1229783e209SZequan Wu LocEnd(LocEnd), GapRegion(GapRegion) {}
1239f2967bcSAlan Phipps
getCounter() const12409c7179bSJustin Bogner const Counter &getCounter() const { return Count; }
12509c7179bSJustin Bogner
getFalseCounter() const1269f2967bcSAlan Phipps const Counter &getFalseCounter() const {
1279f2967bcSAlan Phipps assert(FalseCount && "Region has no alternate counter");
1289f2967bcSAlan Phipps return *FalseCount;
1299f2967bcSAlan Phipps }
1309f2967bcSAlan Phipps
setCounter(Counter C)131bf42cfd7SJustin Bogner void setCounter(Counter C) { Count = C; }
13209c7179bSJustin Bogner
hasStartLoc() const133064a08cdSKazu Hirata bool hasStartLoc() const { return LocStart.has_value(); }
134bf42cfd7SJustin Bogner
setStartLoc(SourceLocation Loc)135bf42cfd7SJustin Bogner void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
136bf42cfd7SJustin Bogner
getBeginLoc() const1373cffc4c7SStephen Kelly SourceLocation getBeginLoc() const {
138bf42cfd7SJustin Bogner assert(LocStart && "Region has no start location");
139bf42cfd7SJustin Bogner return *LocStart;
14009c7179bSJustin Bogner }
14109c7179bSJustin Bogner
hasEndLoc() const142064a08cdSKazu Hirata bool hasEndLoc() const { return LocEnd.has_value(); }
143ee02499aSAlex Lorenz
setEndLoc(SourceLocation Loc)144a14a1f92SVedant Kumar void setEndLoc(SourceLocation Loc) {
145a14a1f92SVedant Kumar assert(Loc.isValid() && "Setting an invalid end location");
146a14a1f92SVedant Kumar LocEnd = Loc;
147a14a1f92SVedant Kumar }
148ee02499aSAlex Lorenz
getEndLoc() const149462c77b4SCraig Topper SourceLocation getEndLoc() const {
150bf42cfd7SJustin Bogner assert(LocEnd && "Region has no end location");
151bf42cfd7SJustin Bogner return *LocEnd;
152ee02499aSAlex Lorenz }
153747b0e29SVedant Kumar
isGap() const154a1c4deb7SVedant Kumar bool isGap() const { return GapRegion; }
155a1c4deb7SVedant Kumar
setGap(bool Gap)156a1c4deb7SVedant Kumar void setGap(bool Gap) { GapRegion = Gap; }
1579f2967bcSAlan Phipps
isBranch() const158064a08cdSKazu Hirata bool isBranch() const { return FalseCount.has_value(); }
159ee02499aSAlex Lorenz };
160ee02499aSAlex Lorenz
161d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
162d7369648SVedant Kumar struct SpellingRegion {
163d7369648SVedant Kumar /// The line where the region starts.
164d7369648SVedant Kumar unsigned LineStart;
165d7369648SVedant Kumar
166d7369648SVedant Kumar /// The column where the region starts.
167d7369648SVedant Kumar unsigned ColumnStart;
168d7369648SVedant Kumar
169d7369648SVedant Kumar /// The line where the region ends.
170d7369648SVedant Kumar unsigned LineEnd;
171d7369648SVedant Kumar
172d7369648SVedant Kumar /// The column where the region ends.
173d7369648SVedant Kumar unsigned ColumnEnd;
174d7369648SVedant Kumar
SpellingRegion__anon8934bc200211::SpellingRegion175d7369648SVedant Kumar SpellingRegion(SourceManager &SM, SourceLocation LocStart,
176d7369648SVedant Kumar SourceLocation LocEnd) {
177d7369648SVedant Kumar LineStart = SM.getSpellingLineNumber(LocStart);
178d7369648SVedant Kumar ColumnStart = SM.getSpellingColumnNumber(LocStart);
179d7369648SVedant Kumar LineEnd = SM.getSpellingLineNumber(LocEnd);
180d7369648SVedant Kumar ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
181d7369648SVedant Kumar }
182d7369648SVedant Kumar
SpellingRegion__anon8934bc200211::SpellingRegion183fa8fa044SVedant Kumar SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
184a6e4358fSStephen Kelly : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
185fa8fa044SVedant Kumar
186d7369648SVedant Kumar /// Check if the start and end locations appear in source order, i.e
187d7369648SVedant Kumar /// top->bottom, left->right.
isInSourceOrder__anon8934bc200211::SpellingRegion188d7369648SVedant Kumar bool isInSourceOrder() const {
189d7369648SVedant Kumar return (LineStart < LineEnd) ||
190d7369648SVedant Kumar (LineStart == LineEnd && ColumnStart <= ColumnEnd);
191d7369648SVedant Kumar }
192d7369648SVedant Kumar };
193d7369648SVedant Kumar
1949fc8faf9SAdrian Prantl /// Provides the common functionality for the different
195ee02499aSAlex Lorenz /// coverage mapping region builders.
196ee02499aSAlex Lorenz class CoverageMappingBuilder {
197ee02499aSAlex Lorenz public:
198ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM;
199ee02499aSAlex Lorenz SourceManager &SM;
200ee02499aSAlex Lorenz const LangOptions &LangOpts;
201ee02499aSAlex Lorenz
202ee02499aSAlex Lorenz private:
2039fc8faf9SAdrian Prantl /// Map of clang's FileIDs to IDs used for coverage mapping.
204bf42cfd7SJustin Bogner llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
205bf42cfd7SJustin Bogner FileIDMapping;
206ee02499aSAlex Lorenz
207ee02499aSAlex Lorenz public:
2089fc8faf9SAdrian Prantl /// The coverage mapping regions for this function
209ee02499aSAlex Lorenz llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
2109fc8faf9SAdrian Prantl /// The source mapping regions for this function.
211f59329b0SJustin Bogner std::vector<SourceMappingRegion> SourceRegions;
212ee02499aSAlex Lorenz
2139fc8faf9SAdrian Prantl /// A set of regions which can be used as a filter.
214fc05ee34SIgor Kudrin ///
215fc05ee34SIgor Kudrin /// It is produced by emitExpansionRegions() and is used in
216fc05ee34SIgor Kudrin /// emitSourceRegions() to suppress producing code regions if
217fc05ee34SIgor Kudrin /// the same area is covered by expansion regions.
218fc05ee34SIgor Kudrin typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
219fc05ee34SIgor Kudrin SourceRegionFilter;
220fc05ee34SIgor Kudrin
CoverageMappingBuilder(CoverageMappingModuleGen & CVM,SourceManager & SM,const LangOptions & LangOpts)221ee02499aSAlex Lorenz CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
222ee02499aSAlex Lorenz const LangOptions &LangOpts)
223bf42cfd7SJustin Bogner : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
224ee02499aSAlex Lorenz
2259fc8faf9SAdrian Prantl /// Return the precise end location for the given token.
getPreciseTokenLocEnd(SourceLocation Loc)226ee02499aSAlex Lorenz SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
227bf42cfd7SJustin Bogner // We avoid getLocForEndOfToken here, because it doesn't do what we want for
228bf42cfd7SJustin Bogner // macro locations, which we just treat as expanded files.
229bf42cfd7SJustin Bogner unsigned TokLen =
230bf42cfd7SJustin Bogner Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
231bf42cfd7SJustin Bogner return Loc.getLocWithOffset(TokLen);
232ee02499aSAlex Lorenz }
233ee02499aSAlex Lorenz
2349fc8faf9SAdrian Prantl /// Return the start location of an included file or expanded macro.
getStartOfFileOrMacro(SourceLocation Loc)235bf42cfd7SJustin Bogner SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
236bf42cfd7SJustin Bogner if (Loc.isMacroID())
237bf42cfd7SJustin Bogner return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
238bf42cfd7SJustin Bogner return SM.getLocForStartOfFile(SM.getFileID(Loc));
239ee02499aSAlex Lorenz }
240ee02499aSAlex Lorenz
2419fc8faf9SAdrian Prantl /// Return the end location of an included file or expanded macro.
getEndOfFileOrMacro(SourceLocation Loc)242bf42cfd7SJustin Bogner SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
243bf42cfd7SJustin Bogner if (Loc.isMacroID())
244bf42cfd7SJustin Bogner return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
245f14b2078SJustin Bogner SM.getFileOffset(Loc));
246bf42cfd7SJustin Bogner return SM.getLocForEndOfFile(SM.getFileID(Loc));
247bf42cfd7SJustin Bogner }
248ee02499aSAlex Lorenz
2499fc8faf9SAdrian Prantl /// Find out where the current file is included or macro is expanded.
getIncludeOrExpansionLoc(SourceLocation Loc)250bf42cfd7SJustin Bogner SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
251b5f8171aSRichard Smith return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
252bf42cfd7SJustin Bogner : SM.getIncludeLoc(SM.getFileID(Loc));
253bf42cfd7SJustin Bogner }
254bf42cfd7SJustin Bogner
2559fc8faf9SAdrian Prantl /// Return true if \c Loc is a location in a built-in macro.
isInBuiltin(SourceLocation Loc)256682bfbf3SJustin Bogner bool isInBuiltin(SourceLocation Loc) {
25799d1b295SMehdi Amini return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
258682bfbf3SJustin Bogner }
259682bfbf3SJustin Bogner
2609fc8faf9SAdrian Prantl /// Check whether \c Loc is included or expanded from \c Parent.
isNestedIn(SourceLocation Loc,FileID Parent)261d9e1a61dSIgor Kudrin bool isNestedIn(SourceLocation Loc, FileID Parent) {
262d9e1a61dSIgor Kudrin do {
263d9e1a61dSIgor Kudrin Loc = getIncludeOrExpansionLoc(Loc);
264d9e1a61dSIgor Kudrin if (Loc.isInvalid())
265d9e1a61dSIgor Kudrin return false;
266d9e1a61dSIgor Kudrin } while (!SM.isInFileID(Loc, Parent));
267d9e1a61dSIgor Kudrin return true;
268d9e1a61dSIgor Kudrin }
269d9e1a61dSIgor Kudrin
2709fc8faf9SAdrian Prantl /// Get the start of \c S ignoring macro arguments and builtin macros.
getStart(const Stmt * S)271bf42cfd7SJustin Bogner SourceLocation getStart(const Stmt *S) {
272f2ceec48SStephen Kelly SourceLocation Loc = S->getBeginLoc();
273682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
274b5f8171aSRichard Smith Loc = SM.getImmediateExpansionRange(Loc).getBegin();
275bf42cfd7SJustin Bogner return Loc;
276bf42cfd7SJustin Bogner }
277bf42cfd7SJustin Bogner
2789fc8faf9SAdrian Prantl /// Get the end of \c S ignoring macro arguments and builtin macros.
getEnd(const Stmt * S)279bf42cfd7SJustin Bogner SourceLocation getEnd(const Stmt *S) {
2801c301dcbSStephen Kelly SourceLocation Loc = S->getEndLoc();
281682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
282b5f8171aSRichard Smith Loc = SM.getImmediateExpansionRange(Loc).getBegin();
283f14b2078SJustin Bogner return getPreciseTokenLocEnd(Loc);
284bf42cfd7SJustin Bogner }
285bf42cfd7SJustin Bogner
2869fc8faf9SAdrian Prantl /// Find the set of files we have regions for and assign IDs
287bf42cfd7SJustin Bogner ///
288bf42cfd7SJustin Bogner /// Fills \c Mapping with the virtual file mapping needed to write out
289bf42cfd7SJustin Bogner /// coverage and collects the necessary file information to emit source and
290bf42cfd7SJustin Bogner /// expansion regions.
gatherFileIDs(SmallVectorImpl<unsigned> & Mapping)291bf42cfd7SJustin Bogner void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
292bf42cfd7SJustin Bogner FileIDMapping.clear();
293bf42cfd7SJustin Bogner
294bc6b80a0SVedant Kumar llvm::SmallSet<FileID, 8> Visited;
295bf42cfd7SJustin Bogner SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
296bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) {
297a6e4358fSStephen Kelly SourceLocation Loc = Region.getBeginLoc();
298bf42cfd7SJustin Bogner FileID File = SM.getFileID(Loc);
299bc6b80a0SVedant Kumar if (!Visited.insert(File).second)
300bf42cfd7SJustin Bogner continue;
301bf42cfd7SJustin Bogner
30293205af0SVedant Kumar // Do not map FileID's associated with system headers.
30393205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
30493205af0SVedant Kumar continue;
30593205af0SVedant Kumar
306bf42cfd7SJustin Bogner unsigned Depth = 0;
307bf42cfd7SJustin Bogner for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
308ed1fe5d0SYaron Keren Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
309bf42cfd7SJustin Bogner ++Depth;
310bf42cfd7SJustin Bogner FileLocs.push_back(std::make_pair(Loc, Depth));
311bf42cfd7SJustin Bogner }
312899d1392SFangrui Song llvm::stable_sort(FileLocs, llvm::less_second());
313bf42cfd7SJustin Bogner
314bf42cfd7SJustin Bogner for (const auto &FL : FileLocs) {
315bf42cfd7SJustin Bogner SourceLocation Loc = FL.first;
316bf42cfd7SJustin Bogner FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
317ee02499aSAlex Lorenz auto Entry = SM.getFileEntryForID(SpellingFile);
318ee02499aSAlex Lorenz if (!Entry)
319bf42cfd7SJustin Bogner continue;
320ee02499aSAlex Lorenz
321bf42cfd7SJustin Bogner FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
322bf42cfd7SJustin Bogner Mapping.push_back(CVM.getFileID(Entry));
323bf42cfd7SJustin Bogner }
324ee02499aSAlex Lorenz }
325ee02499aSAlex Lorenz
3269fc8faf9SAdrian Prantl /// Get the coverage mapping file ID for \c Loc.
327bf42cfd7SJustin Bogner ///
328bf42cfd7SJustin Bogner /// If such file id doesn't exist, return None.
getCoverageFileID(SourceLocation Loc)329bf42cfd7SJustin Bogner Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
330bf42cfd7SJustin Bogner auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
331bf42cfd7SJustin Bogner if (Mapping != FileIDMapping.end())
332bf42cfd7SJustin Bogner return Mapping->second.first;
333903678caSJustin Bogner return None;
334ee02499aSAlex Lorenz }
335ee02499aSAlex Lorenz
336b46176bbSZequan Wu /// This shrinks the skipped range if it spans a line that contains a
337b46176bbSZequan Wu /// non-comment token. If shrinking the skipped range would make it empty,
338b46176bbSZequan Wu /// this returns None.
339e6a76a49SBruno Cardoso Lopes /// Note this function can potentially be expensive because
340e6a76a49SBruno Cardoso Lopes /// getSpellingLineNumber uses getLineNumber, which is expensive.
adjustSkippedRange(SourceManager & SM,SourceLocation LocStart,SourceLocation LocEnd,SourceLocation PrevTokLoc,SourceLocation NextTokLoc)341b46176bbSZequan Wu Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
34284fffa67SZequan Wu SourceLocation LocStart,
34384fffa67SZequan Wu SourceLocation LocEnd,
344b46176bbSZequan Wu SourceLocation PrevTokLoc,
345b46176bbSZequan Wu SourceLocation NextTokLoc) {
34684fffa67SZequan Wu SpellingRegion SR{SM, LocStart, LocEnd};
3479caa3fbeSZequan Wu SR.ColumnStart = 1;
3489caa3fbeSZequan Wu if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
3499caa3fbeSZequan Wu SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
3509caa3fbeSZequan Wu SR.LineStart++;
3519caa3fbeSZequan Wu if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
3529caa3fbeSZequan Wu SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
3539caa3fbeSZequan Wu SR.LineEnd--;
3549caa3fbeSZequan Wu SR.ColumnEnd++;
3559caa3fbeSZequan Wu }
3569caa3fbeSZequan Wu if (SR.isInSourceOrder())
357b46176bbSZequan Wu return SR;
358b46176bbSZequan Wu return None;
359b46176bbSZequan Wu }
360b46176bbSZequan Wu
3619fc8faf9SAdrian Prantl /// Gather all the regions that were skipped by the preprocessor
362b46176bbSZequan Wu /// using the constructs like #if or comments.
gatherSkippedRegions()363ee02499aSAlex Lorenz void gatherSkippedRegions() {
364ee02499aSAlex Lorenz /// An array of the minimum lineStarts and the maximum lineEnds
365ee02499aSAlex Lorenz /// for mapping regions from the appropriate source files.
366ee02499aSAlex Lorenz llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
367ee02499aSAlex Lorenz FileLineRanges.resize(
368ee02499aSAlex Lorenz FileIDMapping.size(),
369ee02499aSAlex Lorenz std::make_pair(std::numeric_limits<unsigned>::max(), 0));
370ee02499aSAlex Lorenz for (const auto &R : MappingRegions) {
371ee02499aSAlex Lorenz FileLineRanges[R.FileID].first =
372ee02499aSAlex Lorenz std::min(FileLineRanges[R.FileID].first, R.LineStart);
373ee02499aSAlex Lorenz FileLineRanges[R.FileID].second =
374ee02499aSAlex Lorenz std::max(FileLineRanges[R.FileID].second, R.LineEnd);
375ee02499aSAlex Lorenz }
376ee02499aSAlex Lorenz
377ee02499aSAlex Lorenz auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
378b46176bbSZequan Wu for (auto &I : SkippedRanges) {
379b46176bbSZequan Wu SourceRange Range = I.Range;
380b46176bbSZequan Wu auto LocStart = Range.getBegin();
381b46176bbSZequan Wu auto LocEnd = Range.getEnd();
382bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
383bf42cfd7SJustin Bogner "region spans multiple files");
384ee02499aSAlex Lorenz
385bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart);
386903678caSJustin Bogner if (!CovFileID)
387ee02499aSAlex Lorenz continue;
388e6a76a49SBruno Cardoso Lopes Optional<SpellingRegion> SR;
389e6a76a49SBruno Cardoso Lopes if (I.isComment())
390e6a76a49SBruno Cardoso Lopes SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc,
391e6a76a49SBruno Cardoso Lopes I.NextTokLoc);
392e6a76a49SBruno Cardoso Lopes else if (I.isPPIfElse() || I.isEmptyLine())
393e6a76a49SBruno Cardoso Lopes SR = {SM, LocStart, LocEnd};
394e6a76a49SBruno Cardoso Lopes
395452db157SKazu Hirata if (!SR)
396b46176bbSZequan Wu continue;
397fd34280bSJustin Bogner auto Region = CounterMappingRegion::makeSkipped(
39884fffa67SZequan Wu *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
39984fffa67SZequan Wu SR->ColumnEnd);
400ee02499aSAlex Lorenz // Make sure that we only collect the regions that are inside
4012a8c18d9SAlexander Kornienko // the source code of this function.
402903678caSJustin Bogner if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
403903678caSJustin Bogner Region.LineEnd <= FileLineRanges[*CovFileID].second)
404ee02499aSAlex Lorenz MappingRegions.push_back(Region);
405ee02499aSAlex Lorenz }
406ee02499aSAlex Lorenz }
407ee02499aSAlex Lorenz
4089fc8faf9SAdrian Prantl /// Generate the coverage counter mapping regions from collected
409ee02499aSAlex Lorenz /// source regions.
emitSourceRegions(const SourceRegionFilter & Filter)410fc05ee34SIgor Kudrin void emitSourceRegions(const SourceRegionFilter &Filter) {
411bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) {
412bf42cfd7SJustin Bogner assert(Region.hasEndLoc() && "incomplete region");
413ee02499aSAlex Lorenz
414a6e4358fSStephen Kelly SourceLocation LocStart = Region.getBeginLoc();
4158b563665SYaron Keren assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
416f59329b0SJustin Bogner
41793205af0SVedant Kumar // Ignore regions from system headers.
41893205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
41993205af0SVedant Kumar continue;
42093205af0SVedant Kumar
421bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart);
422bf42cfd7SJustin Bogner // Ignore regions that don't have a file, such as builtin macros.
423bf42cfd7SJustin Bogner if (!CovFileID)
424ee02499aSAlex Lorenz continue;
425ee02499aSAlex Lorenz
426f14b2078SJustin Bogner SourceLocation LocEnd = Region.getEndLoc();
427bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
428bf42cfd7SJustin Bogner "region spans multiple files");
429bf42cfd7SJustin Bogner
430fc05ee34SIgor Kudrin // Don't add code regions for the area covered by expansion regions.
431fc05ee34SIgor Kudrin // This not only suppresses redundant regions, but sometimes prevents
432fc05ee34SIgor Kudrin // creating regions with wrong counters if, for example, a statement's
433fc05ee34SIgor Kudrin // body ends at the end of a nested macro.
434fc05ee34SIgor Kudrin if (Filter.count(std::make_pair(LocStart, LocEnd)))
435fc05ee34SIgor Kudrin continue;
436fc05ee34SIgor Kudrin
437d7369648SVedant Kumar // Find the spelling locations for the mapping region.
438d7369648SVedant Kumar SpellingRegion SR{SM, LocStart, LocEnd};
439d7369648SVedant Kumar assert(SR.isInSourceOrder() && "region start and end out of order");
440a1c4deb7SVedant Kumar
441a1c4deb7SVedant Kumar if (Region.isGap()) {
442a1c4deb7SVedant Kumar MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
443a1c4deb7SVedant Kumar Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
444a1c4deb7SVedant Kumar SR.LineEnd, SR.ColumnEnd));
4459f2967bcSAlan Phipps } else if (Region.isBranch()) {
4469f2967bcSAlan Phipps MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
4479f2967bcSAlan Phipps Region.getCounter(), Region.getFalseCounter(), *CovFileID,
4489f2967bcSAlan Phipps SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
449a1c4deb7SVedant Kumar } else {
450bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeRegion(
451d7369648SVedant Kumar Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
452d7369648SVedant Kumar SR.LineEnd, SR.ColumnEnd));
453bf42cfd7SJustin Bogner }
454bf42cfd7SJustin Bogner }
455a1c4deb7SVedant Kumar }
456bf42cfd7SJustin Bogner
4579fc8faf9SAdrian Prantl /// Generate expansion regions for each virtual file we've seen.
emitExpansionRegions()458fc05ee34SIgor Kudrin SourceRegionFilter emitExpansionRegions() {
459fc05ee34SIgor Kudrin SourceRegionFilter Filter;
460bf42cfd7SJustin Bogner for (const auto &FM : FileIDMapping) {
461bf42cfd7SJustin Bogner SourceLocation ExpandedLoc = FM.second.second;
462bf42cfd7SJustin Bogner SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
463bf42cfd7SJustin Bogner if (ParentLoc.isInvalid())
464ee02499aSAlex Lorenz continue;
465ee02499aSAlex Lorenz
466bf42cfd7SJustin Bogner auto ParentFileID = getCoverageFileID(ParentLoc);
467bf42cfd7SJustin Bogner if (!ParentFileID)
468bf42cfd7SJustin Bogner continue;
469bf42cfd7SJustin Bogner auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
470bf42cfd7SJustin Bogner assert(ExpandedFileID && "expansion in uncovered file");
471bf42cfd7SJustin Bogner
472bf42cfd7SJustin Bogner SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
473bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
474bf42cfd7SJustin Bogner "region spans multiple files");
475fc05ee34SIgor Kudrin Filter.insert(std::make_pair(ParentLoc, LocEnd));
476bf42cfd7SJustin Bogner
477d7369648SVedant Kumar SpellingRegion SR{SM, ParentLoc, LocEnd};
478d7369648SVedant Kumar assert(SR.isInSourceOrder() && "region start and end out of order");
479bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeExpansion(
480d7369648SVedant Kumar *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
481d7369648SVedant Kumar SR.LineEnd, SR.ColumnEnd));
482ee02499aSAlex Lorenz }
483fc05ee34SIgor Kudrin return Filter;
484ee02499aSAlex Lorenz }
485ee02499aSAlex Lorenz };
486ee02499aSAlex Lorenz
4879fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that
488ee02499aSAlex Lorenz /// are not emitted.
489ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
EmptyCoverageMappingBuilder__anon8934bc200211::EmptyCoverageMappingBuilder490ee02499aSAlex Lorenz EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
491ee02499aSAlex Lorenz const LangOptions &LangOpts)
492ee02499aSAlex Lorenz : CoverageMappingBuilder(CVM, SM, LangOpts) {}
493ee02499aSAlex Lorenz
VisitDecl__anon8934bc200211::EmptyCoverageMappingBuilder494ee02499aSAlex Lorenz void VisitDecl(const Decl *D) {
495ee02499aSAlex Lorenz if (!D->hasBody())
496ee02499aSAlex Lorenz return;
497ee02499aSAlex Lorenz auto Body = D->getBody();
498d9e1a61dSIgor Kudrin SourceLocation Start = getStart(Body);
499d9e1a61dSIgor Kudrin SourceLocation End = getEnd(Body);
500d9e1a61dSIgor Kudrin if (!SM.isWrittenInSameFile(Start, End)) {
501d9e1a61dSIgor Kudrin // Walk up to find the common ancestor.
502d9e1a61dSIgor Kudrin // Correct the locations accordingly.
503d9e1a61dSIgor Kudrin FileID StartFileID = SM.getFileID(Start);
504d9e1a61dSIgor Kudrin FileID EndFileID = SM.getFileID(End);
505d9e1a61dSIgor Kudrin while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
506d9e1a61dSIgor Kudrin Start = getIncludeOrExpansionLoc(Start);
507d9e1a61dSIgor Kudrin assert(Start.isValid() &&
508d9e1a61dSIgor Kudrin "Declaration start location not nested within a known region");
509d9e1a61dSIgor Kudrin StartFileID = SM.getFileID(Start);
510d9e1a61dSIgor Kudrin }
511d9e1a61dSIgor Kudrin while (StartFileID != EndFileID) {
512d9e1a61dSIgor Kudrin End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
513d9e1a61dSIgor Kudrin assert(End.isValid() &&
514d9e1a61dSIgor Kudrin "Declaration end location not nested within a known region");
515d9e1a61dSIgor Kudrin EndFileID = SM.getFileID(End);
516d9e1a61dSIgor Kudrin }
517d9e1a61dSIgor Kudrin }
518d9e1a61dSIgor Kudrin SourceRegions.emplace_back(Counter(), Start, End);
519ee02499aSAlex Lorenz }
520ee02499aSAlex Lorenz
5219fc8faf9SAdrian Prantl /// Write the mapping data to the output stream
write__anon8934bc200211::EmptyCoverageMappingBuilder522ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) {
523ee02499aSAlex Lorenz SmallVector<unsigned, 16> FileIDMapping;
524bf42cfd7SJustin Bogner gatherFileIDs(FileIDMapping);
525fc05ee34SIgor Kudrin emitSourceRegions(SourceRegionFilter());
526ee02499aSAlex Lorenz
527efd319a2SVedant Kumar if (MappingRegions.empty())
528efd319a2SVedant Kumar return;
529efd319a2SVedant Kumar
5305fc8fc2dSCraig Topper CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
531ee02499aSAlex Lorenz Writer.write(OS);
532ee02499aSAlex Lorenz }
533ee02499aSAlex Lorenz };
534ee02499aSAlex Lorenz
5359fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map
536ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
537ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
538ee02499aSAlex Lorenz : public CoverageMappingBuilder,
539ee02499aSAlex Lorenz public ConstStmtVisitor<CounterCoverageMappingBuilder> {
5409fc8faf9SAdrian Prantl /// The map of statements to count values.
541ee02499aSAlex Lorenz llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
542ee02499aSAlex Lorenz
5439fc8faf9SAdrian Prantl /// A stack of currently live regions.
544bf42cfd7SJustin Bogner std::vector<SourceMappingRegion> RegionStack;
545ee02499aSAlex Lorenz
546ee02499aSAlex Lorenz CounterExpressionBuilder Builder;
547ee02499aSAlex Lorenz
5489fc8faf9SAdrian Prantl /// A location in the most recently visited file or macro.
549bf42cfd7SJustin Bogner ///
550bf42cfd7SJustin Bogner /// This is used to adjust the active source regions appropriately when
551bf42cfd7SJustin Bogner /// expressions cross file or macro boundaries.
552bf42cfd7SJustin Bogner SourceLocation MostRecentLocation;
553bf42cfd7SJustin Bogner
5549783e209SZequan Wu /// Whether the visitor at a terminate statement.
5559783e209SZequan Wu bool HasTerminateStmt = false;
5569783e209SZequan Wu
5579783e209SZequan Wu /// Gap region counter after terminate statement.
5589783e209SZequan Wu Counter GapRegionCounter;
5598046d22aSVedant Kumar
5609fc8faf9SAdrian Prantl /// Return a counter for the subtraction of \c RHS from \c LHS
subtractCounters__anon8934bc200211::CounterCoverageMappingBuilder561ce54b226SBruno Cardoso Lopes Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
562ce54b226SBruno Cardoso Lopes return Builder.subtract(LHS, RHS, Simplify);
563ee02499aSAlex Lorenz }
564ee02499aSAlex Lorenz
5659fc8faf9SAdrian Prantl /// Return a counter for the sum of \c LHS and \c RHS.
addCounters__anon8934bc200211::CounterCoverageMappingBuilder566ce54b226SBruno Cardoso Lopes Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
567ce54b226SBruno Cardoso Lopes return Builder.add(LHS, RHS, Simplify);
568ee02499aSAlex Lorenz }
569ee02499aSAlex Lorenz
addCounters__anon8934bc200211::CounterCoverageMappingBuilder570ce54b226SBruno Cardoso Lopes Counter addCounters(Counter C1, Counter C2, Counter C3,
571ce54b226SBruno Cardoso Lopes bool Simplify = true) {
572ce54b226SBruno Cardoso Lopes return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
573bf42cfd7SJustin Bogner }
574bf42cfd7SJustin Bogner
5759fc8faf9SAdrian Prantl /// Return the region counter for the given statement.
576bf42cfd7SJustin Bogner ///
577ee02499aSAlex Lorenz /// This should only be called on statements that have a dedicated counter.
getRegionCounter__anon8934bc200211::CounterCoverageMappingBuilder578bf42cfd7SJustin Bogner Counter getRegionCounter(const Stmt *S) {
579bf42cfd7SJustin Bogner return Counter::getCounter(CounterMap[S]);
580ee02499aSAlex Lorenz }
581ee02499aSAlex Lorenz
5829fc8faf9SAdrian Prantl /// Push a region onto the stack.
583bf42cfd7SJustin Bogner ///
584bf42cfd7SJustin Bogner /// Returns the index on the stack where the region was pushed. This can be
585bf42cfd7SJustin Bogner /// used with popRegions to exit a "scope", ending the region that was pushed.
pushRegion__anon8934bc200211::CounterCoverageMappingBuilder586bf42cfd7SJustin Bogner size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
5879f2967bcSAlan Phipps Optional<SourceLocation> EndLoc = None,
5889f2967bcSAlan Phipps Optional<Counter> FalseCount = None) {
5899f2967bcSAlan Phipps
590452db157SKazu Hirata if (StartLoc && !FalseCount) {
591bf42cfd7SJustin Bogner MostRecentLocation = *StartLoc;
592747b0e29SVedant Kumar }
5939f2967bcSAlan Phipps
5949783e209SZequan Wu RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc);
595ee02499aSAlex Lorenz
596bf42cfd7SJustin Bogner return RegionStack.size() - 1;
597ee02499aSAlex Lorenz }
598ee02499aSAlex Lorenz
locationDepth__anon8934bc200211::CounterCoverageMappingBuilder5990c3e3115SVedant Kumar size_t locationDepth(SourceLocation Loc) {
6000c3e3115SVedant Kumar size_t Depth = 0;
6010c3e3115SVedant Kumar while (Loc.isValid()) {
6020c3e3115SVedant Kumar Loc = getIncludeOrExpansionLoc(Loc);
6030c3e3115SVedant Kumar Depth++;
6040c3e3115SVedant Kumar }
6050c3e3115SVedant Kumar return Depth;
6060c3e3115SVedant Kumar }
6070c3e3115SVedant Kumar
6089fc8faf9SAdrian Prantl /// Pop regions from the stack into the function's list of regions.
609bf42cfd7SJustin Bogner ///
610bf42cfd7SJustin Bogner /// Adds all regions from \c ParentIndex to the top of the stack to the
611bf42cfd7SJustin Bogner /// function's \c SourceRegions.
popRegions__anon8934bc200211::CounterCoverageMappingBuilder612bf42cfd7SJustin Bogner void popRegions(size_t ParentIndex) {
613bf42cfd7SJustin Bogner assert(RegionStack.size() >= ParentIndex && "parent not in stack");
614bf42cfd7SJustin Bogner while (RegionStack.size() > ParentIndex) {
615bf42cfd7SJustin Bogner SourceMappingRegion &Region = RegionStack.back();
616bf42cfd7SJustin Bogner if (Region.hasStartLoc()) {
617a6e4358fSStephen Kelly SourceLocation StartLoc = Region.getBeginLoc();
618bf42cfd7SJustin Bogner SourceLocation EndLoc = Region.hasEndLoc()
619bf42cfd7SJustin Bogner ? Region.getEndLoc()
620bf42cfd7SJustin Bogner : RegionStack[ParentIndex].getEndLoc();
6219f2967bcSAlan Phipps bool isBranch = Region.isBranch();
6220c3e3115SVedant Kumar size_t StartDepth = locationDepth(StartLoc);
6230c3e3115SVedant Kumar size_t EndDepth = locationDepth(EndLoc);
624bf42cfd7SJustin Bogner while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
6250c3e3115SVedant Kumar bool UnnestStart = StartDepth >= EndDepth;
6260c3e3115SVedant Kumar bool UnnestEnd = EndDepth >= StartDepth;
6270c3e3115SVedant Kumar if (UnnestEnd) {
6289f2967bcSAlan Phipps // The region ends in a nested file or macro expansion. If the
6299f2967bcSAlan Phipps // region is not a branch region, create a separate region for each
6309f2967bcSAlan Phipps // expansion, and for all regions, update the EndLoc. Branch
6319f2967bcSAlan Phipps // regions should not be split in order to keep a straightforward
6329f2967bcSAlan Phipps // correspondance between the region and its associated branch
6339f2967bcSAlan Phipps // condition, even if the condition spans multiple depths.
634bf42cfd7SJustin Bogner SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
635bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
636bf42cfd7SJustin Bogner
6379f2967bcSAlan Phipps if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
6389f2967bcSAlan Phipps SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
6399f2967bcSAlan Phipps EndLoc);
640bf42cfd7SJustin Bogner
641f14b2078SJustin Bogner EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
642dceaaadfSJustin Bogner if (EndLoc.isInvalid())
6439f2967bcSAlan Phipps llvm::report_fatal_error(
6449f2967bcSAlan Phipps "File exit not handled before popRegions");
6450c3e3115SVedant Kumar EndDepth--;
646bf42cfd7SJustin Bogner }
6470c3e3115SVedant Kumar if (UnnestStart) {
6489f2967bcSAlan Phipps // The region ends in a nested file or macro expansion. If the
6499f2967bcSAlan Phipps // region is not a branch region, create a separate region for each
6509f2967bcSAlan Phipps // expansion, and for all regions, update the StartLoc. Branch
6519f2967bcSAlan Phipps // regions should not be split in order to keep a straightforward
6529f2967bcSAlan Phipps // correspondance between the region and its associated branch
6539f2967bcSAlan Phipps // condition, even if the condition spans multiple depths.
6540c3e3115SVedant Kumar SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
6550c3e3115SVedant Kumar assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
6560c3e3115SVedant Kumar
6579f2967bcSAlan Phipps if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
6589f2967bcSAlan Phipps SourceRegions.emplace_back(Region.getCounter(), StartLoc,
6599f2967bcSAlan Phipps NestedLoc);
6600c3e3115SVedant Kumar
6610c3e3115SVedant Kumar StartLoc = getIncludeOrExpansionLoc(StartLoc);
6620c3e3115SVedant Kumar if (StartLoc.isInvalid())
6639f2967bcSAlan Phipps llvm::report_fatal_error(
6649f2967bcSAlan Phipps "File exit not handled before popRegions");
6650c3e3115SVedant Kumar StartDepth--;
6660c3e3115SVedant Kumar }
6670c3e3115SVedant Kumar }
6680c3e3115SVedant Kumar Region.setStartLoc(StartLoc);
669bf42cfd7SJustin Bogner Region.setEndLoc(EndLoc);
670bf42cfd7SJustin Bogner
6719f2967bcSAlan Phipps if (!isBranch) {
672bf42cfd7SJustin Bogner MostRecentLocation = EndLoc;
6739f2967bcSAlan Phipps // If this region happens to span an entire expansion, we need to
6749f2967bcSAlan Phipps // make sure we don't overlap the parent region with it.
675bf42cfd7SJustin Bogner if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
676bf42cfd7SJustin Bogner EndLoc == getEndOfFileOrMacro(EndLoc))
677bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
6789f2967bcSAlan Phipps }
679bf42cfd7SJustin Bogner
680a6e4358fSStephen Kelly assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
681fa8fa044SVedant Kumar assert(SpellingRegion(SM, Region).isInSourceOrder());
682f36a5c4aSCraig Topper SourceRegions.push_back(Region);
683bf42cfd7SJustin Bogner }
684bf42cfd7SJustin Bogner RegionStack.pop_back();
685bf42cfd7SJustin Bogner }
686ee02499aSAlex Lorenz }
687ee02499aSAlex Lorenz
6889fc8faf9SAdrian Prantl /// Return the currently active region.
getRegion__anon8934bc200211::CounterCoverageMappingBuilder689bf42cfd7SJustin Bogner SourceMappingRegion &getRegion() {
690bf42cfd7SJustin Bogner assert(!RegionStack.empty() && "statement has no region");
691bf42cfd7SJustin Bogner return RegionStack.back();
692ee02499aSAlex Lorenz }
693ee02499aSAlex Lorenz
6947225a261SVedant Kumar /// Propagate counts through the children of \p S if \p VisitChildren is true.
6957225a261SVedant Kumar /// Otherwise, only emit a count for \p S itself.
propagateCounts__anon8934bc200211::CounterCoverageMappingBuilder6967225a261SVedant Kumar Counter propagateCounts(Counter TopCount, const Stmt *S,
6977225a261SVedant Kumar bool VisitChildren = true) {
6987838696eSVedant Kumar SourceLocation StartLoc = getStart(S);
6997838696eSVedant Kumar SourceLocation EndLoc = getEnd(S);
7007838696eSVedant Kumar size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
7017225a261SVedant Kumar if (VisitChildren)
702bf42cfd7SJustin Bogner Visit(S);
703bf42cfd7SJustin Bogner Counter ExitCount = getRegion().getCounter();
704bf42cfd7SJustin Bogner popRegions(Index);
70539f01975SVedant Kumar
70639f01975SVedant Kumar // The statement may be spanned by an expansion. Make sure we handle a file
70739f01975SVedant Kumar // exit out of this expansion before moving to the next statement.
708f2ceec48SStephen Kelly if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
7097838696eSVedant Kumar MostRecentLocation = EndLoc;
71039f01975SVedant Kumar
711bf42cfd7SJustin Bogner return ExitCount;
712ee02499aSAlex Lorenz }
713ee02499aSAlex Lorenz
7149f2967bcSAlan Phipps /// Determine whether the given condition can be constant folded.
ConditionFoldsToBool__anon8934bc200211::CounterCoverageMappingBuilder7159f2967bcSAlan Phipps bool ConditionFoldsToBool(const Expr *Cond) {
7169f2967bcSAlan Phipps Expr::EvalResult Result;
7179f2967bcSAlan Phipps return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
7189f2967bcSAlan Phipps }
7199f2967bcSAlan Phipps
7209f2967bcSAlan Phipps /// Create a Branch Region around an instrumentable condition for coverage
7219f2967bcSAlan Phipps /// and add it to the function's SourceRegions. A branch region tracks a
7229f2967bcSAlan Phipps /// "True" counter and a "False" counter for boolean expressions that
7239f2967bcSAlan Phipps /// result in the generation of a branch.
createBranchRegion__anon8934bc200211::CounterCoverageMappingBuilder7249f2967bcSAlan Phipps void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) {
7259f2967bcSAlan Phipps // Check for NULL conditions.
7269f2967bcSAlan Phipps if (!C)
7279f2967bcSAlan Phipps return;
7289f2967bcSAlan Phipps
7299f2967bcSAlan Phipps // Ensure we are an instrumentable condition (i.e. no "&&" or "||"). Push
7309f2967bcSAlan Phipps // region onto RegionStack but immediately pop it (which adds it to the
7319f2967bcSAlan Phipps // function's SourceRegions) because it doesn't apply to any other source
7329f2967bcSAlan Phipps // code other than the Condition.
7339f2967bcSAlan Phipps if (CodeGenFunction::isInstrumentedCondition(C)) {
7349f2967bcSAlan Phipps // If a condition can fold to true or false, the corresponding branch
7359f2967bcSAlan Phipps // will be removed. Create a region with both counters hard-coded to
7369f2967bcSAlan Phipps // zero. This allows us to visualize them in a special way.
7379f2967bcSAlan Phipps // Alternatively, we can prevent any optimization done via
7389f2967bcSAlan Phipps // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
7399f2967bcSAlan Phipps // CodeGenFunction.c always returns false, but that is very heavy-handed.
7409f2967bcSAlan Phipps if (ConditionFoldsToBool(C))
7419f2967bcSAlan Phipps popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
7429f2967bcSAlan Phipps Counter::getZero()));
7439f2967bcSAlan Phipps else
7449f2967bcSAlan Phipps // Otherwise, create a region with the True counter and False counter.
7459f2967bcSAlan Phipps popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt));
7469f2967bcSAlan Phipps }
7479f2967bcSAlan Phipps }
7489f2967bcSAlan Phipps
7499f2967bcSAlan Phipps /// Create a Branch Region around a SwitchCase for code coverage
7509f2967bcSAlan Phipps /// and add it to the function's SourceRegions.
createSwitchCaseRegion__anon8934bc200211::CounterCoverageMappingBuilder7519f2967bcSAlan Phipps void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
7529f2967bcSAlan Phipps Counter FalseCnt) {
7539f2967bcSAlan Phipps // Push region onto RegionStack but immediately pop it (which adds it to
7549f2967bcSAlan Phipps // the function's SourceRegions) because it doesn't apply to any other
7559f2967bcSAlan Phipps // source other than the SwitchCase.
7569f2967bcSAlan Phipps popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
7579f2967bcSAlan Phipps }
7589f2967bcSAlan Phipps
7599fc8faf9SAdrian Prantl /// Check whether a region with bounds \c StartLoc and \c EndLoc
7600a7c9d11SIgor Kudrin /// is already added to \c SourceRegions.
isRegionAlreadyAdded__anon8934bc200211::CounterCoverageMappingBuilder7619f2967bcSAlan Phipps bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
7629f2967bcSAlan Phipps bool isBranch = false) {
7634bd46501SKazu Hirata return llvm::any_of(
7644bd46501SKazu Hirata llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) {
765a6e4358fSStephen Kelly return Region.getBeginLoc() == StartLoc &&
7664bd46501SKazu Hirata Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
7670a7c9d11SIgor Kudrin });
7680a7c9d11SIgor Kudrin }
7690a7c9d11SIgor Kudrin
7709fc8faf9SAdrian Prantl /// Adjust the most recently visited location to \c EndLoc.
771bf42cfd7SJustin Bogner ///
772bf42cfd7SJustin Bogner /// This should be used after visiting any statements in non-source order.
adjustForOutOfOrderTraversal__anon8934bc200211::CounterCoverageMappingBuilder773bf42cfd7SJustin Bogner void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
774bf42cfd7SJustin Bogner MostRecentLocation = EndLoc;
7750a7c9d11SIgor Kudrin // The code region for a whole macro is created in handleFileExit() when
7760a7c9d11SIgor Kudrin // it detects exiting of the virtual file of that macro. If we visited
7770a7c9d11SIgor Kudrin // statements in non-source order, we might already have such a region
7780a7c9d11SIgor Kudrin // added, for example, if a body of a loop is divided among multiple
7790a7c9d11SIgor Kudrin // macros. Avoid adding duplicate regions in such case.
78096ae73f7SJustin Bogner if (getRegion().hasEndLoc() &&
7810a7c9d11SIgor Kudrin MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
7820a7c9d11SIgor Kudrin isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
7839f2967bcSAlan Phipps MostRecentLocation, getRegion().isBranch()))
784bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
785ee02499aSAlex Lorenz }
786ee02499aSAlex Lorenz
7879fc8faf9SAdrian Prantl /// Adjust regions and state when \c NewLoc exits a file.
788bf42cfd7SJustin Bogner ///
789bf42cfd7SJustin Bogner /// If moving from our most recently tracked location to \c NewLoc exits any
790bf42cfd7SJustin Bogner /// files, this adjusts our current region stack and creates the file regions
791bf42cfd7SJustin Bogner /// for the exited file.
handleFileExit__anon8934bc200211::CounterCoverageMappingBuilder792bf42cfd7SJustin Bogner void handleFileExit(SourceLocation NewLoc) {
793e44dd6dbSJustin Bogner if (NewLoc.isInvalid() ||
794e44dd6dbSJustin Bogner SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
795bf42cfd7SJustin Bogner return;
796bf42cfd7SJustin Bogner
797bf42cfd7SJustin Bogner // If NewLoc is not in a file that contains MostRecentLocation, walk up to
798bf42cfd7SJustin Bogner // find the common ancestor.
799bf42cfd7SJustin Bogner SourceLocation LCA = NewLoc;
800bf42cfd7SJustin Bogner FileID ParentFile = SM.getFileID(LCA);
801bf42cfd7SJustin Bogner while (!isNestedIn(MostRecentLocation, ParentFile)) {
802bf42cfd7SJustin Bogner LCA = getIncludeOrExpansionLoc(LCA);
803bf42cfd7SJustin Bogner if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
804bf42cfd7SJustin Bogner // Since there isn't a common ancestor, no file was exited. We just need
805bf42cfd7SJustin Bogner // to adjust our location to the new file.
806bf42cfd7SJustin Bogner MostRecentLocation = NewLoc;
807bf42cfd7SJustin Bogner return;
808bf42cfd7SJustin Bogner }
809bf42cfd7SJustin Bogner ParentFile = SM.getFileID(LCA);
810ee02499aSAlex Lorenz }
811ee02499aSAlex Lorenz
812bf42cfd7SJustin Bogner llvm::SmallSet<SourceLocation, 8> StartLocs;
813bf42cfd7SJustin Bogner Optional<Counter> ParentCounter;
81457d3f145SPete Cooper for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
81557d3f145SPete Cooper if (!I.hasStartLoc())
816bf42cfd7SJustin Bogner continue;
817a6e4358fSStephen Kelly SourceLocation Loc = I.getBeginLoc();
818bf42cfd7SJustin Bogner if (!isNestedIn(Loc, ParentFile)) {
81957d3f145SPete Cooper ParentCounter = I.getCounter();
820bf42cfd7SJustin Bogner break;
821ee02499aSAlex Lorenz }
822bf42cfd7SJustin Bogner
823bf42cfd7SJustin Bogner while (!SM.isInFileID(Loc, ParentFile)) {
824bf42cfd7SJustin Bogner // The most nested region for each start location is the one with the
825bf42cfd7SJustin Bogner // correct count. We avoid creating redundant regions by stopping once
826bf42cfd7SJustin Bogner // we've seen this region.
8279f2967bcSAlan Phipps if (StartLocs.insert(Loc).second) {
8289f2967bcSAlan Phipps if (I.isBranch())
8299f2967bcSAlan Phipps SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc,
8309f2967bcSAlan Phipps getEndOfFileOrMacro(Loc), I.isBranch());
8319f2967bcSAlan Phipps else
83257d3f145SPete Cooper SourceRegions.emplace_back(I.getCounter(), Loc,
833bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc));
8349f2967bcSAlan Phipps }
835bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc);
836ee02499aSAlex Lorenz }
83757d3f145SPete Cooper I.setStartLoc(getPreciseTokenLocEnd(Loc));
838bf42cfd7SJustin Bogner }
839bf42cfd7SJustin Bogner
840bf42cfd7SJustin Bogner if (ParentCounter) {
841bf42cfd7SJustin Bogner // If the file is contained completely by another region and doesn't
842bf42cfd7SJustin Bogner // immediately start its own region, the whole file gets a region
843bf42cfd7SJustin Bogner // corresponding to the parent.
844bf42cfd7SJustin Bogner SourceLocation Loc = MostRecentLocation;
845bf42cfd7SJustin Bogner while (isNestedIn(Loc, ParentFile)) {
846bf42cfd7SJustin Bogner SourceLocation FileStart = getStartOfFileOrMacro(Loc);
847fa8fa044SVedant Kumar if (StartLocs.insert(FileStart).second) {
848bf42cfd7SJustin Bogner SourceRegions.emplace_back(*ParentCounter, FileStart,
849bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc));
850fa8fa044SVedant Kumar assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
851fa8fa044SVedant Kumar }
852bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc);
853bf42cfd7SJustin Bogner }
854bf42cfd7SJustin Bogner }
855bf42cfd7SJustin Bogner
856bf42cfd7SJustin Bogner MostRecentLocation = NewLoc;
857bf42cfd7SJustin Bogner }
858bf42cfd7SJustin Bogner
8599fc8faf9SAdrian Prantl /// Ensure that \c S is included in the current region.
extendRegion__anon8934bc200211::CounterCoverageMappingBuilder860bf42cfd7SJustin Bogner void extendRegion(const Stmt *S) {
861bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion();
862bf42cfd7SJustin Bogner SourceLocation StartLoc = getStart(S);
863bf42cfd7SJustin Bogner
864bf42cfd7SJustin Bogner handleFileExit(StartLoc);
865bf42cfd7SJustin Bogner if (!Region.hasStartLoc())
866bf42cfd7SJustin Bogner Region.setStartLoc(StartLoc);
867bf42cfd7SJustin Bogner }
868bf42cfd7SJustin Bogner
8699fc8faf9SAdrian Prantl /// Mark \c S as a terminator, starting a zero region.
terminateRegion__anon8934bc200211::CounterCoverageMappingBuilder870bf42cfd7SJustin Bogner void terminateRegion(const Stmt *S) {
871bf42cfd7SJustin Bogner extendRegion(S);
872bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion();
8738046d22aSVedant Kumar SourceLocation EndLoc = getEnd(S);
874bf42cfd7SJustin Bogner if (!Region.hasEndLoc())
8758046d22aSVedant Kumar Region.setEndLoc(EndLoc);
876bf42cfd7SJustin Bogner pushRegion(Counter::getZero());
8779783e209SZequan Wu HasTerminateStmt = true;
878bf42cfd7SJustin Bogner }
879ee02499aSAlex Lorenz
880fa8fa044SVedant Kumar /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
findGapAreaBetween__anon8934bc200211::CounterCoverageMappingBuilder881fa8fa044SVedant Kumar Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
882fa8fa044SVedant Kumar SourceLocation BeforeLoc) {
8839783e209SZequan Wu // If AfterLoc is in function-like macro, use the right parenthesis
8849783e209SZequan Wu // location.
8859783e209SZequan Wu if (AfterLoc.isMacroID()) {
8869783e209SZequan Wu FileID FID = SM.getFileID(AfterLoc);
8879783e209SZequan Wu const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
8889783e209SZequan Wu if (EI->isFunctionMacroExpansion())
8899783e209SZequan Wu AfterLoc = EI->getExpansionLocEnd();
8909783e209SZequan Wu }
8919783e209SZequan Wu
892d83511ddSZequan Wu size_t StartDepth = locationDepth(AfterLoc);
893d83511ddSZequan Wu size_t EndDepth = locationDepth(BeforeLoc);
894d83511ddSZequan Wu while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
895d83511ddSZequan Wu bool UnnestStart = StartDepth >= EndDepth;
896d83511ddSZequan Wu bool UnnestEnd = EndDepth >= StartDepth;
897d83511ddSZequan Wu if (UnnestEnd) {
8984544a63bSSterling Augustine assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
8994544a63bSSterling Augustine BeforeLoc));
900d83511ddSZequan Wu
901d83511ddSZequan Wu BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
902d83511ddSZequan Wu assert(BeforeLoc.isValid());
903d83511ddSZequan Wu EndDepth--;
904d83511ddSZequan Wu }
905d83511ddSZequan Wu if (UnnestStart) {
906fc97a63dSSterling Augustine assert(SM.isWrittenInSameFile(AfterLoc,
907fc97a63dSSterling Augustine getEndOfFileOrMacro(AfterLoc)));
908d83511ddSZequan Wu
909d83511ddSZequan Wu AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
910d83511ddSZequan Wu assert(AfterLoc.isValid());
911d83511ddSZequan Wu AfterLoc = getPreciseTokenLocEnd(AfterLoc);
912d83511ddSZequan Wu assert(AfterLoc.isValid());
913d83511ddSZequan Wu StartDepth--;
914d83511ddSZequan Wu }
915d83511ddSZequan Wu }
916d83511ddSZequan Wu AfterLoc = getPreciseTokenLocEnd(AfterLoc);
9179500a720SZequan Wu // If the start and end locations of the gap are both within the same macro
9189500a720SZequan Wu // file, the range may not be in source order.
9199500a720SZequan Wu if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
9209500a720SZequan Wu return None;
9219783e209SZequan Wu if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
9229783e209SZequan Wu !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
923fa8fa044SVedant Kumar return None;
924fa8fa044SVedant Kumar return {{AfterLoc, BeforeLoc}};
925fa8fa044SVedant Kumar }
926fa8fa044SVedant Kumar
9272e8c8759SVedant Kumar /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
fillGapAreaWithCount__anon8934bc200211::CounterCoverageMappingBuilder9282e8c8759SVedant Kumar void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
9292e8c8759SVedant Kumar Counter Count) {
930fa8fa044SVedant Kumar if (StartLoc == EndLoc)
9312e8c8759SVedant Kumar return;
932fa8fa044SVedant Kumar assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
9332e8c8759SVedant Kumar handleFileExit(StartLoc);
9342e8c8759SVedant Kumar size_t Index = pushRegion(Count, StartLoc, EndLoc);
9352e8c8759SVedant Kumar getRegion().setGap(true);
9362e8c8759SVedant Kumar handleFileExit(EndLoc);
9372e8c8759SVedant Kumar popRegions(Index);
9382e8c8759SVedant Kumar }
9392e8c8759SVedant Kumar
9409fc8faf9SAdrian Prantl /// Keep counts of breaks and continues inside loops.
941ee02499aSAlex Lorenz struct BreakContinue {
942ee02499aSAlex Lorenz Counter BreakCount;
943ee02499aSAlex Lorenz Counter ContinueCount;
944ee02499aSAlex Lorenz };
945ee02499aSAlex Lorenz SmallVector<BreakContinue, 8> BreakContinueStack;
946ee02499aSAlex Lorenz
CounterCoverageMappingBuilder__anon8934bc200211::CounterCoverageMappingBuilder947ee02499aSAlex Lorenz CounterCoverageMappingBuilder(
948ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM,
949e5ee6c58SJustin Bogner llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
950ee02499aSAlex Lorenz const LangOptions &LangOpts)
9519783e209SZequan Wu : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
952ee02499aSAlex Lorenz
9539fc8faf9SAdrian Prantl /// Write the mapping data to the output stream
write__anon8934bc200211::CounterCoverageMappingBuilder954ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) {
955ee02499aSAlex Lorenz llvm::SmallVector<unsigned, 8> VirtualFileMapping;
956bf42cfd7SJustin Bogner gatherFileIDs(VirtualFileMapping);
957fc05ee34SIgor Kudrin SourceRegionFilter Filter = emitExpansionRegions();
958fc05ee34SIgor Kudrin emitSourceRegions(Filter);
959ee02499aSAlex Lorenz gatherSkippedRegions();
960ee02499aSAlex Lorenz
961efd319a2SVedant Kumar if (MappingRegions.empty())
962efd319a2SVedant Kumar return;
963efd319a2SVedant Kumar
9644da909b2SJustin Bogner CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
9654da909b2SJustin Bogner MappingRegions);
966ee02499aSAlex Lorenz Writer.write(OS);
967ee02499aSAlex Lorenz }
968ee02499aSAlex Lorenz
VisitStmt__anon8934bc200211::CounterCoverageMappingBuilder969ee02499aSAlex Lorenz void VisitStmt(const Stmt *S) {
970f2ceec48SStephen Kelly if (S->getBeginLoc().isValid())
971bf42cfd7SJustin Bogner extendRegion(S);
9729783e209SZequan Wu const Stmt *LastStmt = nullptr;
9739783e209SZequan Wu bool SaveTerminateStmt = HasTerminateStmt;
9749783e209SZequan Wu HasTerminateStmt = false;
9759783e209SZequan Wu GapRegionCounter = Counter::getZero();
976642f173aSBenjamin Kramer for (const Stmt *Child : S->children())
9779783e209SZequan Wu if (Child) {
9789783e209SZequan Wu // If last statement contains terminate statements, add a gap area
9799783e209SZequan Wu // between the two statements. Skipping attributed statements, because
9809783e209SZequan Wu // they don't have valid start location.
981d0ac215dSKazu Hirata if (LastStmt && HasTerminateStmt && !isa<AttributedStmt>(Child)) {
9829783e209SZequan Wu auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
9839783e209SZequan Wu if (Gap)
9849783e209SZequan Wu fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
9859783e209SZequan Wu GapRegionCounter);
9869783e209SZequan Wu SaveTerminateStmt = true;
9879783e209SZequan Wu HasTerminateStmt = false;
9889783e209SZequan Wu }
989642f173aSBenjamin Kramer this->Visit(Child);
9909783e209SZequan Wu LastStmt = Child;
9919783e209SZequan Wu }
9929783e209SZequan Wu if (SaveTerminateStmt)
9939783e209SZequan Wu HasTerminateStmt = true;
994bf42cfd7SJustin Bogner handleFileExit(getEnd(S));
995ee02499aSAlex Lorenz }
996ee02499aSAlex Lorenz
VisitDecl__anon8934bc200211::CounterCoverageMappingBuilder997ee02499aSAlex Lorenz void VisitDecl(const Decl *D) {
998bf42cfd7SJustin Bogner Stmt *Body = D->getBody();
999efd319a2SVedant Kumar
1000efd319a2SVedant Kumar // Do not propagate region counts into system headers.
1001efd319a2SVedant Kumar if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1002efd319a2SVedant Kumar return;
1003efd319a2SVedant Kumar
10047225a261SVedant Kumar // Do not visit the artificial children nodes of defaulted methods. The
10057225a261SVedant Kumar // lexer may not be able to report back precise token end locations for
10067225a261SVedant Kumar // these children nodes (llvm.org/PR39822), and moreover users will not be
10077225a261SVedant Kumar // able to see coverage for them.
10087225a261SVedant Kumar bool Defaulted = false;
10097225a261SVedant Kumar if (auto *Method = dyn_cast<CXXMethodDecl>(D))
10107225a261SVedant Kumar Defaulted = Method->isDefaulted();
10117225a261SVedant Kumar
10127225a261SVedant Kumar propagateCounts(getRegionCounter(Body), Body,
10137225a261SVedant Kumar /*VisitChildren=*/!Defaulted);
1014747b0e29SVedant Kumar assert(RegionStack.empty() && "Regions entered but never exited");
1015341bf429SVedant Kumar }
1016ee02499aSAlex Lorenz
VisitReturnStmt__anon8934bc200211::CounterCoverageMappingBuilder1017ee02499aSAlex Lorenz void VisitReturnStmt(const ReturnStmt *S) {
1018bf42cfd7SJustin Bogner extendRegion(S);
1019ee02499aSAlex Lorenz if (S->getRetValue())
1020ee02499aSAlex Lorenz Visit(S->getRetValue());
1021bf42cfd7SJustin Bogner terminateRegion(S);
1022ee02499aSAlex Lorenz }
1023ee02499aSAlex Lorenz
VisitCoroutineBodyStmt__anon8934bc200211::CounterCoverageMappingBuilder1024565e37c7SXun Li void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1025565e37c7SXun Li extendRegion(S);
1026565e37c7SXun Li Visit(S->getBody());
1027565e37c7SXun Li }
1028565e37c7SXun Li
VisitCoreturnStmt__anon8934bc200211::CounterCoverageMappingBuilder1029565e37c7SXun Li void VisitCoreturnStmt(const CoreturnStmt *S) {
1030565e37c7SXun Li extendRegion(S);
1031565e37c7SXun Li if (S->getOperand())
1032565e37c7SXun Li Visit(S->getOperand());
1033565e37c7SXun Li terminateRegion(S);
1034565e37c7SXun Li }
1035565e37c7SXun Li
VisitCXXThrowExpr__anon8934bc200211::CounterCoverageMappingBuilder1036f959febfSJustin Bogner void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1037f959febfSJustin Bogner extendRegion(E);
1038f959febfSJustin Bogner if (E->getSubExpr())
1039f959febfSJustin Bogner Visit(E->getSubExpr());
1040f959febfSJustin Bogner terminateRegion(E);
1041f959febfSJustin Bogner }
1042f959febfSJustin Bogner
VisitGotoStmt__anon8934bc200211::CounterCoverageMappingBuilder1043bf42cfd7SJustin Bogner void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1044ee02499aSAlex Lorenz
VisitLabelStmt__anon8934bc200211::CounterCoverageMappingBuilder1045ee02499aSAlex Lorenz void VisitLabelStmt(const LabelStmt *S) {
10468046d22aSVedant Kumar Counter LabelCount = getRegionCounter(S);
1047bf42cfd7SJustin Bogner SourceLocation Start = getStart(S);
1048bf42cfd7SJustin Bogner // We can't extendRegion here or we risk overlapping with our new region.
1049bf42cfd7SJustin Bogner handleFileExit(Start);
10508046d22aSVedant Kumar pushRegion(LabelCount, Start);
1051ee02499aSAlex Lorenz Visit(S->getSubStmt());
1052ee02499aSAlex Lorenz }
1053ee02499aSAlex Lorenz
VisitBreakStmt__anon8934bc200211::CounterCoverageMappingBuilder1054ee02499aSAlex Lorenz void VisitBreakStmt(const BreakStmt *S) {
1055ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1056ee02499aSAlex Lorenz BreakContinueStack.back().BreakCount = addCounters(
1057bf42cfd7SJustin Bogner BreakContinueStack.back().BreakCount, getRegion().getCounter());
10587f53fbfcSEli Friedman // FIXME: a break in a switch should terminate regions for all preceding
10597f53fbfcSEli Friedman // case statements, not just the most recent one.
1060bf42cfd7SJustin Bogner terminateRegion(S);
1061ee02499aSAlex Lorenz }
1062ee02499aSAlex Lorenz
VisitContinueStmt__anon8934bc200211::CounterCoverageMappingBuilder1063ee02499aSAlex Lorenz void VisitContinueStmt(const ContinueStmt *S) {
1064ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1065ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters(
1066bf42cfd7SJustin Bogner BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1067bf42cfd7SJustin Bogner terminateRegion(S);
1068ee02499aSAlex Lorenz }
1069ee02499aSAlex Lorenz
VisitCallExpr__anon8934bc200211::CounterCoverageMappingBuilder1070181dfe4cSEli Friedman void VisitCallExpr(const CallExpr *E) {
1071181dfe4cSEli Friedman VisitStmt(E);
1072181dfe4cSEli Friedman
1073181dfe4cSEli Friedman // Terminate the region when we hit a noreturn function.
1074181dfe4cSEli Friedman // (This is helpful dealing with switch statements.)
1075181dfe4cSEli Friedman QualType CalleeType = E->getCallee()->getType();
1076181dfe4cSEli Friedman if (getFunctionExtInfo(*CalleeType).getNoReturn())
1077181dfe4cSEli Friedman terminateRegion(E);
1078181dfe4cSEli Friedman }
1079181dfe4cSEli Friedman
VisitWhileStmt__anon8934bc200211::CounterCoverageMappingBuilder1080ee02499aSAlex Lorenz void VisitWhileStmt(const WhileStmt *S) {
1081bf42cfd7SJustin Bogner extendRegion(S);
1082ee02499aSAlex Lorenz
1083bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter();
1084bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S);
1085bf42cfd7SJustin Bogner
1086bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count.
1087bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue());
1088bf42cfd7SJustin Bogner extendRegion(S->getBody());
1089bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1090ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val();
1091bf42cfd7SJustin Bogner
10929783e209SZequan Wu bool BodyHasTerminateStmt = HasTerminateStmt;
10939783e209SZequan Wu HasTerminateStmt = false;
10949783e209SZequan Wu
1095bf42cfd7SJustin Bogner // Go back to handle the condition.
1096bf42cfd7SJustin Bogner Counter CondCount =
1097bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1098bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond());
1099bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S));
1100bf42cfd7SJustin Bogner
1101fa8fa044SVedant Kumar // The body count applies to the area immediately after the increment.
1102d83511ddSZequan Wu auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1103fa8fa044SVedant Kumar if (Gap)
1104fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1105fa8fa044SVedant Kumar
1106bf42cfd7SJustin Bogner Counter OutCount =
1107bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
11089783e209SZequan Wu if (OutCount != ParentCount) {
1109bf42cfd7SJustin Bogner pushRegion(OutCount);
11109783e209SZequan Wu GapRegionCounter = OutCount;
11119783e209SZequan Wu if (BodyHasTerminateStmt)
11129783e209SZequan Wu HasTerminateStmt = true;
11139783e209SZequan Wu }
11149f2967bcSAlan Phipps
11159f2967bcSAlan Phipps // Create Branch Region around condition.
11169f2967bcSAlan Phipps createBranchRegion(S->getCond(), BodyCount,
11179f2967bcSAlan Phipps subtractCounters(CondCount, BodyCount));
1118ee02499aSAlex Lorenz }
1119ee02499aSAlex Lorenz
VisitDoStmt__anon8934bc200211::CounterCoverageMappingBuilder1120ee02499aSAlex Lorenz void VisitDoStmt(const DoStmt *S) {
1121bf42cfd7SJustin Bogner extendRegion(S);
1122ee02499aSAlex Lorenz
1123bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter();
1124bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S);
1125bf42cfd7SJustin Bogner
1126bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue());
1127bf42cfd7SJustin Bogner extendRegion(S->getBody());
1128bf42cfd7SJustin Bogner Counter BackedgeCount =
1129bf42cfd7SJustin Bogner propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1130ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val();
1131bf42cfd7SJustin Bogner
11329783e209SZequan Wu bool BodyHasTerminateStmt = HasTerminateStmt;
11339783e209SZequan Wu HasTerminateStmt = false;
11349783e209SZequan Wu
1135bf42cfd7SJustin Bogner Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1136bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond());
1137bf42cfd7SJustin Bogner
1138bf42cfd7SJustin Bogner Counter OutCount =
1139bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
11409783e209SZequan Wu if (OutCount != ParentCount) {
1141bf42cfd7SJustin Bogner pushRegion(OutCount);
11429783e209SZequan Wu GapRegionCounter = OutCount;
11439783e209SZequan Wu }
11449f2967bcSAlan Phipps
11459f2967bcSAlan Phipps // Create Branch Region around condition.
11469f2967bcSAlan Phipps createBranchRegion(S->getCond(), BodyCount,
11479f2967bcSAlan Phipps subtractCounters(CondCount, BodyCount));
11489783e209SZequan Wu
11499783e209SZequan Wu if (BodyHasTerminateStmt)
11509783e209SZequan Wu HasTerminateStmt = true;
1151ee02499aSAlex Lorenz }
1152ee02499aSAlex Lorenz
VisitForStmt__anon8934bc200211::CounterCoverageMappingBuilder1153ee02499aSAlex Lorenz void VisitForStmt(const ForStmt *S) {
1154bf42cfd7SJustin Bogner extendRegion(S);
1155ee02499aSAlex Lorenz if (S->getInit())
1156ee02499aSAlex Lorenz Visit(S->getInit());
1157ee02499aSAlex Lorenz
1158bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter();
1159bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S);
1160bf42cfd7SJustin Bogner
11613e2ae49aSVedant Kumar // The loop increment may contain a break or continue.
11623e2ae49aSVedant Kumar if (S->getInc())
11633e2ae49aSVedant Kumar BreakContinueStack.emplace_back();
11643e2ae49aSVedant Kumar
1165bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count.
11663e2ae49aSVedant Kumar BreakContinueStack.emplace_back();
1167bf42cfd7SJustin Bogner extendRegion(S->getBody());
1168bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
11693e2ae49aSVedant Kumar BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1170ee02499aSAlex Lorenz
11719783e209SZequan Wu bool BodyHasTerminateStmt = HasTerminateStmt;
11729783e209SZequan Wu HasTerminateStmt = false;
11739783e209SZequan Wu
1174ee02499aSAlex Lorenz // The increment is essentially part of the body but it needs to include
1175ee02499aSAlex Lorenz // the count for all the continue statements.
11763e2ae49aSVedant Kumar BreakContinue IncrementBC;
11773e2ae49aSVedant Kumar if (const Stmt *Inc = S->getInc()) {
11783e2ae49aSVedant Kumar propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
11793e2ae49aSVedant Kumar IncrementBC = BreakContinueStack.pop_back_val();
11803e2ae49aSVedant Kumar }
1181bf42cfd7SJustin Bogner
1182bf42cfd7SJustin Bogner // Go back to handle the condition.
11833e2ae49aSVedant Kumar Counter CondCount = addCounters(
11843e2ae49aSVedant Kumar addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
11853e2ae49aSVedant Kumar IncrementBC.ContinueCount);
1186bf42cfd7SJustin Bogner if (const Expr *Cond = S->getCond()) {
1187bf42cfd7SJustin Bogner propagateCounts(CondCount, Cond);
1188bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S));
1189ee02499aSAlex Lorenz }
1190ee02499aSAlex Lorenz
1191fa8fa044SVedant Kumar // The body count applies to the area immediately after the increment.
1192d83511ddSZequan Wu auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1193fa8fa044SVedant Kumar if (Gap)
1194fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1195fa8fa044SVedant Kumar
11963e2ae49aSVedant Kumar Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
11973e2ae49aSVedant Kumar subtractCounters(CondCount, BodyCount));
11989783e209SZequan Wu if (OutCount != ParentCount) {
1199bf42cfd7SJustin Bogner pushRegion(OutCount);
12009783e209SZequan Wu GapRegionCounter = OutCount;
12019783e209SZequan Wu if (BodyHasTerminateStmt)
12029783e209SZequan Wu HasTerminateStmt = true;
12039783e209SZequan Wu }
12049f2967bcSAlan Phipps
12059f2967bcSAlan Phipps // Create Branch Region around condition.
12069f2967bcSAlan Phipps createBranchRegion(S->getCond(), BodyCount,
12079f2967bcSAlan Phipps subtractCounters(CondCount, BodyCount));
1208ee02499aSAlex Lorenz }
1209ee02499aSAlex Lorenz
VisitCXXForRangeStmt__anon8934bc200211::CounterCoverageMappingBuilder1210ee02499aSAlex Lorenz void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1211bf42cfd7SJustin Bogner extendRegion(S);
12128baa5001SRichard Smith if (S->getInit())
12138baa5001SRichard Smith Visit(S->getInit());
1214bf42cfd7SJustin Bogner Visit(S->getLoopVarStmt());
1215ee02499aSAlex Lorenz Visit(S->getRangeStmt());
1216bf42cfd7SJustin Bogner
1217bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter();
1218bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S);
1219bf42cfd7SJustin Bogner
1220ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue());
1221bf42cfd7SJustin Bogner extendRegion(S->getBody());
1222bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1223ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val();
1224bf42cfd7SJustin Bogner
12259783e209SZequan Wu bool BodyHasTerminateStmt = HasTerminateStmt;
12269783e209SZequan Wu HasTerminateStmt = false;
12279783e209SZequan Wu
1228fa8fa044SVedant Kumar // The body count applies to the area immediately after the range.
1229d83511ddSZequan Wu auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1230fa8fa044SVedant Kumar if (Gap)
1231fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1232fa8fa044SVedant Kumar
12331587432dSJustin Bogner Counter LoopCount =
12341587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
12351587432dSJustin Bogner Counter OutCount =
12361587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
12379783e209SZequan Wu if (OutCount != ParentCount) {
1238bf42cfd7SJustin Bogner pushRegion(OutCount);
12399783e209SZequan Wu GapRegionCounter = OutCount;
12409783e209SZequan Wu if (BodyHasTerminateStmt)
12419783e209SZequan Wu HasTerminateStmt = true;
12429783e209SZequan Wu }
12439f2967bcSAlan Phipps
12449f2967bcSAlan Phipps // Create Branch Region around condition.
12459f2967bcSAlan Phipps createBranchRegion(S->getCond(), BodyCount,
12469f2967bcSAlan Phipps subtractCounters(LoopCount, BodyCount));
1247ee02499aSAlex Lorenz }
1248ee02499aSAlex Lorenz
VisitObjCForCollectionStmt__anon8934bc200211::CounterCoverageMappingBuilder1249ee02499aSAlex Lorenz void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1250bf42cfd7SJustin Bogner extendRegion(S);
1251ee02499aSAlex Lorenz Visit(S->getElement());
1252bf42cfd7SJustin Bogner
1253bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter();
1254bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S);
1255bf42cfd7SJustin Bogner
1256ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue());
1257bf42cfd7SJustin Bogner extendRegion(S->getBody());
1258bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1259ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val();
1260bf42cfd7SJustin Bogner
1261fa8fa044SVedant Kumar // The body count applies to the area immediately after the collection.
1262d83511ddSZequan Wu auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1263fa8fa044SVedant Kumar if (Gap)
1264fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1265fa8fa044SVedant Kumar
12661587432dSJustin Bogner Counter LoopCount =
12671587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
12681587432dSJustin Bogner Counter OutCount =
12691587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
12709783e209SZequan Wu if (OutCount != ParentCount) {
1271bf42cfd7SJustin Bogner pushRegion(OutCount);
12729783e209SZequan Wu GapRegionCounter = OutCount;
12739783e209SZequan Wu }
1274ee02499aSAlex Lorenz }
1275ee02499aSAlex Lorenz
VisitSwitchStmt__anon8934bc200211::CounterCoverageMappingBuilder1276ee02499aSAlex Lorenz void VisitSwitchStmt(const SwitchStmt *S) {
1277bf42cfd7SJustin Bogner extendRegion(S);
1278f2a6ec55SVedant Kumar if (S->getInit())
1279f2a6ec55SVedant Kumar Visit(S->getInit());
1280ee02499aSAlex Lorenz Visit(S->getCond());
1281bf42cfd7SJustin Bogner
1282ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue());
1283bf42cfd7SJustin Bogner
1284bf42cfd7SJustin Bogner const Stmt *Body = S->getBody();
1285bf42cfd7SJustin Bogner extendRegion(Body);
1286bf42cfd7SJustin Bogner if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1287bf42cfd7SJustin Bogner if (!CS->body_empty()) {
12887f53fbfcSEli Friedman // Make a region for the body of the switch. If the body starts with
12897f53fbfcSEli Friedman // a case, that case will reuse this region; otherwise, this covers
12907f53fbfcSEli Friedman // the unreachable code at the beginning of the switch body.
1291859bf4d2SVedant Kumar size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1292859bf4d2SVedant Kumar getRegion().setGap(true);
12939783e209SZequan Wu Visit(Body);
12947f53fbfcSEli Friedman
12957f53fbfcSEli Friedman // Set the end for the body of the switch, if it isn't already set.
12967f53fbfcSEli Friedman for (size_t i = RegionStack.size(); i != Index; --i) {
12977f53fbfcSEli Friedman if (!RegionStack[i - 1].hasEndLoc())
12987f53fbfcSEli Friedman RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
12997f53fbfcSEli Friedman }
13007f53fbfcSEli Friedman
1301bf42cfd7SJustin Bogner popRegions(Index);
1302ee02499aSAlex Lorenz }
130387ea3b05SVedant Kumar } else
1304bf42cfd7SJustin Bogner propagateCounts(Counter::getZero(), Body);
1305ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val();
1306bf42cfd7SJustin Bogner
1307ee02499aSAlex Lorenz if (!BreakContinueStack.empty())
1308ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters(
1309ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1310bf42cfd7SJustin Bogner
13119f2967bcSAlan Phipps Counter ParentCount = getRegion().getCounter();
1312bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S);
13133836482aSVedant Kumar SourceLocation ExitLoc = getEnd(S);
131408780529SAlex Lorenz pushRegion(ExitCount);
13159783e209SZequan Wu GapRegionCounter = ExitCount;
131608780529SAlex Lorenz
131708780529SAlex Lorenz // Ensure that handleFileExit recognizes when the end location is located
131808780529SAlex Lorenz // in a different file.
131908780529SAlex Lorenz MostRecentLocation = getStart(S);
13203836482aSVedant Kumar handleFileExit(ExitLoc);
13219f2967bcSAlan Phipps
13229f2967bcSAlan Phipps // Create a Branch Region around each Case. Subtract the case's
13239f2967bcSAlan Phipps // counter from the Parent counter to track the "False" branch count.
13249f2967bcSAlan Phipps Counter CaseCountSum;
13259f2967bcSAlan Phipps bool HasDefaultCase = false;
13269f2967bcSAlan Phipps const SwitchCase *Case = S->getSwitchCaseList();
13279f2967bcSAlan Phipps for (; Case; Case = Case->getNextSwitchCase()) {
13289f2967bcSAlan Phipps HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1329ce54b226SBruno Cardoso Lopes CaseCountSum =
1330ce54b226SBruno Cardoso Lopes addCounters(CaseCountSum, getRegionCounter(Case), /*Simplify=*/false);
13319f2967bcSAlan Phipps createSwitchCaseRegion(
13329f2967bcSAlan Phipps Case, getRegionCounter(Case),
13339f2967bcSAlan Phipps subtractCounters(ParentCount, getRegionCounter(Case)));
13349f2967bcSAlan Phipps }
1335ce54b226SBruno Cardoso Lopes // Simplify is skipped while building the counters above: it can get really
1336ce54b226SBruno Cardoso Lopes // slow on top of switches with thousands of cases. Instead, trigger
1337ce54b226SBruno Cardoso Lopes // simplification by adding zero to the last counter.
1338ce54b226SBruno Cardoso Lopes CaseCountSum = addCounters(CaseCountSum, Counter::getZero());
13399f2967bcSAlan Phipps
13409f2967bcSAlan Phipps // If no explicit default case exists, create a branch region to represent
13419f2967bcSAlan Phipps // the hidden branch, which will be added later by the CodeGen. This region
13429f2967bcSAlan Phipps // will be associated with the switch statement's condition.
13439f2967bcSAlan Phipps if (!HasDefaultCase) {
13449f2967bcSAlan Phipps Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
13459f2967bcSAlan Phipps Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
13469f2967bcSAlan Phipps createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
13479f2967bcSAlan Phipps }
1348ee02499aSAlex Lorenz }
1349ee02499aSAlex Lorenz
VisitSwitchCase__anon8934bc200211::CounterCoverageMappingBuilder1350bf42cfd7SJustin Bogner void VisitSwitchCase(const SwitchCase *S) {
1351bf42cfd7SJustin Bogner extendRegion(S);
1352ee02499aSAlex Lorenz
1353bf42cfd7SJustin Bogner SourceMappingRegion &Parent = getRegion();
1354bf42cfd7SJustin Bogner
1355bf42cfd7SJustin Bogner Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1356bf42cfd7SJustin Bogner // Reuse the existing region if it starts at our label. This is typical of
1357bf42cfd7SJustin Bogner // the first case in a switch.
1358a6e4358fSStephen Kelly if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1359bf42cfd7SJustin Bogner Parent.setCounter(Count);
1360bf42cfd7SJustin Bogner else
1361bf42cfd7SJustin Bogner pushRegion(Count, getStart(S));
1362bf42cfd7SJustin Bogner
13639783e209SZequan Wu GapRegionCounter = Count;
13649783e209SZequan Wu
1365376c06c2SSanjay Patel if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1366bf42cfd7SJustin Bogner Visit(CS->getLHS());
1367bf42cfd7SJustin Bogner if (const Expr *RHS = CS->getRHS())
1368bf42cfd7SJustin Bogner Visit(RHS);
1369bf42cfd7SJustin Bogner }
1370ee02499aSAlex Lorenz Visit(S->getSubStmt());
1371ee02499aSAlex Lorenz }
1372ee02499aSAlex Lorenz
VisitIfStmt__anon8934bc200211::CounterCoverageMappingBuilder1373ee02499aSAlex Lorenz void VisitIfStmt(const IfStmt *S) {
1374bf42cfd7SJustin Bogner extendRegion(S);
13759d2a16b9SVedant Kumar if (S->getInit())
13769d2a16b9SVedant Kumar Visit(S->getInit());
13779d2a16b9SVedant Kumar
1378055ebc34SJustin Bogner // Extend into the condition before we propagate through it below - this is
1379055ebc34SJustin Bogner // needed to handle macros that generate the "if" but not the condition.
1380*3a08ad21SCorentin Jabot if (!S->isConsteval())
1381055ebc34SJustin Bogner extendRegion(S->getCond());
1382ee02499aSAlex Lorenz
1383bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter();
1384bf42cfd7SJustin Bogner Counter ThenCount = getRegionCounter(S);
1385ee02499aSAlex Lorenz
1386*3a08ad21SCorentin Jabot if (!S->isConsteval()) {
138791f2e3c9SJustin Bogner // Emitting a counter for the condition makes it easier to interpret the
138891f2e3c9SJustin Bogner // counter for the body when looking at the coverage.
138991f2e3c9SJustin Bogner propagateCounts(ParentCount, S->getCond());
139091f2e3c9SJustin Bogner
13912e8c8759SVedant Kumar // The 'then' count applies to the area immediately after the condition.
1392*3a08ad21SCorentin Jabot Optional<SourceRange> Gap =
1393*3a08ad21SCorentin Jabot findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1394fa8fa044SVedant Kumar if (Gap)
1395fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1396*3a08ad21SCorentin Jabot }
13972e8c8759SVedant Kumar
1398bf42cfd7SJustin Bogner extendRegion(S->getThen());
1399bf42cfd7SJustin Bogner Counter OutCount = propagateCounts(ThenCount, S->getThen());
1400bf42cfd7SJustin Bogner
1401bf42cfd7SJustin Bogner Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1402bf42cfd7SJustin Bogner if (const Stmt *Else = S->getElse()) {
14039783e209SZequan Wu bool ThenHasTerminateStmt = HasTerminateStmt;
14049783e209SZequan Wu HasTerminateStmt = false;
14052e8c8759SVedant Kumar // The 'else' count applies to the area immediately after the 'then'.
1406*3a08ad21SCorentin Jabot Optional<SourceRange> Gap =
1407*3a08ad21SCorentin Jabot findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1408fa8fa044SVedant Kumar if (Gap)
1409fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
14102e8c8759SVedant Kumar extendRegion(Else);
1411bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
14129783e209SZequan Wu
14139783e209SZequan Wu if (ThenHasTerminateStmt)
14149783e209SZequan Wu HasTerminateStmt = true;
1415bf42cfd7SJustin Bogner } else
1416bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, ElseCount);
1417bf42cfd7SJustin Bogner
14189783e209SZequan Wu if (OutCount != ParentCount) {
1419bf42cfd7SJustin Bogner pushRegion(OutCount);
14209783e209SZequan Wu GapRegionCounter = OutCount;
14219783e209SZequan Wu }
14229f2967bcSAlan Phipps
1423*3a08ad21SCorentin Jabot if (!S->isConsteval()) {
14249f2967bcSAlan Phipps // Create Branch Region around condition.
14259f2967bcSAlan Phipps createBranchRegion(S->getCond(), ThenCount,
14269f2967bcSAlan Phipps subtractCounters(ParentCount, ThenCount));
1427ee02499aSAlex Lorenz }
1428*3a08ad21SCorentin Jabot }
1429ee02499aSAlex Lorenz
VisitCXXTryStmt__anon8934bc200211::CounterCoverageMappingBuilder1430ee02499aSAlex Lorenz void VisitCXXTryStmt(const CXXTryStmt *S) {
1431bf42cfd7SJustin Bogner extendRegion(S);
1432049908b2SVedant Kumar // Handle macros that generate the "try" but not the rest.
1433049908b2SVedant Kumar extendRegion(S->getTryBlock());
1434049908b2SVedant Kumar
1435049908b2SVedant Kumar Counter ParentCount = getRegion().getCounter();
1436049908b2SVedant Kumar propagateCounts(ParentCount, S->getTryBlock());
1437049908b2SVedant Kumar
1438ee02499aSAlex Lorenz for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1439ee02499aSAlex Lorenz Visit(S->getHandler(I));
1440bf42cfd7SJustin Bogner
1441bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S);
1442bf42cfd7SJustin Bogner pushRegion(ExitCount);
1443ee02499aSAlex Lorenz }
1444ee02499aSAlex Lorenz
VisitCXXCatchStmt__anon8934bc200211::CounterCoverageMappingBuilder1445ee02499aSAlex Lorenz void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1446bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1447ee02499aSAlex Lorenz }
1448ee02499aSAlex Lorenz
VisitAbstractConditionalOperator__anon8934bc200211::CounterCoverageMappingBuilder1449ee02499aSAlex Lorenz void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1450bf42cfd7SJustin Bogner extendRegion(E);
1451ee02499aSAlex Lorenz
1452bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter();
1453bf42cfd7SJustin Bogner Counter TrueCount = getRegionCounter(E);
1454ee02499aSAlex Lorenz
14554dc08cc3SZequan Wu propagateCounts(ParentCount, E->getCond());
1456e3654ce7SJustin Bogner
1457e3654ce7SJustin Bogner if (!isa<BinaryConditionalOperator>(E)) {
14582e8c8759SVedant Kumar // The 'then' count applies to the area immediately after the condition.
1459fa8fa044SVedant Kumar auto Gap =
1460fa8fa044SVedant Kumar findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1461fa8fa044SVedant Kumar if (Gap)
1462fa8fa044SVedant Kumar fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
14632e8c8759SVedant Kumar
1464e3654ce7SJustin Bogner extendRegion(E->getTrueExpr());
1465bf42cfd7SJustin Bogner propagateCounts(TrueCount, E->getTrueExpr());
1466e3654ce7SJustin Bogner }
14672e8c8759SVedant Kumar
1468e3654ce7SJustin Bogner extendRegion(E->getFalseExpr());
1469bf42cfd7SJustin Bogner propagateCounts(subtractCounters(ParentCount, TrueCount),
1470bf42cfd7SJustin Bogner E->getFalseExpr());
14719f2967bcSAlan Phipps
14729f2967bcSAlan Phipps // Create Branch Region around condition.
14739f2967bcSAlan Phipps createBranchRegion(E->getCond(), TrueCount,
14749f2967bcSAlan Phipps subtractCounters(ParentCount, TrueCount));
1475ee02499aSAlex Lorenz }
1476ee02499aSAlex Lorenz
VisitBinLAnd__anon8934bc200211::CounterCoverageMappingBuilder1477ee02499aSAlex Lorenz void VisitBinLAnd(const BinaryOperator *E) {
1478e5f06a81SVedant Kumar extendRegion(E->getLHS());
1479e5f06a81SVedant Kumar propagateCounts(getRegion().getCounter(), E->getLHS());
1480e5f06a81SVedant Kumar handleFileExit(getEnd(E->getLHS()));
1481bf42cfd7SJustin Bogner
14829f2967bcSAlan Phipps // Counter tracks the right hand side of a logical and operator.
1483bf42cfd7SJustin Bogner extendRegion(E->getRHS());
1484bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS());
14859f2967bcSAlan Phipps
14869f2967bcSAlan Phipps // Extract the RHS's Execution Counter.
14879f2967bcSAlan Phipps Counter RHSExecCnt = getRegionCounter(E);
14889f2967bcSAlan Phipps
14899f2967bcSAlan Phipps // Extract the RHS's "True" Instance Counter.
14909f2967bcSAlan Phipps Counter RHSTrueCnt = getRegionCounter(E->getRHS());
14919f2967bcSAlan Phipps
14929f2967bcSAlan Phipps // Extract the Parent Region Counter.
14939f2967bcSAlan Phipps Counter ParentCnt = getRegion().getCounter();
14949f2967bcSAlan Phipps
14959f2967bcSAlan Phipps // Create Branch Region around LHS condition.
14969f2967bcSAlan Phipps createBranchRegion(E->getLHS(), RHSExecCnt,
14979f2967bcSAlan Phipps subtractCounters(ParentCnt, RHSExecCnt));
14989f2967bcSAlan Phipps
14999f2967bcSAlan Phipps // Create Branch Region around RHS condition.
15009f2967bcSAlan Phipps createBranchRegion(E->getRHS(), RHSTrueCnt,
15019f2967bcSAlan Phipps subtractCounters(RHSExecCnt, RHSTrueCnt));
1502ee02499aSAlex Lorenz }
1503ee02499aSAlex Lorenz
VisitBinLOr__anon8934bc200211::CounterCoverageMappingBuilder1504ee02499aSAlex Lorenz void VisitBinLOr(const BinaryOperator *E) {
1505e5f06a81SVedant Kumar extendRegion(E->getLHS());
1506e5f06a81SVedant Kumar propagateCounts(getRegion().getCounter(), E->getLHS());
1507e5f06a81SVedant Kumar handleFileExit(getEnd(E->getLHS()));
1508ee02499aSAlex Lorenz
15099f2967bcSAlan Phipps // Counter tracks the right hand side of a logical or operator.
1510bf42cfd7SJustin Bogner extendRegion(E->getRHS());
1511bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS());
15129f2967bcSAlan Phipps
15139f2967bcSAlan Phipps // Extract the RHS's Execution Counter.
15149f2967bcSAlan Phipps Counter RHSExecCnt = getRegionCounter(E);
15159f2967bcSAlan Phipps
15169f2967bcSAlan Phipps // Extract the RHS's "False" Instance Counter.
15179f2967bcSAlan Phipps Counter RHSFalseCnt = getRegionCounter(E->getRHS());
15189f2967bcSAlan Phipps
15199f2967bcSAlan Phipps // Extract the Parent Region Counter.
15209f2967bcSAlan Phipps Counter ParentCnt = getRegion().getCounter();
15219f2967bcSAlan Phipps
15229f2967bcSAlan Phipps // Create Branch Region around LHS condition.
15239f2967bcSAlan Phipps createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
15249f2967bcSAlan Phipps RHSExecCnt);
15259f2967bcSAlan Phipps
15269f2967bcSAlan Phipps // Create Branch Region around RHS condition.
15279f2967bcSAlan Phipps createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
15289f2967bcSAlan Phipps RHSFalseCnt);
152901a0d062SAlex Lorenz }
1530c109102eSJustin Bogner
VisitLambdaExpr__anon8934bc200211::CounterCoverageMappingBuilder1531c109102eSJustin Bogner void VisitLambdaExpr(const LambdaExpr *LE) {
1532c109102eSJustin Bogner // Lambdas are treated as their own functions for now, so we shouldn't
1533c109102eSJustin Bogner // propagate counts into them.
1534c109102eSJustin Bogner }
1535ee02499aSAlex Lorenz };
1536ee02499aSAlex Lorenz
153714f8fb68SVedant Kumar } // end anonymous namespace
153814f8fb68SVedant Kumar
dump(llvm::raw_ostream & OS,StringRef FunctionName,ArrayRef<CounterExpression> Expressions,ArrayRef<CounterMappingRegion> Regions)1539a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1540a432d176SJustin Bogner ArrayRef<CounterExpression> Expressions,
1541a432d176SJustin Bogner ArrayRef<CounterMappingRegion> Regions) {
1542a432d176SJustin Bogner OS << FunctionName << ":\n";
1543a432d176SJustin Bogner CounterMappingContext Ctx(Expressions);
1544a432d176SJustin Bogner for (const auto &R : Regions) {
1545f2cf38e0SAlex Lorenz OS.indent(2);
1546f2cf38e0SAlex Lorenz switch (R.Kind) {
1547f2cf38e0SAlex Lorenz case CounterMappingRegion::CodeRegion:
1548f2cf38e0SAlex Lorenz break;
1549f2cf38e0SAlex Lorenz case CounterMappingRegion::ExpansionRegion:
1550f2cf38e0SAlex Lorenz OS << "Expansion,";
1551f2cf38e0SAlex Lorenz break;
1552f2cf38e0SAlex Lorenz case CounterMappingRegion::SkippedRegion:
1553f2cf38e0SAlex Lorenz OS << "Skipped,";
1554f2cf38e0SAlex Lorenz break;
1555a1c4deb7SVedant Kumar case CounterMappingRegion::GapRegion:
1556a1c4deb7SVedant Kumar OS << "Gap,";
1557a1c4deb7SVedant Kumar break;
15589f2967bcSAlan Phipps case CounterMappingRegion::BranchRegion:
15599f2967bcSAlan Phipps OS << "Branch,";
15609f2967bcSAlan Phipps break;
1561f2cf38e0SAlex Lorenz }
1562f2cf38e0SAlex Lorenz
15634da909b2SJustin Bogner OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
15644da909b2SJustin Bogner << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1565f69dc349SJustin Bogner Ctx.dump(R.Count, OS);
15669f2967bcSAlan Phipps
15679f2967bcSAlan Phipps if (R.Kind == CounterMappingRegion::BranchRegion) {
15689f2967bcSAlan Phipps OS << ", ";
15699f2967bcSAlan Phipps Ctx.dump(R.FalseCount, OS);
15709f2967bcSAlan Phipps }
15719f2967bcSAlan Phipps
1572f2cf38e0SAlex Lorenz if (R.Kind == CounterMappingRegion::ExpansionRegion)
15734da909b2SJustin Bogner OS << " (Expanded file = " << R.ExpandedFileID << ")";
15744da909b2SJustin Bogner OS << "\n";
1575f2cf38e0SAlex Lorenz }
1576f2cf38e0SAlex Lorenz }
1577f2cf38e0SAlex Lorenz
CoverageMappingModuleGen(CodeGenModule & CGM,CoverageSourceInfo & SourceInfo)1578c3324450SKeith Smiley CoverageMappingModuleGen::CoverageMappingModuleGen(
1579c3324450SKeith Smiley CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
1580c3324450SKeith Smiley : CGM(CGM), SourceInfo(SourceInfo) {
15818459b8efSPetr Hosek CoveragePrefixMap = CGM.getCodeGenOpts().CoveragePrefixMap;
1582c3324450SKeith Smiley }
1583c3324450SKeith Smiley
getCurrentDirname()15845fbd1a33SPetr Hosek std::string CoverageMappingModuleGen::getCurrentDirname() {
15858459b8efSPetr Hosek if (!CGM.getCodeGenOpts().CoverageCompilationDir.empty())
15868459b8efSPetr Hosek return CGM.getCodeGenOpts().CoverageCompilationDir;
15875fbd1a33SPetr Hosek
15885fbd1a33SPetr Hosek SmallString<256> CWD;
15895fbd1a33SPetr Hosek llvm::sys::fs::current_path(CWD);
15905fbd1a33SPetr Hosek return CWD.str().str();
15915fbd1a33SPetr Hosek }
15925fbd1a33SPetr Hosek
normalizeFilename(StringRef Filename)1593c3324450SKeith Smiley std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
1594c3324450SKeith Smiley llvm::SmallString<256> Path(Filename);
1595c3324450SKeith Smiley llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
15968459b8efSPetr Hosek for (const auto &Entry : CoveragePrefixMap) {
1597c3324450SKeith Smiley if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second))
1598c3324450SKeith Smiley break;
1599c3324450SKeith Smiley }
1600c3324450SKeith Smiley return Path.str().str();
1601c3324450SKeith Smiley }
1602c3324450SKeith Smiley
getInstrProfSection(const CodeGenModule & CGM,llvm::InstrProfSectKind SK)1603dd1ea9deSVedant Kumar static std::string getInstrProfSection(const CodeGenModule &CGM,
1604dd1ea9deSVedant Kumar llvm::InstrProfSectKind SK) {
1605dd1ea9deSVedant Kumar return llvm::getInstrProfSectionName(
1606dd1ea9deSVedant Kumar SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1607dd1ea9deSVedant Kumar }
1608dd1ea9deSVedant Kumar
emitFunctionMappingRecord(const FunctionInfo & Info,uint64_t FilenamesRef)1609dd1ea9deSVedant Kumar void CoverageMappingModuleGen::emitFunctionMappingRecord(
1610dd1ea9deSVedant Kumar const FunctionInfo &Info, uint64_t FilenamesRef) {
161199317124SVedant Kumar llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1612dd1ea9deSVedant Kumar
1613dd1ea9deSVedant Kumar // Assign a name to the function record. This is used to merge duplicates.
1614dd1ea9deSVedant Kumar std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1615dd1ea9deSVedant Kumar
1616dd1ea9deSVedant Kumar // A dummy description for a function included-but-not-used in a TU can be
1617dd1ea9deSVedant Kumar // replaced by full description provided by a different TU. The two kinds of
1618dd1ea9deSVedant Kumar // descriptions play distinct roles: therefore, assign them different names
1619dd1ea9deSVedant Kumar // to prevent `linkonce_odr` merging.
1620dd1ea9deSVedant Kumar if (Info.IsUsed)
1621dd1ea9deSVedant Kumar FuncRecordName += "u";
1622dd1ea9deSVedant Kumar
1623dd1ea9deSVedant Kumar // Create the function record type.
1624dd1ea9deSVedant Kumar const uint64_t NameHash = Info.NameHash;
1625dd1ea9deSVedant Kumar const uint64_t FuncHash = Info.FuncHash;
1626dd1ea9deSVedant Kumar const std::string &CoverageMapping = Info.CoverageMapping;
162733888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
162833888717SVedant Kumar llvm::Type *FunctionRecordTypes[] = {
162933888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc"
163033888717SVedant Kumar };
1631dd1ea9deSVedant Kumar auto *FunctionRecordTy =
163233888717SVedant Kumar llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
163333888717SVedant Kumar /*isPacked=*/true);
163499317124SVedant Kumar
1635dd1ea9deSVedant Kumar // Create the function record constant.
163633888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
163733888717SVedant Kumar llvm::Constant *FunctionRecordVals[] = {
163833888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc"
163933888717SVedant Kumar };
1640dd1ea9deSVedant Kumar auto *FuncRecordConstant = llvm::ConstantStruct::get(
1641dd1ea9deSVedant Kumar FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1642dd1ea9deSVedant Kumar
1643dd1ea9deSVedant Kumar // Create the function record global.
1644dd1ea9deSVedant Kumar auto *FuncRecord = new llvm::GlobalVariable(
1645dd1ea9deSVedant Kumar CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1646dd1ea9deSVedant Kumar llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1647dd1ea9deSVedant Kumar FuncRecordName);
1648dd1ea9deSVedant Kumar FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1649dd1ea9deSVedant Kumar FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1650dd1ea9deSVedant Kumar FuncRecord->setAlignment(llvm::Align(8));
1651dd1ea9deSVedant Kumar if (CGM.supportsCOMDAT())
1652dd1ea9deSVedant Kumar FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1653dd1ea9deSVedant Kumar
1654dd1ea9deSVedant Kumar // Make sure the data doesn't get deleted.
1655dd1ea9deSVedant Kumar CGM.addUsedGlobal(FuncRecord);
1656dd1ea9deSVedant Kumar }
1657dd1ea9deSVedant Kumar
addFunctionMappingRecord(llvm::GlobalVariable * NamePtr,StringRef NameValue,uint64_t FuncHash,const std::string & CoverageMapping,bool IsUsed)1658dd1ea9deSVedant Kumar void CoverageMappingModuleGen::addFunctionMappingRecord(
1659dd1ea9deSVedant Kumar llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1660dd1ea9deSVedant Kumar const std::string &CoverageMapping, bool IsUsed) {
1661dd1ea9deSVedant Kumar llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1662dd1ea9deSVedant Kumar const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1663dd1ea9deSVedant Kumar FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1664dd1ea9deSVedant Kumar
1665848da137SXinliang David Li if (!IsUsed)
16662129ae53SXinliang David Li FunctionNames.push_back(
16672129ae53SXinliang David Li llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1668f2cf38e0SAlex Lorenz
1669f2cf38e0SAlex Lorenz if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1670f2cf38e0SAlex Lorenz // Dump the coverage mapping data for this function by decoding the
1671f2cf38e0SAlex Lorenz // encoded data. This allows us to dump the mapping regions which were
1672f2cf38e0SAlex Lorenz // also processed by the CoverageMappingWriter which performs
1673f2cf38e0SAlex Lorenz // additional minimization operations such as reducing the number of
1674f2cf38e0SAlex Lorenz // expressions.
16755fbd1a33SPetr Hosek llvm::SmallVector<std::string, 16> FilenameStrs;
1676f2cf38e0SAlex Lorenz std::vector<StringRef> Filenames;
1677f2cf38e0SAlex Lorenz std::vector<CounterExpression> Expressions;
1678f2cf38e0SAlex Lorenz std::vector<CounterMappingRegion> Regions;
16795fbd1a33SPetr Hosek FilenameStrs.resize(FileEntries.size() + 1);
16805fbd1a33SPetr Hosek FilenameStrs[0] = normalizeFilename(getCurrentDirname());
1681b31ee819SJordan Rose for (const auto &Entry : FileEntries) {
1682b31ee819SJordan Rose auto I = Entry.second;
1683b31ee819SJordan Rose FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1684b31ee819SJordan Rose }
16855fbd1a33SPetr Hosek ArrayRef<std::string> FilenameRefs = llvm::makeArrayRef(FilenameStrs);
1686a432d176SJustin Bogner RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1687a432d176SJustin Bogner Expressions, Regions);
1688a432d176SJustin Bogner if (Reader.read())
1689f2cf38e0SAlex Lorenz return;
1690a026a437SXinliang David Li dump(llvm::outs(), NameValue, Expressions, Regions);
1691f2cf38e0SAlex Lorenz }
1692ee02499aSAlex Lorenz }
1693ee02499aSAlex Lorenz
emit()1694ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1695ee02499aSAlex Lorenz if (FunctionRecords.empty())
1696ee02499aSAlex Lorenz return;
1697ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1698ee02499aSAlex Lorenz auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1699ee02499aSAlex Lorenz
1700ee02499aSAlex Lorenz // Create the filenames and merge them with coverage mappings
1701ee02499aSAlex Lorenz llvm::SmallVector<std::string, 16> FilenameStrs;
17025fbd1a33SPetr Hosek FilenameStrs.resize(FileEntries.size() + 1);
17035fbd1a33SPetr Hosek // The first filename is the current working directory.
17043275b18fSPetr Hosek FilenameStrs[0] = normalizeFilename(getCurrentDirname());
1705ee02499aSAlex Lorenz for (const auto &Entry : FileEntries) {
1706ee02499aSAlex Lorenz auto I = Entry.second;
170714f8fb68SVedant Kumar FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1708ee02499aSAlex Lorenz }
1709ee02499aSAlex Lorenz
1710dd1ea9deSVedant Kumar std::string Filenames;
1711dd1ea9deSVedant Kumar {
1712dd1ea9deSVedant Kumar llvm::raw_string_ostream OS(Filenames);
17135fbd1a33SPetr Hosek CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
17144cd07dbeSSerge Guelton }
1715dd1ea9deSVedant Kumar auto *FilenamesVal =
1716dd1ea9deSVedant Kumar llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1717dd1ea9deSVedant Kumar const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
17184cd07dbeSSerge Guelton
1719dd1ea9deSVedant Kumar // Emit the function records.
1720dd1ea9deSVedant Kumar for (const FunctionInfo &Info : FunctionRecords)
1721dd1ea9deSVedant Kumar emitFunctionMappingRecord(Info, FilenamesRef);
1722ee02499aSAlex Lorenz
1723dd1ea9deSVedant Kumar const unsigned NRecords = 0;
1724dd1ea9deSVedant Kumar const size_t FilenamesSize = Filenames.size();
1725dd1ea9deSVedant Kumar const unsigned CoverageMappingSize = 0;
172620b188c0SXinliang David Li llvm::Type *CovDataHeaderTypes[] = {
172720b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
172820b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
172920b188c0SXinliang David Li };
173020b188c0SXinliang David Li auto CovDataHeaderTy =
173120b188c0SXinliang David Li llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
173220b188c0SXinliang David Li llvm::Constant *CovDataHeaderVals[] = {
173320b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
173420b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
173520b188c0SXinliang David Li };
173620b188c0SXinliang David Li auto CovDataHeaderVal = llvm::ConstantStruct::get(
173720b188c0SXinliang David Li CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
173820b188c0SXinliang David Li
1739ee02499aSAlex Lorenz // Create the coverage data record
1740dd1ea9deSVedant Kumar llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1741ee02499aSAlex Lorenz auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1742dd1ea9deSVedant Kumar llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1743ee02499aSAlex Lorenz auto CovDataVal =
1744ee02499aSAlex Lorenz llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
174520b188c0SXinliang David Li auto CovData = new llvm::GlobalVariable(
1746dd1ea9deSVedant Kumar CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
174720b188c0SXinliang David Li CovDataVal, llvm::getCoverageMappingVarName());
1748ee02499aSAlex Lorenz
1749dd1ea9deSVedant Kumar CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1750c79099e0SGuillaume Chatelet CovData->setAlignment(llvm::Align(8));
1751ee02499aSAlex Lorenz
1752ee02499aSAlex Lorenz // Make sure the data doesn't get deleted.
1753ee02499aSAlex Lorenz CGM.addUsedGlobal(CovData);
17542129ae53SXinliang David Li // Create the deferred function records array
17552129ae53SXinliang David Li if (!FunctionNames.empty()) {
17562129ae53SXinliang David Li auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
17572129ae53SXinliang David Li FunctionNames.size());
17582129ae53SXinliang David Li auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
17592129ae53SXinliang David Li // This variable will *NOT* be emitted to the object file. It is used
17602129ae53SXinliang David Li // to pass the list of names referenced to codegen.
17612129ae53SXinliang David Li new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
17622129ae53SXinliang David Li llvm::GlobalValue::InternalLinkage, NamesArrVal,
17637077f0afSXinliang David Li llvm::getCoverageUnusedNamesVarName());
17642129ae53SXinliang David Li }
1765ee02499aSAlex Lorenz }
1766ee02499aSAlex Lorenz
getFileID(const FileEntry * File)1767ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1768ee02499aSAlex Lorenz auto It = FileEntries.find(File);
1769ee02499aSAlex Lorenz if (It != FileEntries.end())
1770ee02499aSAlex Lorenz return It->second;
17715fbd1a33SPetr Hosek unsigned FileID = FileEntries.size() + 1;
1772ee02499aSAlex Lorenz FileEntries.insert(std::make_pair(File, FileID));
1773ee02499aSAlex Lorenz return FileID;
1774ee02499aSAlex Lorenz }
1775ee02499aSAlex Lorenz
emitCounterMapping(const Decl * D,llvm::raw_ostream & OS)1776ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1777ee02499aSAlex Lorenz llvm::raw_ostream &OS) {
1778ee02499aSAlex Lorenz assert(CounterMap);
1779e5ee6c58SJustin Bogner CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1780ee02499aSAlex Lorenz Walker.VisitDecl(D);
1781ee02499aSAlex Lorenz Walker.write(OS);
1782ee02499aSAlex Lorenz }
1783ee02499aSAlex Lorenz
emitEmptyMapping(const Decl * D,llvm::raw_ostream & OS)1784ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1785ee02499aSAlex Lorenz llvm::raw_ostream &OS) {
1786ee02499aSAlex Lorenz EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1787ee02499aSAlex Lorenz Walker.VisitDecl(D);
1788ee02499aSAlex Lorenz Walker.write(OS);
1789ee02499aSAlex Lorenz }
1790