1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2ee02499aSAlex Lorenz //
3ee02499aSAlex Lorenz //                     The LLVM Compiler Infrastructure
4ee02499aSAlex Lorenz //
5ee02499aSAlex Lorenz // This file is distributed under the University of Illinois Open Source
6ee02499aSAlex Lorenz // License. See LICENSE.TXT for details.
7ee02499aSAlex Lorenz //
8ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
9ee02499aSAlex Lorenz //
10ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator
11ee02499aSAlex Lorenz //
12ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
13ee02499aSAlex Lorenz 
14ee02499aSAlex Lorenz #include "CoverageMappingGen.h"
15ee02499aSAlex Lorenz #include "CodeGenFunction.h"
16ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h"
17ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
18bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h"
19ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h"
20bf42cfd7SJustin Bogner #include "llvm/ADT/Optional.h"
21b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
22b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
240d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
25ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
2614f8fb68SVedant Kumar #include "llvm/Support/Path.h"
27ee02499aSAlex Lorenz 
28ee02499aSAlex Lorenz using namespace clang;
29ee02499aSAlex Lorenz using namespace CodeGen;
30ee02499aSAlex Lorenz using namespace llvm::coverage;
31ee02499aSAlex Lorenz 
32ee02499aSAlex Lorenz void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
33ee02499aSAlex Lorenz   SkippedRanges.push_back(Range);
34ee02499aSAlex Lorenz }
35ee02499aSAlex Lorenz 
36ee02499aSAlex Lorenz namespace {
37ee02499aSAlex Lorenz 
38ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter.
3909c7179bSJustin Bogner class SourceMappingRegion {
40ee02499aSAlex Lorenz   Counter Count;
41ee02499aSAlex Lorenz 
42ee02499aSAlex Lorenz   /// \brief The region's starting location.
43bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
44ee02499aSAlex Lorenz 
45ee02499aSAlex Lorenz   /// \brief The region's ending location.
46bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
47ee02499aSAlex Lorenz 
4809c7179bSJustin Bogner public:
49bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
50bf42cfd7SJustin Bogner                       Optional<SourceLocation> LocEnd)
51bf42cfd7SJustin Bogner       : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
52ee02499aSAlex Lorenz 
5309c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
5409c7179bSJustin Bogner 
55bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
5609c7179bSJustin Bogner 
57bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
58bf42cfd7SJustin Bogner 
59bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
60bf42cfd7SJustin Bogner 
61462c77b4SCraig Topper   SourceLocation getStartLoc() const {
62bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
63bf42cfd7SJustin Bogner     return *LocStart;
6409c7179bSJustin Bogner   }
6509c7179bSJustin Bogner 
66bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
67ee02499aSAlex Lorenz 
68bf42cfd7SJustin Bogner   void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
69ee02499aSAlex Lorenz 
70462c77b4SCraig Topper   SourceLocation getEndLoc() const {
71bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
72bf42cfd7SJustin Bogner     return *LocEnd;
73ee02499aSAlex Lorenz   }
74ee02499aSAlex Lorenz };
75ee02499aSAlex Lorenz 
76ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different
77ee02499aSAlex Lorenz /// coverage mapping region builders.
78ee02499aSAlex Lorenz class CoverageMappingBuilder {
79ee02499aSAlex Lorenz public:
80ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
81ee02499aSAlex Lorenz   SourceManager &SM;
82ee02499aSAlex Lorenz   const LangOptions &LangOpts;
83ee02499aSAlex Lorenz 
84ee02499aSAlex Lorenz private:
85bf42cfd7SJustin Bogner   /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
86bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
87bf42cfd7SJustin Bogner       FileIDMapping;
88ee02499aSAlex Lorenz 
89ee02499aSAlex Lorenz public:
90ee02499aSAlex Lorenz   /// \brief The coverage mapping regions for this function
91ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
92ee02499aSAlex Lorenz   /// \brief The source mapping regions for this function.
93f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
94ee02499aSAlex Lorenz 
95fc05ee34SIgor Kudrin   /// \brief A set of regions which can be used as a filter.
96fc05ee34SIgor Kudrin   ///
97fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
98fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
99fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
100fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
101fc05ee34SIgor Kudrin       SourceRegionFilter;
102fc05ee34SIgor Kudrin 
103ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
104ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
105bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
106ee02499aSAlex Lorenz 
107ee02499aSAlex Lorenz   /// \brief Return the precise end location for the given token.
108ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
109bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
110bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
111bf42cfd7SJustin Bogner     unsigned TokLen =
112bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
113bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
114ee02499aSAlex Lorenz   }
115ee02499aSAlex Lorenz 
116bf42cfd7SJustin Bogner   /// \brief Return the start location of an included file or expanded macro.
117bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
118bf42cfd7SJustin Bogner     if (Loc.isMacroID())
119bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
120bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
121ee02499aSAlex Lorenz   }
122ee02499aSAlex Lorenz 
123bf42cfd7SJustin Bogner   /// \brief Return the end location of an included file or expanded macro.
124bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
125bf42cfd7SJustin Bogner     if (Loc.isMacroID())
126bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
127f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
128bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
129bf42cfd7SJustin Bogner   }
130ee02499aSAlex Lorenz 
131bf42cfd7SJustin Bogner   /// \brief Find out where the current file is included or macro is expanded.
132bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
133bf42cfd7SJustin Bogner     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
134bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
135bf42cfd7SJustin Bogner   }
136bf42cfd7SJustin Bogner 
137682bfbf3SJustin Bogner   /// \brief Return true if \c Loc is a location in a built-in macro.
138682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
13999d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
140682bfbf3SJustin Bogner   }
141682bfbf3SJustin Bogner 
142d9e1a61dSIgor Kudrin   /// \brief Check whether \c Loc is included or expanded from \c Parent.
143d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
144d9e1a61dSIgor Kudrin     do {
145d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
146d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
147d9e1a61dSIgor Kudrin         return false;
148d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
149d9e1a61dSIgor Kudrin     return true;
150d9e1a61dSIgor Kudrin   }
151d9e1a61dSIgor Kudrin 
152682bfbf3SJustin Bogner   /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
153bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
154bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocStart();
155682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
156bf42cfd7SJustin Bogner       Loc = SM.getImmediateExpansionRange(Loc).first;
157bf42cfd7SJustin Bogner     return Loc;
158bf42cfd7SJustin Bogner   }
159bf42cfd7SJustin Bogner 
160682bfbf3SJustin Bogner   /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
161bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
162bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocEnd();
163682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
164bf42cfd7SJustin Bogner       Loc = SM.getImmediateExpansionRange(Loc).first;
165f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
166bf42cfd7SJustin Bogner   }
167bf42cfd7SJustin Bogner 
168bf42cfd7SJustin Bogner   /// \brief Find the set of files we have regions for and assign IDs
169bf42cfd7SJustin Bogner   ///
170bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
171bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
172bf42cfd7SJustin Bogner   /// expansion regions.
173bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
174bf42cfd7SJustin Bogner     FileIDMapping.clear();
175bf42cfd7SJustin Bogner 
176bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
177bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
178bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
179bf42cfd7SJustin Bogner       SourceLocation Loc = Region.getStartLoc();
180bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
181bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
182bf42cfd7SJustin Bogner         continue;
183bf42cfd7SJustin Bogner 
18493205af0SVedant Kumar       // Do not map FileID's associated with system headers.
18593205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
18693205af0SVedant Kumar         continue;
18793205af0SVedant Kumar 
188bf42cfd7SJustin Bogner       unsigned Depth = 0;
189bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
190ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
191bf42cfd7SJustin Bogner         ++Depth;
192bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
193bf42cfd7SJustin Bogner     }
194bf42cfd7SJustin Bogner     std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
195bf42cfd7SJustin Bogner 
196bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
197bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
198bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
199ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
200ee02499aSAlex Lorenz       if (!Entry)
201bf42cfd7SJustin Bogner         continue;
202ee02499aSAlex Lorenz 
203bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
204bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
205bf42cfd7SJustin Bogner     }
206ee02499aSAlex Lorenz   }
207ee02499aSAlex Lorenz 
208bf42cfd7SJustin Bogner   /// \brief Get the coverage mapping file ID for \c Loc.
209bf42cfd7SJustin Bogner   ///
210bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
211bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
212bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
213bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
214bf42cfd7SJustin Bogner       return Mapping->second.first;
215903678caSJustin Bogner     return None;
216ee02499aSAlex Lorenz   }
217ee02499aSAlex Lorenz 
218ee02499aSAlex Lorenz   /// \brief Gather all the regions that were skipped by the preprocessor
219ee02499aSAlex Lorenz   /// using the constructs like #if.
220ee02499aSAlex Lorenz   void gatherSkippedRegions() {
221ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
222ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
223ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
224ee02499aSAlex Lorenz     FileLineRanges.resize(
225ee02499aSAlex Lorenz         FileIDMapping.size(),
226ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
227ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
228ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
229ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
230ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
231ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
232ee02499aSAlex Lorenz     }
233ee02499aSAlex Lorenz 
234ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
235ee02499aSAlex Lorenz     for (const auto &I : SkippedRanges) {
236ee02499aSAlex Lorenz       auto LocStart = I.getBegin();
237ee02499aSAlex Lorenz       auto LocEnd = I.getEnd();
238bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
239bf42cfd7SJustin Bogner              "region spans multiple files");
240ee02499aSAlex Lorenz 
241bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
242903678caSJustin Bogner       if (!CovFileID)
243ee02499aSAlex Lorenz         continue;
244ee02499aSAlex Lorenz       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
245ee02499aSAlex Lorenz       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
246ee02499aSAlex Lorenz       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
247ee02499aSAlex Lorenz       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
248fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
249fd34280bSJustin Bogner           *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
250ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
251ee02499aSAlex Lorenz       // the souce code of this function.
252903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
253903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
254ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
255ee02499aSAlex Lorenz     }
256ee02499aSAlex Lorenz   }
257ee02499aSAlex Lorenz 
258ee02499aSAlex Lorenz   /// \brief Generate the coverage counter mapping regions from collected
259ee02499aSAlex Lorenz   /// source regions.
260fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
261bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
262bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
263ee02499aSAlex Lorenz 
264bf42cfd7SJustin Bogner       SourceLocation LocStart = Region.getStartLoc();
2658b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
266f59329b0SJustin Bogner 
26793205af0SVedant Kumar       // Ignore regions from system headers.
26893205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
26993205af0SVedant Kumar         continue;
27093205af0SVedant Kumar 
271bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
272bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
273bf42cfd7SJustin Bogner       if (!CovFileID)
274ee02499aSAlex Lorenz         continue;
275ee02499aSAlex Lorenz 
276f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
277bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
278bf42cfd7SJustin Bogner              "region spans multiple files");
279bf42cfd7SJustin Bogner 
280fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
281fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
282fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
283fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
284fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
285fc05ee34SIgor Kudrin         continue;
286fc05ee34SIgor Kudrin 
287f59329b0SJustin Bogner       // Find the spilling locations for the mapping region.
288ee02499aSAlex Lorenz       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
289ee02499aSAlex Lorenz       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
290ee02499aSAlex Lorenz       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
291ee02499aSAlex Lorenz       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
292ee02499aSAlex Lorenz 
293bf42cfd7SJustin Bogner       assert(LineStart <= LineEnd && "region start and end out of order");
294bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeRegion(
295bf42cfd7SJustin Bogner           Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
296bf42cfd7SJustin Bogner           ColumnEnd));
297bf42cfd7SJustin Bogner     }
298bf42cfd7SJustin Bogner   }
299bf42cfd7SJustin Bogner 
300bf42cfd7SJustin Bogner   /// \brief Generate expansion regions for each virtual file we've seen.
301fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
302fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
303bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
304bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
305bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
306bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
307ee02499aSAlex Lorenz         continue;
308ee02499aSAlex Lorenz 
309bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
310bf42cfd7SJustin Bogner       if (!ParentFileID)
311bf42cfd7SJustin Bogner         continue;
312bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
313bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
314bf42cfd7SJustin Bogner 
315bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
316bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
317bf42cfd7SJustin Bogner              "region spans multiple files");
318fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
319bf42cfd7SJustin Bogner 
320bf42cfd7SJustin Bogner       unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
321bf42cfd7SJustin Bogner       unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
322bf42cfd7SJustin Bogner       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
323bf42cfd7SJustin Bogner       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
324bf42cfd7SJustin Bogner 
325bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
326bf42cfd7SJustin Bogner           *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
327fd34280bSJustin Bogner           ColumnEnd));
328ee02499aSAlex Lorenz     }
329fc05ee34SIgor Kudrin     return Filter;
330ee02499aSAlex Lorenz   }
331ee02499aSAlex Lorenz };
332ee02499aSAlex Lorenz 
333ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that
334ee02499aSAlex Lorenz /// are not emitted.
335ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
336ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
337ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
338ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
339ee02499aSAlex Lorenz 
340ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
341ee02499aSAlex Lorenz     if (!D->hasBody())
342ee02499aSAlex Lorenz       return;
343ee02499aSAlex Lorenz     auto Body = D->getBody();
344d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
345d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
346d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
347d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
348d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
349d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
350d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
351d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
352d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
353d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
354d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
355d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
356d9e1a61dSIgor Kudrin       }
357d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
358d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
359d9e1a61dSIgor Kudrin         assert(End.isValid() &&
360d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
361d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
362d9e1a61dSIgor Kudrin       }
363d9e1a61dSIgor Kudrin     }
364d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
365ee02499aSAlex Lorenz   }
366ee02499aSAlex Lorenz 
367ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
368ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
369ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
370bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
371fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
372ee02499aSAlex Lorenz 
373efd319a2SVedant Kumar     if (MappingRegions.empty())
374efd319a2SVedant Kumar       return;
375efd319a2SVedant Kumar 
3765fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
377ee02499aSAlex Lorenz     Writer.write(OS);
378ee02499aSAlex Lorenz   }
379ee02499aSAlex Lorenz };
380ee02499aSAlex Lorenz 
381ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map
382ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
383ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
384ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
385ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
386ee02499aSAlex Lorenz   /// \brief The map of statements to count values.
387ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
388ee02499aSAlex Lorenz 
389bf42cfd7SJustin Bogner   /// \brief A stack of currently live regions.
390bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
391ee02499aSAlex Lorenz 
392ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
393ee02499aSAlex Lorenz 
394bf42cfd7SJustin Bogner   /// \brief A location in the most recently visited file or macro.
395bf42cfd7SJustin Bogner   ///
396bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
397bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
398bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
399bf42cfd7SJustin Bogner 
400bf42cfd7SJustin Bogner   /// \brief Return a counter for the subtraction of \c RHS from \c LHS
401ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
402ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
403ee02499aSAlex Lorenz   }
404ee02499aSAlex Lorenz 
405bf42cfd7SJustin Bogner   /// \brief Return a counter for the sum of \c LHS and \c RHS.
406ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
407ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
408ee02499aSAlex Lorenz   }
409ee02499aSAlex Lorenz 
410bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
411bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
412bf42cfd7SJustin Bogner   }
413bf42cfd7SJustin Bogner 
414ee02499aSAlex Lorenz   /// \brief Return the region counter for the given statement.
415bf42cfd7SJustin Bogner   ///
416ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
417bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
418bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
419ee02499aSAlex Lorenz   }
420ee02499aSAlex Lorenz 
421bf42cfd7SJustin Bogner   /// \brief Push a region onto the stack.
422bf42cfd7SJustin Bogner   ///
423bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
424bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
425bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
426bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
427bf42cfd7SJustin Bogner     if (StartLoc)
428bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
429bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
430ee02499aSAlex Lorenz 
431bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
432ee02499aSAlex Lorenz   }
433ee02499aSAlex Lorenz 
434bf42cfd7SJustin Bogner   /// \brief Pop regions from the stack into the function's list of regions.
435bf42cfd7SJustin Bogner   ///
436bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
437bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
438bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
439bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
440bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
441bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
442bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
443bf42cfd7SJustin Bogner         SourceLocation StartLoc = Region.getStartLoc();
444bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
445bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
446bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
447bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
448bf42cfd7SJustin Bogner           // The region ends in a nested file or macro expansion. Create a
449bf42cfd7SJustin Bogner           // separate region for each expansion.
450bf42cfd7SJustin Bogner           SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
451bf42cfd7SJustin Bogner           assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
452bf42cfd7SJustin Bogner 
4538545dae2SIgor Kudrin           if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
454bf42cfd7SJustin Bogner             SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
455bf42cfd7SJustin Bogner 
456f14b2078SJustin Bogner           EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
457dceaaadfSJustin Bogner           if (EndLoc.isInvalid())
458dceaaadfSJustin Bogner             llvm::report_fatal_error("File exit not handled before popRegions");
459bf42cfd7SJustin Bogner         }
460bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
461bf42cfd7SJustin Bogner 
462bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
463bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
464bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
465bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
466bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
467bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
468bf42cfd7SJustin Bogner 
469bf42cfd7SJustin Bogner         assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
470f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
471bf42cfd7SJustin Bogner       }
472bf42cfd7SJustin Bogner       RegionStack.pop_back();
473bf42cfd7SJustin Bogner     }
474ee02499aSAlex Lorenz   }
475ee02499aSAlex Lorenz 
476bf42cfd7SJustin Bogner   /// \brief Return the currently active region.
477bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
478bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
479bf42cfd7SJustin Bogner     return RegionStack.back();
480ee02499aSAlex Lorenz   }
481ee02499aSAlex Lorenz 
482bf42cfd7SJustin Bogner   /// \brief Propagate counts through the children of \c S.
483bf42cfd7SJustin Bogner   Counter propagateCounts(Counter TopCount, const Stmt *S) {
484bf42cfd7SJustin Bogner     size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
485bf42cfd7SJustin Bogner     Visit(S);
486bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
487bf42cfd7SJustin Bogner     popRegions(Index);
48839f01975SVedant Kumar 
48939f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
49039f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
49139f01975SVedant Kumar     if (SM.isBeforeInTranslationUnit(getStart(S), S->getLocStart()))
49239f01975SVedant Kumar       MostRecentLocation = getEnd(S);
49339f01975SVedant Kumar 
494bf42cfd7SJustin Bogner     return ExitCount;
495ee02499aSAlex Lorenz   }
496ee02499aSAlex Lorenz 
4970a7c9d11SIgor Kudrin   /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
4980a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
4990a7c9d11SIgor Kudrin   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
5000a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
5010a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
5020a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
5030a7c9d11SIgor Kudrin                           return Region.getStartLoc() == StartLoc &&
5040a7c9d11SIgor Kudrin                                  Region.getEndLoc() == EndLoc;
5050a7c9d11SIgor Kudrin                         });
5060a7c9d11SIgor Kudrin   }
5070a7c9d11SIgor Kudrin 
508bf42cfd7SJustin Bogner   /// \brief Adjust the most recently visited location to \c EndLoc.
509bf42cfd7SJustin Bogner   ///
510bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
511bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
512bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
5130a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
5140a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
5150a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
5160a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
5170a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
51896ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
5190a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
5200a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
5210a7c9d11SIgor Kudrin                              MostRecentLocation))
522bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
523ee02499aSAlex Lorenz   }
524ee02499aSAlex Lorenz 
525bf42cfd7SJustin Bogner   /// \brief Adjust regions and state when \c NewLoc exits a file.
526bf42cfd7SJustin Bogner   ///
527bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
528bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
529bf42cfd7SJustin Bogner   /// for the exited file.
530bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
531e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
532e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
533bf42cfd7SJustin Bogner       return;
534bf42cfd7SJustin Bogner 
535bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
536bf42cfd7SJustin Bogner     // find the common ancestor.
537bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
538bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
539bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
540bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
541bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
542bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
543bf42cfd7SJustin Bogner         // to adjust our location to the new file.
544bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
545bf42cfd7SJustin Bogner         return;
546bf42cfd7SJustin Bogner       }
547bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
548ee02499aSAlex Lorenz     }
549ee02499aSAlex Lorenz 
550bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
551bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
55257d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
55357d3f145SPete Cooper       if (!I.hasStartLoc())
554bf42cfd7SJustin Bogner         continue;
55557d3f145SPete Cooper       SourceLocation Loc = I.getStartLoc();
556bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
55757d3f145SPete Cooper         ParentCounter = I.getCounter();
558bf42cfd7SJustin Bogner         break;
559ee02499aSAlex Lorenz       }
560bf42cfd7SJustin Bogner 
561bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
562bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
563bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
564bf42cfd7SJustin Bogner         // we've seen this region.
565bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
56657d3f145SPete Cooper           SourceRegions.emplace_back(I.getCounter(), Loc,
567bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
568bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
569ee02499aSAlex Lorenz       }
57057d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
571bf42cfd7SJustin Bogner     }
572bf42cfd7SJustin Bogner 
573bf42cfd7SJustin Bogner     if (ParentCounter) {
574bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
575bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
576bf42cfd7SJustin Bogner       // corresponding to the parent.
577bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
578bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
579bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
580bf42cfd7SJustin Bogner         if (StartLocs.insert(FileStart).second)
581bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
582bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
583bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
584bf42cfd7SJustin Bogner       }
585bf42cfd7SJustin Bogner     }
586bf42cfd7SJustin Bogner 
587bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
588bf42cfd7SJustin Bogner   }
589bf42cfd7SJustin Bogner 
590bf42cfd7SJustin Bogner   /// \brief Ensure that \c S is included in the current region.
591bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
592bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
593bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
594bf42cfd7SJustin Bogner 
595bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
596bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
597bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
598bf42cfd7SJustin Bogner   }
599bf42cfd7SJustin Bogner 
600bf42cfd7SJustin Bogner   /// \brief Mark \c S as a terminator, starting a zero region.
601bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
602bf42cfd7SJustin Bogner     extendRegion(S);
603bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
604bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
605bf42cfd7SJustin Bogner       Region.setEndLoc(getEnd(S));
606bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
607bf42cfd7SJustin Bogner   }
608ee02499aSAlex Lorenz 
609ee02499aSAlex Lorenz   /// \brief Keep counts of breaks and continues inside loops.
610ee02499aSAlex Lorenz   struct BreakContinue {
611ee02499aSAlex Lorenz     Counter BreakCount;
612ee02499aSAlex Lorenz     Counter ContinueCount;
613ee02499aSAlex Lorenz   };
614ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
615ee02499aSAlex Lorenz 
616ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
617ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
618e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
619ee02499aSAlex Lorenz       const LangOptions &LangOpts)
620e5ee6c58SJustin Bogner       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
621ee02499aSAlex Lorenz 
622ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
623ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
624ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
625bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
626fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
627fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
628ee02499aSAlex Lorenz     gatherSkippedRegions();
629ee02499aSAlex Lorenz 
630efd319a2SVedant Kumar     if (MappingRegions.empty())
631efd319a2SVedant Kumar       return;
632efd319a2SVedant Kumar 
6334da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
6344da909b2SJustin Bogner                                  MappingRegions);
635ee02499aSAlex Lorenz     Writer.write(OS);
636ee02499aSAlex Lorenz   }
637ee02499aSAlex Lorenz 
638ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
639ed1fe5d0SYaron Keren     if (S->getLocStart().isValid())
640bf42cfd7SJustin Bogner       extendRegion(S);
641642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
642642f173aSBenjamin Kramer       if (Child)
643642f173aSBenjamin Kramer         this->Visit(Child);
644bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
645ee02499aSAlex Lorenz   }
646ee02499aSAlex Lorenz 
647ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
648bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
649efd319a2SVedant Kumar 
650efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
651efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
652efd319a2SVedant Kumar       return;
653efd319a2SVedant Kumar 
654bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(Body), Body);
655ee02499aSAlex Lorenz   }
656ee02499aSAlex Lorenz 
657ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
658bf42cfd7SJustin Bogner     extendRegion(S);
659ee02499aSAlex Lorenz     if (S->getRetValue())
660ee02499aSAlex Lorenz       Visit(S->getRetValue());
661bf42cfd7SJustin Bogner     terminateRegion(S);
662ee02499aSAlex Lorenz   }
663ee02499aSAlex Lorenz 
664f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
665f959febfSJustin Bogner     extendRegion(E);
666f959febfSJustin Bogner     if (E->getSubExpr())
667f959febfSJustin Bogner       Visit(E->getSubExpr());
668f959febfSJustin Bogner     terminateRegion(E);
669f959febfSJustin Bogner   }
670f959febfSJustin Bogner 
671bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
672ee02499aSAlex Lorenz 
673ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
674bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
675bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
676bf42cfd7SJustin Bogner     handleFileExit(Start);
677bf42cfd7SJustin Bogner     pushRegion(getRegionCounter(S), Start);
678ee02499aSAlex Lorenz     Visit(S->getSubStmt());
679ee02499aSAlex Lorenz   }
680ee02499aSAlex Lorenz 
681ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
682ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
683ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
684bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
685bf42cfd7SJustin Bogner     terminateRegion(S);
686ee02499aSAlex Lorenz   }
687ee02499aSAlex Lorenz 
688ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
689ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
690ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
691bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
692bf42cfd7SJustin Bogner     terminateRegion(S);
693ee02499aSAlex Lorenz   }
694ee02499aSAlex Lorenz 
695ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
696bf42cfd7SJustin Bogner     extendRegion(S);
697ee02499aSAlex Lorenz 
698bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
699bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
700bf42cfd7SJustin Bogner 
701bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
702bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
703bf42cfd7SJustin Bogner     extendRegion(S->getBody());
704bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
705ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
706bf42cfd7SJustin Bogner 
707bf42cfd7SJustin Bogner     // Go back to handle the condition.
708bf42cfd7SJustin Bogner     Counter CondCount =
709bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
710bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
711bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
712bf42cfd7SJustin Bogner 
713bf42cfd7SJustin Bogner     Counter OutCount =
714bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
715bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
716bf42cfd7SJustin Bogner       pushRegion(OutCount);
717ee02499aSAlex Lorenz   }
718ee02499aSAlex Lorenz 
719ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
720bf42cfd7SJustin Bogner     extendRegion(S);
721ee02499aSAlex Lorenz 
722bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
723bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
724bf42cfd7SJustin Bogner 
725bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
726bf42cfd7SJustin Bogner     extendRegion(S->getBody());
727bf42cfd7SJustin Bogner     Counter BackedgeCount =
728bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
729ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
730bf42cfd7SJustin Bogner 
731bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
732bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
733bf42cfd7SJustin Bogner 
734bf42cfd7SJustin Bogner     Counter OutCount =
735bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
736bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
737bf42cfd7SJustin Bogner       pushRegion(OutCount);
738ee02499aSAlex Lorenz   }
739ee02499aSAlex Lorenz 
740ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
741bf42cfd7SJustin Bogner     extendRegion(S);
742ee02499aSAlex Lorenz     if (S->getInit())
743ee02499aSAlex Lorenz       Visit(S->getInit());
744ee02499aSAlex Lorenz 
745bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
746bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
747bf42cfd7SJustin Bogner 
748bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
749ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
750bf42cfd7SJustin Bogner     extendRegion(S->getBody());
751bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
752bf42cfd7SJustin Bogner     BreakContinue BC = BreakContinueStack.pop_back_val();
753ee02499aSAlex Lorenz 
754ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
755ee02499aSAlex Lorenz     // the count for all the continue statements.
756bf42cfd7SJustin Bogner     if (const Stmt *Inc = S->getInc())
757bf42cfd7SJustin Bogner       propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
758bf42cfd7SJustin Bogner 
759bf42cfd7SJustin Bogner     // Go back to handle the condition.
760bf42cfd7SJustin Bogner     Counter CondCount =
761bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
762bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
763bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
764bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
765ee02499aSAlex Lorenz     }
766ee02499aSAlex Lorenz 
767bf42cfd7SJustin Bogner     Counter OutCount =
768bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
769bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
770bf42cfd7SJustin Bogner       pushRegion(OutCount);
771ee02499aSAlex Lorenz   }
772ee02499aSAlex Lorenz 
773ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
774bf42cfd7SJustin Bogner     extendRegion(S);
775bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
776ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
777bf42cfd7SJustin Bogner 
778bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
779bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
780bf42cfd7SJustin Bogner 
781ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
782bf42cfd7SJustin Bogner     extendRegion(S->getBody());
783bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
784ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
785bf42cfd7SJustin Bogner 
7861587432dSJustin Bogner     Counter LoopCount =
7871587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
7881587432dSJustin Bogner     Counter OutCount =
7891587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
790bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
791bf42cfd7SJustin Bogner       pushRegion(OutCount);
792ee02499aSAlex Lorenz   }
793ee02499aSAlex Lorenz 
794ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
795bf42cfd7SJustin Bogner     extendRegion(S);
796ee02499aSAlex Lorenz     Visit(S->getElement());
797bf42cfd7SJustin Bogner 
798bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
799bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
800bf42cfd7SJustin Bogner 
801ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
802bf42cfd7SJustin Bogner     extendRegion(S->getBody());
803bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
804ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
805bf42cfd7SJustin Bogner 
8061587432dSJustin Bogner     Counter LoopCount =
8071587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
8081587432dSJustin Bogner     Counter OutCount =
8091587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
810bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
811bf42cfd7SJustin Bogner       pushRegion(OutCount);
812ee02499aSAlex Lorenz   }
813ee02499aSAlex Lorenz 
814ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
815bf42cfd7SJustin Bogner     extendRegion(S);
816f2a6ec55SVedant Kumar     if (S->getInit())
817f2a6ec55SVedant Kumar       Visit(S->getInit());
818ee02499aSAlex Lorenz     Visit(S->getCond());
819bf42cfd7SJustin Bogner 
820ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
821bf42cfd7SJustin Bogner 
822bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
823bf42cfd7SJustin Bogner     extendRegion(Body);
824bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
825bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
826bf42cfd7SJustin Bogner         // The body of the switch needs a zero region so that fallthrough counts
827bf42cfd7SJustin Bogner         // behave correctly, but it would be misleading to include the braces of
828bf42cfd7SJustin Bogner         // the compound statement in the zeroed area, so we need to handle this
829bf42cfd7SJustin Bogner         // specially.
830bf42cfd7SJustin Bogner         size_t Index =
831bf42cfd7SJustin Bogner             pushRegion(Counter::getZero(), getStart(CS->body_front()),
832bf42cfd7SJustin Bogner                        getEnd(CS->body_back()));
833b5841332SRichard Trieu         for (const auto *Child : CS->children())
834bf42cfd7SJustin Bogner           Visit(Child);
835bf42cfd7SJustin Bogner         popRegions(Index);
836ee02499aSAlex Lorenz       }
83787ea3b05SVedant Kumar     } else
838bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
839ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
840bf42cfd7SJustin Bogner 
841ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
842ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
843ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
844bf42cfd7SJustin Bogner 
845bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
8463836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
84708780529SAlex Lorenz     pushRegion(ExitCount);
84808780529SAlex Lorenz 
84908780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
85008780529SAlex Lorenz     // in a different file.
85108780529SAlex Lorenz     MostRecentLocation = getStart(S);
8523836482aSVedant Kumar     handleFileExit(ExitLoc);
853ee02499aSAlex Lorenz   }
854ee02499aSAlex Lorenz 
855bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
856bf42cfd7SJustin Bogner     extendRegion(S);
857ee02499aSAlex Lorenz 
858bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
859bf42cfd7SJustin Bogner 
860bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
861bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
862bf42cfd7SJustin Bogner     // the first case in a switch.
863bf42cfd7SJustin Bogner     if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
864bf42cfd7SJustin Bogner       Parent.setCounter(Count);
865bf42cfd7SJustin Bogner     else
866bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
867bf42cfd7SJustin Bogner 
868376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
869bf42cfd7SJustin Bogner       Visit(CS->getLHS());
870bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
871bf42cfd7SJustin Bogner         Visit(RHS);
872bf42cfd7SJustin Bogner     }
873ee02499aSAlex Lorenz     Visit(S->getSubStmt());
874ee02499aSAlex Lorenz   }
875ee02499aSAlex Lorenz 
876ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
877bf42cfd7SJustin Bogner     extendRegion(S);
8789d2a16b9SVedant Kumar     if (S->getInit())
8799d2a16b9SVedant Kumar       Visit(S->getInit());
8809d2a16b9SVedant Kumar 
881055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
882055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
883055ebc34SJustin Bogner     extendRegion(S->getCond());
884ee02499aSAlex Lorenz 
885bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
886bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
887ee02499aSAlex Lorenz 
88891f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
88991f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
89091f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
89191f2e3c9SJustin Bogner 
892bf42cfd7SJustin Bogner     extendRegion(S->getThen());
893bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
894bf42cfd7SJustin Bogner 
895bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
896bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
897bf42cfd7SJustin Bogner       extendRegion(S->getElse());
898bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
899bf42cfd7SJustin Bogner     } else
900bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
901bf42cfd7SJustin Bogner 
902bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
903bf42cfd7SJustin Bogner       pushRegion(OutCount);
904ee02499aSAlex Lorenz   }
905ee02499aSAlex Lorenz 
906ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
907bf42cfd7SJustin Bogner     extendRegion(S);
908049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
909049908b2SVedant Kumar     extendRegion(S->getTryBlock());
910049908b2SVedant Kumar 
911049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
912049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
913049908b2SVedant Kumar 
914ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
915ee02499aSAlex Lorenz       Visit(S->getHandler(I));
916bf42cfd7SJustin Bogner 
917bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
918bf42cfd7SJustin Bogner     pushRegion(ExitCount);
919ee02499aSAlex Lorenz   }
920ee02499aSAlex Lorenz 
921ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
922bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
923ee02499aSAlex Lorenz   }
924ee02499aSAlex Lorenz 
925ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
926bf42cfd7SJustin Bogner     extendRegion(E);
927ee02499aSAlex Lorenz 
928bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
929bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
930ee02499aSAlex Lorenz 
931e3654ce7SJustin Bogner     Visit(E->getCond());
932e3654ce7SJustin Bogner 
933e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
934e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
935bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
936e3654ce7SJustin Bogner     }
937e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
938bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
939bf42cfd7SJustin Bogner                     E->getFalseExpr());
940ee02499aSAlex Lorenz   }
941ee02499aSAlex Lorenz 
942ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
943bf42cfd7SJustin Bogner     extendRegion(E);
944ee02499aSAlex Lorenz     Visit(E->getLHS());
945bf42cfd7SJustin Bogner 
946bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
947bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
948ee02499aSAlex Lorenz   }
949ee02499aSAlex Lorenz 
950ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
951bf42cfd7SJustin Bogner     extendRegion(E);
952ee02499aSAlex Lorenz     Visit(E->getLHS());
953ee02499aSAlex Lorenz 
954bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
955bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
95601a0d062SAlex Lorenz   }
957c109102eSJustin Bogner 
958c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
959c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
960c109102eSJustin Bogner     // propagate counts into them.
961c109102eSJustin Bogner   }
962ee02499aSAlex Lorenz };
963ee02499aSAlex Lorenz 
9641f39fcf2SXinliang David Li std::string getCoverageSection(const CodeGenModule &CGM) {
965*8a767a43SVedant Kumar   return llvm::getInstrProfSectionName(
966*8a767a43SVedant Kumar       llvm::IPSK_covmap,
967*8a767a43SVedant Kumar       CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
968ee02499aSAlex Lorenz }
969ee02499aSAlex Lorenz 
97014f8fb68SVedant Kumar std::string normalizeFilename(StringRef Filename) {
97114f8fb68SVedant Kumar   llvm::SmallString<256> Path(Filename);
97214f8fb68SVedant Kumar   llvm::sys::fs::make_absolute(Path);
973d04929d8SVedant Kumar   llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
97414f8fb68SVedant Kumar   return Path.str().str();
97514f8fb68SVedant Kumar }
97614f8fb68SVedant Kumar 
97714f8fb68SVedant Kumar } // end anonymous namespace
97814f8fb68SVedant Kumar 
979a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
980a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
981a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
982a432d176SJustin Bogner   OS << FunctionName << ":\n";
983a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
984a432d176SJustin Bogner   for (const auto &R : Regions) {
985f2cf38e0SAlex Lorenz     OS.indent(2);
986f2cf38e0SAlex Lorenz     switch (R.Kind) {
987f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
988f2cf38e0SAlex Lorenz       break;
989f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
990f2cf38e0SAlex Lorenz       OS << "Expansion,";
991f2cf38e0SAlex Lorenz       break;
992f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
993f2cf38e0SAlex Lorenz       OS << "Skipped,";
994f2cf38e0SAlex Lorenz       break;
995f2cf38e0SAlex Lorenz     }
996f2cf38e0SAlex Lorenz 
9974da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
9984da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
999f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1000f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
10014da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
10024da909b2SJustin Bogner     OS << "\n";
1003f2cf38e0SAlex Lorenz   }
1004f2cf38e0SAlex Lorenz }
1005f2cf38e0SAlex Lorenz 
1006ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord(
10072129ae53SXinliang David Li     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1008848da137SXinliang David Li     const std::string &CoverageMapping, bool IsUsed) {
1009ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1010ee02499aSAlex Lorenz   if (!FunctionRecordTy) {
1011a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1012a026a437SXinliang David Li     llvm::Type *FunctionRecordTypes[] = {
1013a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1014a026a437SXinliang David Li     };
1015ee02499aSAlex Lorenz     FunctionRecordTy =
10164dc5adc7SJustin Bogner         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
10174dc5adc7SJustin Bogner                               /*isPacked=*/true);
1018ee02499aSAlex Lorenz   }
1019ee02499aSAlex Lorenz 
1020a026a437SXinliang David Li   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1021ee02499aSAlex Lorenz   llvm::Constant *FunctionRecordVals[] = {
1022a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1023a026a437SXinliang David Li   };
1024ee02499aSAlex Lorenz   FunctionRecords.push_back(llvm::ConstantStruct::get(
1025ee02499aSAlex Lorenz       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
1026848da137SXinliang David Li   if (!IsUsed)
10272129ae53SXinliang David Li     FunctionNames.push_back(
10282129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1029ca3326c0SVedant Kumar   CoverageMappings.push_back(CoverageMapping);
1030f2cf38e0SAlex Lorenz 
1031f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1032f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1033f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1034f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1035f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1036f2cf38e0SAlex Lorenz     // expressions.
1037f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1038f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1039f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1040b31ee819SJordan Rose     llvm::SmallVector<std::string, 16> FilenameStrs;
1041f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1042b31ee819SJordan Rose     FilenameStrs.resize(FileEntries.size());
1043f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1044b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1045b31ee819SJordan Rose       auto I = Entry.second;
1046b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1047b31ee819SJordan Rose       FilenameRefs[I] = FilenameStrs[I];
1048b31ee819SJordan Rose     }
1049a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1050a432d176SJustin Bogner                                     Expressions, Regions);
1051a432d176SJustin Bogner     if (Reader.read())
1052f2cf38e0SAlex Lorenz       return;
1053a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1054f2cf38e0SAlex Lorenz   }
1055ee02499aSAlex Lorenz }
1056ee02499aSAlex Lorenz 
1057ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1058ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1059ee02499aSAlex Lorenz     return;
1060ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1061ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1062ee02499aSAlex Lorenz 
1063ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1064ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
10659e324dd1SVedant Kumar   llvm::SmallVector<StringRef, 16> FilenameRefs;
1066ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
10679e324dd1SVedant Kumar   FilenameRefs.resize(FileEntries.size());
1068ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1069ee02499aSAlex Lorenz     auto I = Entry.second;
107014f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
10719e324dd1SVedant Kumar     FilenameRefs[I] = FilenameStrs[I];
1072ee02499aSAlex Lorenz   }
1073ee02499aSAlex Lorenz 
10749e324dd1SVedant Kumar   std::string FilenamesAndCoverageMappings;
10759e324dd1SVedant Kumar   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
10769e324dd1SVedant Kumar   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
10779e324dd1SVedant Kumar   std::string RawCoverageMappings =
10789e324dd1SVedant Kumar       llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
10799e324dd1SVedant Kumar   OS << RawCoverageMappings;
10809e324dd1SVedant Kumar   size_t CoverageMappingSize = RawCoverageMappings.size();
10819e324dd1SVedant Kumar   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
10829e324dd1SVedant Kumar   // Append extra zeroes if necessary to ensure that the size of the filenames
10839e324dd1SVedant Kumar   // and coverage mappings is a multiple of 8.
10849e324dd1SVedant Kumar   if (size_t Rem = OS.str().size() % 8) {
10859e324dd1SVedant Kumar     CoverageMappingSize += 8 - Rem;
10869e324dd1SVedant Kumar     for (size_t I = 0, S = 8 - Rem; I < S; ++I)
10879e324dd1SVedant Kumar       OS << '\0';
1088ee02499aSAlex Lorenz   }
1089ee02499aSAlex Lorenz   auto *FilenamesAndMappingsVal =
10909e324dd1SVedant Kumar       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1091ee02499aSAlex Lorenz 
1092ee02499aSAlex Lorenz   // Create the deferred function records array
1093ee02499aSAlex Lorenz   auto RecordsTy =
1094ee02499aSAlex Lorenz       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1095ee02499aSAlex Lorenz   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1096ee02499aSAlex Lorenz 
109720b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
109820b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
109920b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
110020b188c0SXinliang David Li   };
110120b188c0SXinliang David Li   auto CovDataHeaderTy =
110220b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
110320b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
110420b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
110520b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
110620b188c0SXinliang David Li   };
110720b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
110820b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
110920b188c0SXinliang David Li 
1110ee02499aSAlex Lorenz   // Create the coverage data record
111120b188c0SXinliang David Li   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
111220b188c0SXinliang David Li                                 FilenamesAndMappingsVal->getType()};
1113ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
111420b188c0SXinliang David Li   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
111520b188c0SXinliang David Li                                   FilenamesAndMappingsVal};
1116ee02499aSAlex Lorenz   auto CovDataVal =
1117ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
111820b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
111920b188c0SXinliang David Li       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
112020b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1121ee02499aSAlex Lorenz 
1122ee02499aSAlex Lorenz   CovData->setSection(getCoverageSection(CGM));
1123ee02499aSAlex Lorenz   CovData->setAlignment(8);
1124ee02499aSAlex Lorenz 
1125ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1126ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
11272129ae53SXinliang David Li   // Create the deferred function records array
11282129ae53SXinliang David Li   if (!FunctionNames.empty()) {
11292129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
11302129ae53SXinliang David Li                                            FunctionNames.size());
11312129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
11322129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
11332129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
11342129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
11352129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
11367077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
11372129ae53SXinliang David Li   }
1138ee02499aSAlex Lorenz }
1139ee02499aSAlex Lorenz 
1140ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1141ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1142ee02499aSAlex Lorenz   if (It != FileEntries.end())
1143ee02499aSAlex Lorenz     return It->second;
1144ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1145ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1146ee02499aSAlex Lorenz   return FileID;
1147ee02499aSAlex Lorenz }
1148ee02499aSAlex Lorenz 
1149ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1150ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1151ee02499aSAlex Lorenz   assert(CounterMap);
1152e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1153ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1154ee02499aSAlex Lorenz   Walker.write(OS);
1155ee02499aSAlex Lorenz }
1156ee02499aSAlex Lorenz 
1157ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1158ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1159ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1160ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1161ee02499aSAlex Lorenz   Walker.write(OS);
1162ee02499aSAlex Lorenz }
1163