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"
16ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
17bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h"
18ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h"
19bf42cfd7SJustin Bogner #include "llvm/ADT/Optional.h"
20b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
21b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
22b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
230d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
24ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
2514f8fb68SVedant Kumar #include "llvm/Support/Path.h"
26ee02499aSAlex Lorenz 
27ee02499aSAlex Lorenz using namespace clang;
28ee02499aSAlex Lorenz using namespace CodeGen;
29ee02499aSAlex Lorenz using namespace llvm::coverage;
30ee02499aSAlex Lorenz 
313919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
32ee02499aSAlex Lorenz   SkippedRanges.push_back(Range);
33ee02499aSAlex Lorenz }
34ee02499aSAlex Lorenz 
35ee02499aSAlex Lorenz namespace {
36ee02499aSAlex Lorenz 
379fc8faf9SAdrian Prantl /// A region of source code that can be mapped to a counter.
3809c7179bSJustin Bogner class SourceMappingRegion {
39ee02499aSAlex Lorenz   Counter Count;
40ee02499aSAlex Lorenz 
419fc8faf9SAdrian Prantl   /// The region's starting location.
42bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
43ee02499aSAlex Lorenz 
449fc8faf9SAdrian Prantl   /// The region's ending location.
45bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
46ee02499aSAlex Lorenz 
47747b0e29SVedant Kumar   /// Whether this region should be emitted after its parent is emitted.
48747b0e29SVedant Kumar   bool DeferRegion;
49747b0e29SVedant Kumar 
50a1c4deb7SVedant Kumar   /// Whether this region is a gap region. The count from a gap region is set
51a1c4deb7SVedant Kumar   /// as the line execution count if there are no other regions on the line.
52a1c4deb7SVedant Kumar   bool GapRegion;
53a1c4deb7SVedant Kumar 
5409c7179bSJustin Bogner public:
55bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
56a1c4deb7SVedant Kumar                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
57a1c4deb7SVedant Kumar                       bool GapRegion = false)
58747b0e29SVedant Kumar       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
59a1c4deb7SVedant Kumar         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
60ee02499aSAlex Lorenz 
6109c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
6209c7179bSJustin Bogner 
63bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
6409c7179bSJustin Bogner 
65bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
66bf42cfd7SJustin Bogner 
67bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
68bf42cfd7SJustin Bogner 
693cffc4c7SStephen Kelly   SourceLocation getBeginLoc() const {
70bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
71bf42cfd7SJustin Bogner     return *LocStart;
7209c7179bSJustin Bogner   }
7309c7179bSJustin Bogner 
74bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
75ee02499aSAlex Lorenz 
76a14a1f92SVedant Kumar   void setEndLoc(SourceLocation Loc) {
77a14a1f92SVedant Kumar     assert(Loc.isValid() && "Setting an invalid end location");
78a14a1f92SVedant Kumar     LocEnd = Loc;
79a14a1f92SVedant Kumar   }
80ee02499aSAlex Lorenz 
81462c77b4SCraig Topper   SourceLocation getEndLoc() const {
82bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
83bf42cfd7SJustin Bogner     return *LocEnd;
84ee02499aSAlex Lorenz   }
85747b0e29SVedant Kumar 
86747b0e29SVedant Kumar   bool isDeferred() const { return DeferRegion; }
87747b0e29SVedant Kumar 
88747b0e29SVedant Kumar   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
89a1c4deb7SVedant Kumar 
90a1c4deb7SVedant Kumar   bool isGap() const { return GapRegion; }
91a1c4deb7SVedant Kumar 
92a1c4deb7SVedant Kumar   void setGap(bool Gap) { GapRegion = Gap; }
93ee02499aSAlex Lorenz };
94ee02499aSAlex Lorenz 
95d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
96d7369648SVedant Kumar struct SpellingRegion {
97d7369648SVedant Kumar   /// The line where the region starts.
98d7369648SVedant Kumar   unsigned LineStart;
99d7369648SVedant Kumar 
100d7369648SVedant Kumar   /// The column where the region starts.
101d7369648SVedant Kumar   unsigned ColumnStart;
102d7369648SVedant Kumar 
103d7369648SVedant Kumar   /// The line where the region ends.
104d7369648SVedant Kumar   unsigned LineEnd;
105d7369648SVedant Kumar 
106d7369648SVedant Kumar   /// The column where the region ends.
107d7369648SVedant Kumar   unsigned ColumnEnd;
108d7369648SVedant Kumar 
109d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
110d7369648SVedant Kumar                  SourceLocation LocEnd) {
111d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
112d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
113d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
114d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
115d7369648SVedant Kumar   }
116d7369648SVedant Kumar 
117fa8fa044SVedant Kumar   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
118a6e4358fSStephen Kelly       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
119fa8fa044SVedant Kumar 
120d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
121d7369648SVedant Kumar   /// top->bottom, left->right.
122d7369648SVedant Kumar   bool isInSourceOrder() const {
123d7369648SVedant Kumar     return (LineStart < LineEnd) ||
124d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
125d7369648SVedant Kumar   }
126d7369648SVedant Kumar };
127d7369648SVedant Kumar 
1289fc8faf9SAdrian Prantl /// Provides the common functionality for the different
129ee02499aSAlex Lorenz /// coverage mapping region builders.
130ee02499aSAlex Lorenz class CoverageMappingBuilder {
131ee02499aSAlex Lorenz public:
132ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
133ee02499aSAlex Lorenz   SourceManager &SM;
134ee02499aSAlex Lorenz   const LangOptions &LangOpts;
135ee02499aSAlex Lorenz 
136ee02499aSAlex Lorenz private:
1379fc8faf9SAdrian Prantl   /// Map of clang's FileIDs to IDs used for coverage mapping.
138bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
139bf42cfd7SJustin Bogner       FileIDMapping;
140ee02499aSAlex Lorenz 
141ee02499aSAlex Lorenz public:
1429fc8faf9SAdrian Prantl   /// The coverage mapping regions for this function
143ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
1449fc8faf9SAdrian Prantl   /// The source mapping regions for this function.
145f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
146ee02499aSAlex Lorenz 
1479fc8faf9SAdrian Prantl   /// A set of regions which can be used as a filter.
148fc05ee34SIgor Kudrin   ///
149fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
150fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
151fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
152fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
153fc05ee34SIgor Kudrin       SourceRegionFilter;
154fc05ee34SIgor Kudrin 
155ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
156ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
157bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
158ee02499aSAlex Lorenz 
1599fc8faf9SAdrian Prantl   /// Return the precise end location for the given token.
160ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
161bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
162bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
163bf42cfd7SJustin Bogner     unsigned TokLen =
164bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
165bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
166ee02499aSAlex Lorenz   }
167ee02499aSAlex Lorenz 
1689fc8faf9SAdrian Prantl   /// Return the start location of an included file or expanded macro.
169bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
170bf42cfd7SJustin Bogner     if (Loc.isMacroID())
171bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
172bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
173ee02499aSAlex Lorenz   }
174ee02499aSAlex Lorenz 
1759fc8faf9SAdrian Prantl   /// Return the end location of an included file or expanded macro.
176bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
177bf42cfd7SJustin Bogner     if (Loc.isMacroID())
178bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
179f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
180bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
181bf42cfd7SJustin Bogner   }
182ee02499aSAlex Lorenz 
1839fc8faf9SAdrian Prantl   /// Find out where the current file is included or macro is expanded.
184bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
185b5f8171aSRichard Smith     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
186bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
187bf42cfd7SJustin Bogner   }
188bf42cfd7SJustin Bogner 
1899fc8faf9SAdrian Prantl   /// Return true if \c Loc is a location in a built-in macro.
190682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
19199d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
192682bfbf3SJustin Bogner   }
193682bfbf3SJustin Bogner 
1949fc8faf9SAdrian Prantl   /// Check whether \c Loc is included or expanded from \c Parent.
195d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
196d9e1a61dSIgor Kudrin     do {
197d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
198d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
199d9e1a61dSIgor Kudrin         return false;
200d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
201d9e1a61dSIgor Kudrin     return true;
202d9e1a61dSIgor Kudrin   }
203d9e1a61dSIgor Kudrin 
2049fc8faf9SAdrian Prantl   /// Get the start of \c S ignoring macro arguments and builtin macros.
205bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
206f2ceec48SStephen Kelly     SourceLocation Loc = S->getBeginLoc();
207682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
208b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
209bf42cfd7SJustin Bogner     return Loc;
210bf42cfd7SJustin Bogner   }
211bf42cfd7SJustin Bogner 
2129fc8faf9SAdrian Prantl   /// Get the end of \c S ignoring macro arguments and builtin macros.
213bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
2141c301dcbSStephen Kelly     SourceLocation Loc = S->getEndLoc();
215682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
216b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
217f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
218bf42cfd7SJustin Bogner   }
219bf42cfd7SJustin Bogner 
2209fc8faf9SAdrian Prantl   /// Find the set of files we have regions for and assign IDs
221bf42cfd7SJustin Bogner   ///
222bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
223bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
224bf42cfd7SJustin Bogner   /// expansion regions.
225bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
226bf42cfd7SJustin Bogner     FileIDMapping.clear();
227bf42cfd7SJustin Bogner 
228bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
229bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
230bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
231a6e4358fSStephen Kelly       SourceLocation Loc = Region.getBeginLoc();
232bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
233bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
234bf42cfd7SJustin Bogner         continue;
235bf42cfd7SJustin Bogner 
23693205af0SVedant Kumar       // Do not map FileID's associated with system headers.
23793205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
23893205af0SVedant Kumar         continue;
23993205af0SVedant Kumar 
240bf42cfd7SJustin Bogner       unsigned Depth = 0;
241bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
242ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
243bf42cfd7SJustin Bogner         ++Depth;
244bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
245bf42cfd7SJustin Bogner     }
246899d1392SFangrui Song     llvm::stable_sort(FileLocs, llvm::less_second());
247bf42cfd7SJustin Bogner 
248bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
249bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
250bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
251ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
252ee02499aSAlex Lorenz       if (!Entry)
253bf42cfd7SJustin Bogner         continue;
254ee02499aSAlex Lorenz 
255bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
256bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
257bf42cfd7SJustin Bogner     }
258ee02499aSAlex Lorenz   }
259ee02499aSAlex Lorenz 
2609fc8faf9SAdrian Prantl   /// Get the coverage mapping file ID for \c Loc.
261bf42cfd7SJustin Bogner   ///
262bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
263bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
264bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
265bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
266bf42cfd7SJustin Bogner       return Mapping->second.first;
267903678caSJustin Bogner     return None;
268ee02499aSAlex Lorenz   }
269ee02499aSAlex Lorenz 
2709fc8faf9SAdrian Prantl   /// Gather all the regions that were skipped by the preprocessor
271ee02499aSAlex Lorenz   /// using the constructs like #if.
272ee02499aSAlex Lorenz   void gatherSkippedRegions() {
273ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
274ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
275ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
276ee02499aSAlex Lorenz     FileLineRanges.resize(
277ee02499aSAlex Lorenz         FileIDMapping.size(),
278ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
279ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
280ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
281ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
282ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
283ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
284ee02499aSAlex Lorenz     }
285ee02499aSAlex Lorenz 
286ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
287ee02499aSAlex Lorenz     for (const auto &I : SkippedRanges) {
288ee02499aSAlex Lorenz       auto LocStart = I.getBegin();
289ee02499aSAlex Lorenz       auto LocEnd = I.getEnd();
290bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
291bf42cfd7SJustin Bogner              "region spans multiple files");
292ee02499aSAlex Lorenz 
293bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
294903678caSJustin Bogner       if (!CovFileID)
295ee02499aSAlex Lorenz         continue;
296d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
297fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
298d7369648SVedant Kumar           *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
299ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
3002a8c18d9SAlexander Kornienko       // the source code of this function.
301903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
302903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
303ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
304ee02499aSAlex Lorenz     }
305ee02499aSAlex Lorenz   }
306ee02499aSAlex Lorenz 
3079fc8faf9SAdrian Prantl   /// Generate the coverage counter mapping regions from collected
308ee02499aSAlex Lorenz   /// source regions.
309fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
310bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
311bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
312ee02499aSAlex Lorenz 
313a6e4358fSStephen Kelly       SourceLocation LocStart = Region.getBeginLoc();
3148b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
315f59329b0SJustin Bogner 
31693205af0SVedant Kumar       // Ignore regions from system headers.
31793205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
31893205af0SVedant Kumar         continue;
31993205af0SVedant Kumar 
320bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
321bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
322bf42cfd7SJustin Bogner       if (!CovFileID)
323ee02499aSAlex Lorenz         continue;
324ee02499aSAlex Lorenz 
325f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
326bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
327bf42cfd7SJustin Bogner              "region spans multiple files");
328bf42cfd7SJustin Bogner 
329fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
330fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
331fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
332fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
333fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
334fc05ee34SIgor Kudrin         continue;
335fc05ee34SIgor Kudrin 
336d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
337d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
338d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
339a1c4deb7SVedant Kumar 
340a1c4deb7SVedant Kumar       if (Region.isGap()) {
341a1c4deb7SVedant Kumar         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
342a1c4deb7SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
343a1c4deb7SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
344a1c4deb7SVedant Kumar       } else {
345bf42cfd7SJustin Bogner         MappingRegions.push_back(CounterMappingRegion::makeRegion(
346d7369648SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
347d7369648SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
348bf42cfd7SJustin Bogner       }
349bf42cfd7SJustin Bogner     }
350a1c4deb7SVedant Kumar   }
351bf42cfd7SJustin Bogner 
3529fc8faf9SAdrian Prantl   /// Generate expansion regions for each virtual file we've seen.
353fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
354fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
355bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
356bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
357bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
358bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
359ee02499aSAlex Lorenz         continue;
360ee02499aSAlex Lorenz 
361bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
362bf42cfd7SJustin Bogner       if (!ParentFileID)
363bf42cfd7SJustin Bogner         continue;
364bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
365bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
366bf42cfd7SJustin Bogner 
367bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
368bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
369bf42cfd7SJustin Bogner              "region spans multiple files");
370fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
371bf42cfd7SJustin Bogner 
372d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
373d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
374bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
375d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
376d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
377ee02499aSAlex Lorenz     }
378fc05ee34SIgor Kudrin     return Filter;
379ee02499aSAlex Lorenz   }
380ee02499aSAlex Lorenz };
381ee02499aSAlex Lorenz 
3829fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that
383ee02499aSAlex Lorenz /// are not emitted.
384ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
385ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
386ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
387ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
388ee02499aSAlex Lorenz 
389ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
390ee02499aSAlex Lorenz     if (!D->hasBody())
391ee02499aSAlex Lorenz       return;
392ee02499aSAlex Lorenz     auto Body = D->getBody();
393d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
394d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
395d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
396d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
397d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
398d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
399d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
400d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
401d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
402d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
403d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
404d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
405d9e1a61dSIgor Kudrin       }
406d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
407d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
408d9e1a61dSIgor Kudrin         assert(End.isValid() &&
409d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
410d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
411d9e1a61dSIgor Kudrin       }
412d9e1a61dSIgor Kudrin     }
413d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
414ee02499aSAlex Lorenz   }
415ee02499aSAlex Lorenz 
4169fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
417ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
418ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
419bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
420fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
421ee02499aSAlex Lorenz 
422efd319a2SVedant Kumar     if (MappingRegions.empty())
423efd319a2SVedant Kumar       return;
424efd319a2SVedant Kumar 
4255fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
426ee02499aSAlex Lorenz     Writer.write(OS);
427ee02499aSAlex Lorenz   }
428ee02499aSAlex Lorenz };
429ee02499aSAlex Lorenz 
4309fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map
431ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
432ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
433ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
434ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
4359fc8faf9SAdrian Prantl   /// The map of statements to count values.
436ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
437ee02499aSAlex Lorenz 
4389fc8faf9SAdrian Prantl   /// A stack of currently live regions.
439bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
440ee02499aSAlex Lorenz 
441747b0e29SVedant Kumar   /// The currently deferred region: its end location and count can be set once
442747b0e29SVedant Kumar   /// its parent has been popped from the region stack.
443747b0e29SVedant Kumar   Optional<SourceMappingRegion> DeferredRegion;
444747b0e29SVedant Kumar 
445ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
446ee02499aSAlex Lorenz 
4479fc8faf9SAdrian Prantl   /// A location in the most recently visited file or macro.
448bf42cfd7SJustin Bogner   ///
449bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
450bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
451bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
452bf42cfd7SJustin Bogner 
4538046d22aSVedant Kumar   /// Location of the last terminated region.
4548046d22aSVedant Kumar   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
4558046d22aSVedant Kumar 
4569fc8faf9SAdrian Prantl   /// Return a counter for the subtraction of \c RHS from \c LHS
457ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
458ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
459ee02499aSAlex Lorenz   }
460ee02499aSAlex Lorenz 
4619fc8faf9SAdrian Prantl   /// Return a counter for the sum of \c LHS and \c RHS.
462ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
463ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
464ee02499aSAlex Lorenz   }
465ee02499aSAlex Lorenz 
466bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
467bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
468bf42cfd7SJustin Bogner   }
469bf42cfd7SJustin Bogner 
4709fc8faf9SAdrian Prantl   /// Return the region counter for the given statement.
471bf42cfd7SJustin Bogner   ///
472ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
473bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
474bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
475ee02499aSAlex Lorenz   }
476ee02499aSAlex Lorenz 
4779fc8faf9SAdrian Prantl   /// Push a region onto the stack.
478bf42cfd7SJustin Bogner   ///
479bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
480bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
481bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
482bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
483747b0e29SVedant Kumar     if (StartLoc) {
484bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
485747b0e29SVedant Kumar       completeDeferred(Count, MostRecentLocation);
486747b0e29SVedant Kumar     }
487bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
488ee02499aSAlex Lorenz 
489bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
490ee02499aSAlex Lorenz   }
491ee02499aSAlex Lorenz 
492747b0e29SVedant Kumar   /// Complete any pending deferred region by setting its end location and
493747b0e29SVedant Kumar   /// count, and then pushing it onto the region stack.
494747b0e29SVedant Kumar   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
495747b0e29SVedant Kumar     size_t Index = RegionStack.size();
496747b0e29SVedant Kumar     if (!DeferredRegion)
497747b0e29SVedant Kumar       return Index;
498747b0e29SVedant Kumar 
499747b0e29SVedant Kumar     // Consume the pending region.
500747b0e29SVedant Kumar     SourceMappingRegion DR = DeferredRegion.getValue();
501747b0e29SVedant Kumar     DeferredRegion = None;
502747b0e29SVedant Kumar 
503747b0e29SVedant Kumar     // If the region ends in an expansion, find the expansion site.
504a6e4358fSStephen Kelly     FileID StartFile = SM.getFileID(DR.getBeginLoc());
505f9a0d44eSVedant Kumar     if (SM.getFileID(DeferredEndLoc) != StartFile) {
506747b0e29SVedant Kumar       if (isNestedIn(DeferredEndLoc, StartFile)) {
507747b0e29SVedant Kumar         do {
508747b0e29SVedant Kumar           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
509747b0e29SVedant Kumar         } while (StartFile != SM.getFileID(DeferredEndLoc));
510f9a0d44eSVedant Kumar       } else {
511f9a0d44eSVedant Kumar         return Index;
512747b0e29SVedant Kumar       }
513747b0e29SVedant Kumar     }
514747b0e29SVedant Kumar 
515747b0e29SVedant Kumar     // The parent of this deferred region ends where the containing decl ends,
516747b0e29SVedant Kumar     // so the region isn't useful.
517a6e4358fSStephen Kelly     if (DR.getBeginLoc() == DeferredEndLoc)
518747b0e29SVedant Kumar       return Index;
519747b0e29SVedant Kumar 
520747b0e29SVedant Kumar     // If we're visiting statements in non-source order (e.g switch cases or
521747b0e29SVedant Kumar     // a loop condition) we can't construct a sensible deferred region.
522a6e4358fSStephen Kelly     if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
523747b0e29SVedant Kumar       return Index;
524747b0e29SVedant Kumar 
525a1c4deb7SVedant Kumar     DR.setGap(true);
526747b0e29SVedant Kumar     DR.setCounter(Count);
527747b0e29SVedant Kumar     DR.setEndLoc(DeferredEndLoc);
528747b0e29SVedant Kumar     handleFileExit(DeferredEndLoc);
529747b0e29SVedant Kumar     RegionStack.push_back(DR);
530747b0e29SVedant Kumar     return Index;
531747b0e29SVedant Kumar   }
532747b0e29SVedant Kumar 
5338046d22aSVedant Kumar   /// Complete a deferred region created after a terminated region at the
5348046d22aSVedant Kumar   /// top-level.
5358046d22aSVedant Kumar   void completeTopLevelDeferredRegion(Counter Count,
5368046d22aSVedant Kumar                                       SourceLocation DeferredEndLoc) {
5378046d22aSVedant Kumar     if (DeferredRegion || !LastTerminatedRegion)
5388046d22aSVedant Kumar       return;
5398046d22aSVedant Kumar 
5408046d22aSVedant Kumar     if (LastTerminatedRegion->second != RegionStack.size())
5418046d22aSVedant Kumar       return;
5428046d22aSVedant Kumar 
5438046d22aSVedant Kumar     SourceLocation Start = LastTerminatedRegion->first;
5448046d22aSVedant Kumar     if (SM.getFileID(Start) != SM.getMainFileID())
5458046d22aSVedant Kumar       return;
5468046d22aSVedant Kumar 
5478046d22aSVedant Kumar     SourceMappingRegion DR = RegionStack.back();
5488046d22aSVedant Kumar     DR.setStartLoc(Start);
5498046d22aSVedant Kumar     DR.setDeferred(false);
5508046d22aSVedant Kumar     DeferredRegion = DR;
5518046d22aSVedant Kumar     completeDeferred(Count, DeferredEndLoc);
5528046d22aSVedant Kumar   }
5538046d22aSVedant Kumar 
5540c3e3115SVedant Kumar   size_t locationDepth(SourceLocation Loc) {
5550c3e3115SVedant Kumar     size_t Depth = 0;
5560c3e3115SVedant Kumar     while (Loc.isValid()) {
5570c3e3115SVedant Kumar       Loc = getIncludeOrExpansionLoc(Loc);
5580c3e3115SVedant Kumar       Depth++;
5590c3e3115SVedant Kumar     }
5600c3e3115SVedant Kumar     return Depth;
5610c3e3115SVedant Kumar   }
5620c3e3115SVedant Kumar 
5639fc8faf9SAdrian Prantl   /// Pop regions from the stack into the function's list of regions.
564bf42cfd7SJustin Bogner   ///
565bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
566bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
567bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
568bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
569747b0e29SVedant Kumar     bool ParentOfDeferredRegion = false;
570bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
571bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
572bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
573a6e4358fSStephen Kelly         SourceLocation StartLoc = Region.getBeginLoc();
574bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
575bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
576bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
5770c3e3115SVedant Kumar         size_t StartDepth = locationDepth(StartLoc);
5780c3e3115SVedant Kumar         size_t EndDepth = locationDepth(EndLoc);
579bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
5800c3e3115SVedant Kumar           bool UnnestStart = StartDepth >= EndDepth;
5810c3e3115SVedant Kumar           bool UnnestEnd = EndDepth >= StartDepth;
5820c3e3115SVedant Kumar           if (UnnestEnd) {
583bf42cfd7SJustin Bogner             // The region ends in a nested file or macro expansion. Create a
584bf42cfd7SJustin Bogner             // separate region for each expansion.
585bf42cfd7SJustin Bogner             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
586bf42cfd7SJustin Bogner             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
587bf42cfd7SJustin Bogner 
5888545dae2SIgor Kudrin             if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
589bf42cfd7SJustin Bogner               SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
590bf42cfd7SJustin Bogner 
591f14b2078SJustin Bogner             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
592dceaaadfSJustin Bogner             if (EndLoc.isInvalid())
593dceaaadfSJustin Bogner               llvm::report_fatal_error("File exit not handled before popRegions");
5940c3e3115SVedant Kumar             EndDepth--;
595bf42cfd7SJustin Bogner           }
5960c3e3115SVedant Kumar           if (UnnestStart) {
5970c3e3115SVedant Kumar             // The region begins in a nested file or macro expansion. Create a
5980c3e3115SVedant Kumar             // separate region for each expansion.
5990c3e3115SVedant Kumar             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
6000c3e3115SVedant Kumar             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
6010c3e3115SVedant Kumar 
6020c3e3115SVedant Kumar             if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
6030c3e3115SVedant Kumar               SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
6040c3e3115SVedant Kumar 
6050c3e3115SVedant Kumar             StartLoc = getIncludeOrExpansionLoc(StartLoc);
6060c3e3115SVedant Kumar             if (StartLoc.isInvalid())
6070c3e3115SVedant Kumar               llvm::report_fatal_error("File exit not handled before popRegions");
6080c3e3115SVedant Kumar             StartDepth--;
6090c3e3115SVedant Kumar           }
6100c3e3115SVedant Kumar         }
6110c3e3115SVedant Kumar         Region.setStartLoc(StartLoc);
612bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
613bf42cfd7SJustin Bogner 
614bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
615bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
616bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
617bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
618bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
619bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
620bf42cfd7SJustin Bogner 
621a6e4358fSStephen Kelly         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
622fa8fa044SVedant Kumar         assert(SpellingRegion(SM, Region).isInSourceOrder());
623f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
624747b0e29SVedant Kumar 
625747b0e29SVedant Kumar         if (ParentOfDeferredRegion) {
626747b0e29SVedant Kumar           ParentOfDeferredRegion = false;
627747b0e29SVedant Kumar 
628747b0e29SVedant Kumar           // If there's an existing deferred region, keep the old one, because
629747b0e29SVedant Kumar           // it means there are two consecutive returns (or a similar pattern).
630747b0e29SVedant Kumar           if (!DeferredRegion.hasValue() &&
631747b0e29SVedant Kumar               // File IDs aren't gathered within macro expansions, so it isn't
632747b0e29SVedant Kumar               // useful to try and create a deferred region inside of one.
633f9a0d44eSVedant Kumar               !EndLoc.isMacroID())
634747b0e29SVedant Kumar             DeferredRegion =
635747b0e29SVedant Kumar                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
636747b0e29SVedant Kumar         }
637747b0e29SVedant Kumar       } else if (Region.isDeferred()) {
638747b0e29SVedant Kumar         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
639747b0e29SVedant Kumar         ParentOfDeferredRegion = true;
640bf42cfd7SJustin Bogner       }
641bf42cfd7SJustin Bogner       RegionStack.pop_back();
6428046d22aSVedant Kumar 
6438046d22aSVedant Kumar       // If the zero region pushed after the last terminated region no longer
6448046d22aSVedant Kumar       // exists, clear its cached information.
6458046d22aSVedant Kumar       if (LastTerminatedRegion &&
6468046d22aSVedant Kumar           RegionStack.size() < LastTerminatedRegion->second)
6478046d22aSVedant Kumar         LastTerminatedRegion = None;
648bf42cfd7SJustin Bogner     }
649747b0e29SVedant Kumar     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
650ee02499aSAlex Lorenz   }
651ee02499aSAlex Lorenz 
6529fc8faf9SAdrian Prantl   /// Return the currently active region.
653bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
654bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
655bf42cfd7SJustin Bogner     return RegionStack.back();
656ee02499aSAlex Lorenz   }
657ee02499aSAlex Lorenz 
6587225a261SVedant Kumar   /// Propagate counts through the children of \p S if \p VisitChildren is true.
6597225a261SVedant Kumar   /// Otherwise, only emit a count for \p S itself.
6607225a261SVedant Kumar   Counter propagateCounts(Counter TopCount, const Stmt *S,
6617225a261SVedant Kumar                           bool VisitChildren = true) {
6627838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
6637838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
6647838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
6657225a261SVedant Kumar     if (VisitChildren)
666bf42cfd7SJustin Bogner       Visit(S);
667bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
668bf42cfd7SJustin Bogner     popRegions(Index);
66939f01975SVedant Kumar 
67039f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
67139f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
672f2ceec48SStephen Kelly     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
6737838696eSVedant Kumar       MostRecentLocation = EndLoc;
67439f01975SVedant Kumar 
675bf42cfd7SJustin Bogner     return ExitCount;
676ee02499aSAlex Lorenz   }
677ee02499aSAlex Lorenz 
6789fc8faf9SAdrian Prantl   /// Check whether a region with bounds \c StartLoc and \c EndLoc
6790a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
6800a7c9d11SIgor Kudrin   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
6810a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
6820a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
6830a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
684a6e4358fSStephen Kelly                           return Region.getBeginLoc() == StartLoc &&
6850a7c9d11SIgor Kudrin                                  Region.getEndLoc() == EndLoc;
6860a7c9d11SIgor Kudrin                         });
6870a7c9d11SIgor Kudrin   }
6880a7c9d11SIgor Kudrin 
6899fc8faf9SAdrian Prantl   /// Adjust the most recently visited location to \c EndLoc.
690bf42cfd7SJustin Bogner   ///
691bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
692bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
693bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
6940a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
6950a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
6960a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
6970a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
6980a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
69996ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
7000a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
7010a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
7020a7c9d11SIgor Kudrin                              MostRecentLocation))
703bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
704ee02499aSAlex Lorenz   }
705ee02499aSAlex Lorenz 
7069fc8faf9SAdrian Prantl   /// Adjust regions and state when \c NewLoc exits a file.
707bf42cfd7SJustin Bogner   ///
708bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
709bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
710bf42cfd7SJustin Bogner   /// for the exited file.
711bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
712e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
713e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
714bf42cfd7SJustin Bogner       return;
715bf42cfd7SJustin Bogner 
716bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
717bf42cfd7SJustin Bogner     // find the common ancestor.
718bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
719bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
720bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
721bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
722bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
723bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
724bf42cfd7SJustin Bogner         // to adjust our location to the new file.
725bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
726bf42cfd7SJustin Bogner         return;
727bf42cfd7SJustin Bogner       }
728bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
729ee02499aSAlex Lorenz     }
730ee02499aSAlex Lorenz 
731bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
732bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
73357d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
73457d3f145SPete Cooper       if (!I.hasStartLoc())
735bf42cfd7SJustin Bogner         continue;
736a6e4358fSStephen Kelly       SourceLocation Loc = I.getBeginLoc();
737bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
73857d3f145SPete Cooper         ParentCounter = I.getCounter();
739bf42cfd7SJustin Bogner         break;
740ee02499aSAlex Lorenz       }
741bf42cfd7SJustin Bogner 
742bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
743bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
744bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
745bf42cfd7SJustin Bogner         // we've seen this region.
746bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
74757d3f145SPete Cooper           SourceRegions.emplace_back(I.getCounter(), Loc,
748bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
749bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
750ee02499aSAlex Lorenz       }
75157d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
752bf42cfd7SJustin Bogner     }
753bf42cfd7SJustin Bogner 
754bf42cfd7SJustin Bogner     if (ParentCounter) {
755bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
756bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
757bf42cfd7SJustin Bogner       // corresponding to the parent.
758bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
759bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
760bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
761fa8fa044SVedant Kumar         if (StartLocs.insert(FileStart).second) {
762bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
763bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
764fa8fa044SVedant Kumar           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
765fa8fa044SVedant Kumar         }
766bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
767bf42cfd7SJustin Bogner       }
768bf42cfd7SJustin Bogner     }
769bf42cfd7SJustin Bogner 
770bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
771bf42cfd7SJustin Bogner   }
772bf42cfd7SJustin Bogner 
7739fc8faf9SAdrian Prantl   /// Ensure that \c S is included in the current region.
774bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
775bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
776bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
777bf42cfd7SJustin Bogner 
778bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
779bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
780bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
781747b0e29SVedant Kumar 
782747b0e29SVedant Kumar     completeDeferred(Region.getCounter(), StartLoc);
783bf42cfd7SJustin Bogner   }
784bf42cfd7SJustin Bogner 
7859fc8faf9SAdrian Prantl   /// Mark \c S as a terminator, starting a zero region.
786bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
787bf42cfd7SJustin Bogner     extendRegion(S);
788bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
7898046d22aSVedant Kumar     SourceLocation EndLoc = getEnd(S);
790bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
7918046d22aSVedant Kumar       Region.setEndLoc(EndLoc);
792bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
7938046d22aSVedant Kumar     auto &ZeroRegion = getRegion();
7948046d22aSVedant Kumar     ZeroRegion.setDeferred(true);
7958046d22aSVedant Kumar     LastTerminatedRegion = {EndLoc, RegionStack.size()};
796bf42cfd7SJustin Bogner   }
797ee02499aSAlex Lorenz 
798fa8fa044SVedant Kumar   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
799fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
800fa8fa044SVedant Kumar                                            SourceLocation BeforeLoc) {
801fa8fa044SVedant Kumar     // If the start and end locations of the gap are both within the same macro
802fa8fa044SVedant Kumar     // file, the range may not be in source order.
803fa8fa044SVedant Kumar     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
804fa8fa044SVedant Kumar       return None;
805fa8fa044SVedant Kumar     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
806fa8fa044SVedant Kumar       return None;
807fa8fa044SVedant Kumar     return {{AfterLoc, BeforeLoc}};
808fa8fa044SVedant Kumar   }
809fa8fa044SVedant Kumar 
810fa8fa044SVedant Kumar   /// Find the source range after \p AfterStmt and before \p BeforeStmt.
811fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
812fa8fa044SVedant Kumar                                            const Stmt *BeforeStmt) {
813fa8fa044SVedant Kumar     return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
814fa8fa044SVedant Kumar                               getStart(BeforeStmt));
815fa8fa044SVedant Kumar   }
816fa8fa044SVedant Kumar 
8172e8c8759SVedant Kumar   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
8182e8c8759SVedant Kumar   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
8192e8c8759SVedant Kumar                             Counter Count) {
820fa8fa044SVedant Kumar     if (StartLoc == EndLoc)
8212e8c8759SVedant Kumar       return;
822fa8fa044SVedant Kumar     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
8232e8c8759SVedant Kumar     handleFileExit(StartLoc);
8242e8c8759SVedant Kumar     size_t Index = pushRegion(Count, StartLoc, EndLoc);
8252e8c8759SVedant Kumar     getRegion().setGap(true);
8262e8c8759SVedant Kumar     handleFileExit(EndLoc);
8272e8c8759SVedant Kumar     popRegions(Index);
8282e8c8759SVedant Kumar   }
8292e8c8759SVedant Kumar 
8309fc8faf9SAdrian Prantl   /// Keep counts of breaks and continues inside loops.
831ee02499aSAlex Lorenz   struct BreakContinue {
832ee02499aSAlex Lorenz     Counter BreakCount;
833ee02499aSAlex Lorenz     Counter ContinueCount;
834ee02499aSAlex Lorenz   };
835ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
836ee02499aSAlex Lorenz 
837ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
838ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
839e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
840ee02499aSAlex Lorenz       const LangOptions &LangOpts)
841747b0e29SVedant Kumar       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
842747b0e29SVedant Kumar         DeferredRegion(None) {}
843ee02499aSAlex Lorenz 
8449fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
845ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
846ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
847bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
848fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
849747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
850fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
851ee02499aSAlex Lorenz     gatherSkippedRegions();
852ee02499aSAlex Lorenz 
853efd319a2SVedant Kumar     if (MappingRegions.empty())
854efd319a2SVedant Kumar       return;
855efd319a2SVedant Kumar 
8564da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
8574da909b2SJustin Bogner                                  MappingRegions);
858ee02499aSAlex Lorenz     Writer.write(OS);
859ee02499aSAlex Lorenz   }
860ee02499aSAlex Lorenz 
861ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
862f2ceec48SStephen Kelly     if (S->getBeginLoc().isValid())
863bf42cfd7SJustin Bogner       extendRegion(S);
864642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
865642f173aSBenjamin Kramer       if (Child)
866642f173aSBenjamin Kramer         this->Visit(Child);
867bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
868ee02499aSAlex Lorenz   }
869ee02499aSAlex Lorenz 
870ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
871747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
872747b0e29SVedant Kumar 
873bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
874efd319a2SVedant Kumar 
875efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
876efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
877efd319a2SVedant Kumar       return;
878efd319a2SVedant Kumar 
8797225a261SVedant Kumar     // Do not visit the artificial children nodes of defaulted methods. The
8807225a261SVedant Kumar     // lexer may not be able to report back precise token end locations for
8817225a261SVedant Kumar     // these children nodes (llvm.org/PR39822), and moreover users will not be
8827225a261SVedant Kumar     // able to see coverage for them.
8837225a261SVedant Kumar     bool Defaulted = false;
8847225a261SVedant Kumar     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
8857225a261SVedant Kumar       Defaulted = Method->isDefaulted();
8867225a261SVedant Kumar 
8877225a261SVedant Kumar     propagateCounts(getRegionCounter(Body), Body,
8887225a261SVedant Kumar                     /*VisitChildren=*/!Defaulted);
889747b0e29SVedant Kumar     assert(RegionStack.empty() && "Regions entered but never exited");
890747b0e29SVedant Kumar 
89161763b65SVedant Kumar     // Discard the last uncompleted deferred region in a decl, if one exists.
89261763b65SVedant Kumar     // This prevents lines at the end of a function containing only whitespace
89361763b65SVedant Kumar     // or closing braces from being marked as uncovered.
894ef8e05ffSVedant Kumar     DeferredRegion = None;
895341bf429SVedant Kumar   }
896ee02499aSAlex Lorenz 
897ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
898bf42cfd7SJustin Bogner     extendRegion(S);
899ee02499aSAlex Lorenz     if (S->getRetValue())
900ee02499aSAlex Lorenz       Visit(S->getRetValue());
901bf42cfd7SJustin Bogner     terminateRegion(S);
902ee02499aSAlex Lorenz   }
903ee02499aSAlex Lorenz 
904f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
905f959febfSJustin Bogner     extendRegion(E);
906f959febfSJustin Bogner     if (E->getSubExpr())
907f959febfSJustin Bogner       Visit(E->getSubExpr());
908f959febfSJustin Bogner     terminateRegion(E);
909f959febfSJustin Bogner   }
910f959febfSJustin Bogner 
911bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
912ee02499aSAlex Lorenz 
913ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
9148046d22aSVedant Kumar     Counter LabelCount = getRegionCounter(S);
915bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
9168046d22aSVedant Kumar     completeTopLevelDeferredRegion(LabelCount, Start);
917d781d97eSVedant Kumar     completeDeferred(LabelCount, Start);
918bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
919bf42cfd7SJustin Bogner     handleFileExit(Start);
9208046d22aSVedant Kumar     pushRegion(LabelCount, Start);
921ee02499aSAlex Lorenz     Visit(S->getSubStmt());
922ee02499aSAlex Lorenz   }
923ee02499aSAlex Lorenz 
924ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
925ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
926ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
927bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
9287f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
9297f53fbfcSEli Friedman     // case statements, not just the most recent one.
930bf42cfd7SJustin Bogner     terminateRegion(S);
931ee02499aSAlex Lorenz   }
932ee02499aSAlex Lorenz 
933ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
934ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
935ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
936bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
937bf42cfd7SJustin Bogner     terminateRegion(S);
938ee02499aSAlex Lorenz   }
939ee02499aSAlex Lorenz 
940181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
941181dfe4cSEli Friedman     VisitStmt(E);
942181dfe4cSEli Friedman 
943181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
944181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
945181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
946181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
947181dfe4cSEli Friedman       terminateRegion(E);
948181dfe4cSEli Friedman   }
949181dfe4cSEli Friedman 
950ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
951bf42cfd7SJustin Bogner     extendRegion(S);
952ee02499aSAlex Lorenz 
953bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
954bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
955bf42cfd7SJustin Bogner 
956bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
957bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
958bf42cfd7SJustin Bogner     extendRegion(S->getBody());
959bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
960ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
961bf42cfd7SJustin Bogner 
962bf42cfd7SJustin Bogner     // Go back to handle the condition.
963bf42cfd7SJustin Bogner     Counter CondCount =
964bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
965bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
966bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
967bf42cfd7SJustin Bogner 
968fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
969fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
970fa8fa044SVedant Kumar     if (Gap)
971fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
972fa8fa044SVedant Kumar 
973bf42cfd7SJustin Bogner     Counter OutCount =
974bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
975bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
976bf42cfd7SJustin Bogner       pushRegion(OutCount);
977ee02499aSAlex Lorenz   }
978ee02499aSAlex Lorenz 
979ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
980bf42cfd7SJustin Bogner     extendRegion(S);
981ee02499aSAlex Lorenz 
982bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
983bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
984bf42cfd7SJustin Bogner 
985bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
986bf42cfd7SJustin Bogner     extendRegion(S->getBody());
987bf42cfd7SJustin Bogner     Counter BackedgeCount =
988bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
989ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
990bf42cfd7SJustin Bogner 
991bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
992bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
993bf42cfd7SJustin Bogner 
994bf42cfd7SJustin Bogner     Counter OutCount =
995bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
996bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
997bf42cfd7SJustin Bogner       pushRegion(OutCount);
998ee02499aSAlex Lorenz   }
999ee02499aSAlex Lorenz 
1000ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
1001bf42cfd7SJustin Bogner     extendRegion(S);
1002ee02499aSAlex Lorenz     if (S->getInit())
1003ee02499aSAlex Lorenz       Visit(S->getInit());
1004ee02499aSAlex Lorenz 
1005bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1006bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1007bf42cfd7SJustin Bogner 
10083e2ae49aSVedant Kumar     // The loop increment may contain a break or continue.
10093e2ae49aSVedant Kumar     if (S->getInc())
10103e2ae49aSVedant Kumar       BreakContinueStack.emplace_back();
10113e2ae49aSVedant Kumar 
1012bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
10133e2ae49aSVedant Kumar     BreakContinueStack.emplace_back();
1014bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1015bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
10163e2ae49aSVedant Kumar     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1017ee02499aSAlex Lorenz 
1018ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
1019ee02499aSAlex Lorenz     // the count for all the continue statements.
10203e2ae49aSVedant Kumar     BreakContinue IncrementBC;
10213e2ae49aSVedant Kumar     if (const Stmt *Inc = S->getInc()) {
10223e2ae49aSVedant Kumar       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
10233e2ae49aSVedant Kumar       IncrementBC = BreakContinueStack.pop_back_val();
10243e2ae49aSVedant Kumar     }
1025bf42cfd7SJustin Bogner 
1026bf42cfd7SJustin Bogner     // Go back to handle the condition.
10273e2ae49aSVedant Kumar     Counter CondCount = addCounters(
10283e2ae49aSVedant Kumar         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
10293e2ae49aSVedant Kumar         IncrementBC.ContinueCount);
1030bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
1031bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
1032bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
1033ee02499aSAlex Lorenz     }
1034ee02499aSAlex Lorenz 
1035fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1036fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1037fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1038fa8fa044SVedant Kumar     if (Gap)
1039fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1040fa8fa044SVedant Kumar 
10413e2ae49aSVedant Kumar     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
10423e2ae49aSVedant Kumar                                    subtractCounters(CondCount, BodyCount));
1043bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1044bf42cfd7SJustin Bogner       pushRegion(OutCount);
1045ee02499aSAlex Lorenz   }
1046ee02499aSAlex Lorenz 
1047ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1048bf42cfd7SJustin Bogner     extendRegion(S);
10498baa5001SRichard Smith     if (S->getInit())
10508baa5001SRichard Smith       Visit(S->getInit());
1051bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
1052ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
1053bf42cfd7SJustin Bogner 
1054bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1055bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1056bf42cfd7SJustin Bogner 
1057ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1058bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1059bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1060ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1061bf42cfd7SJustin Bogner 
1062fa8fa044SVedant Kumar     // The body count applies to the area immediately after the range.
1063fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1064fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1065fa8fa044SVedant Kumar     if (Gap)
1066fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1067fa8fa044SVedant Kumar 
10681587432dSJustin Bogner     Counter LoopCount =
10691587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
10701587432dSJustin Bogner     Counter OutCount =
10711587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1072bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1073bf42cfd7SJustin Bogner       pushRegion(OutCount);
1074ee02499aSAlex Lorenz   }
1075ee02499aSAlex Lorenz 
1076ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1077bf42cfd7SJustin Bogner     extendRegion(S);
1078ee02499aSAlex Lorenz     Visit(S->getElement());
1079bf42cfd7SJustin Bogner 
1080bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1081bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1082bf42cfd7SJustin Bogner 
1083ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1084bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1085bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1086ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1087bf42cfd7SJustin Bogner 
1088fa8fa044SVedant Kumar     // The body count applies to the area immediately after the collection.
1089fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1090fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1091fa8fa044SVedant Kumar     if (Gap)
1092fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1093fa8fa044SVedant Kumar 
10941587432dSJustin Bogner     Counter LoopCount =
10951587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
10961587432dSJustin Bogner     Counter OutCount =
10971587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1098bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1099bf42cfd7SJustin Bogner       pushRegion(OutCount);
1100ee02499aSAlex Lorenz   }
1101ee02499aSAlex Lorenz 
1102ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
1103bf42cfd7SJustin Bogner     extendRegion(S);
1104f2a6ec55SVedant Kumar     if (S->getInit())
1105f2a6ec55SVedant Kumar       Visit(S->getInit());
1106ee02499aSAlex Lorenz     Visit(S->getCond());
1107bf42cfd7SJustin Bogner 
1108ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1109bf42cfd7SJustin Bogner 
1110bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
1111bf42cfd7SJustin Bogner     extendRegion(Body);
1112bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1113bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
11147f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
11157f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
11167f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
1117bf42cfd7SJustin Bogner         size_t Index =
11187f53fbfcSEli Friedman             pushRegion(Counter::getZero(), getStart(CS->body_front()));
1119b5841332SRichard Trieu         for (const auto *Child : CS->children())
1120bf42cfd7SJustin Bogner           Visit(Child);
11217f53fbfcSEli Friedman 
11227f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
11237f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
11247f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
11257f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
11267f53fbfcSEli Friedman         }
11277f53fbfcSEli Friedman 
1128bf42cfd7SJustin Bogner         popRegions(Index);
1129ee02499aSAlex Lorenz       }
113087ea3b05SVedant Kumar     } else
1131bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
1132ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1133bf42cfd7SJustin Bogner 
1134ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
1135ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
1136ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1137bf42cfd7SJustin Bogner 
1138bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
11393836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
114008780529SAlex Lorenz     pushRegion(ExitCount);
114108780529SAlex Lorenz 
114208780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
114308780529SAlex Lorenz     // in a different file.
114408780529SAlex Lorenz     MostRecentLocation = getStart(S);
11453836482aSVedant Kumar     handleFileExit(ExitLoc);
1146ee02499aSAlex Lorenz   }
1147ee02499aSAlex Lorenz 
1148bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
1149bf42cfd7SJustin Bogner     extendRegion(S);
1150ee02499aSAlex Lorenz 
1151bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
1152bf42cfd7SJustin Bogner 
1153bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1154bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
1155bf42cfd7SJustin Bogner     // the first case in a switch.
1156a6e4358fSStephen Kelly     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1157bf42cfd7SJustin Bogner       Parent.setCounter(Count);
1158bf42cfd7SJustin Bogner     else
1159bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
1160bf42cfd7SJustin Bogner 
1161376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1162bf42cfd7SJustin Bogner       Visit(CS->getLHS());
1163bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
1164bf42cfd7SJustin Bogner         Visit(RHS);
1165bf42cfd7SJustin Bogner     }
1166ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1167ee02499aSAlex Lorenz   }
1168ee02499aSAlex Lorenz 
1169ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
1170bf42cfd7SJustin Bogner     extendRegion(S);
11719d2a16b9SVedant Kumar     if (S->getInit())
11729d2a16b9SVedant Kumar       Visit(S->getInit());
11739d2a16b9SVedant Kumar 
1174055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
1175055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
1176055ebc34SJustin Bogner     extendRegion(S->getCond());
1177ee02499aSAlex Lorenz 
1178bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1179bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
1180ee02499aSAlex Lorenz 
118191f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
118291f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
118391f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
118491f2e3c9SJustin Bogner 
11852e8c8759SVedant Kumar     // The 'then' count applies to the area immediately after the condition.
1186fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1187fa8fa044SVedant Kumar     if (Gap)
1188fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
11892e8c8759SVedant Kumar 
1190bf42cfd7SJustin Bogner     extendRegion(S->getThen());
1191bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1192bf42cfd7SJustin Bogner 
1193bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1194bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
11952e8c8759SVedant Kumar       // The 'else' count applies to the area immediately after the 'then'.
1196fa8fa044SVedant Kumar       Gap = findGapAreaBetween(S->getThen(), Else);
1197fa8fa044SVedant Kumar       if (Gap)
1198fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
11992e8c8759SVedant Kumar       extendRegion(Else);
1200bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1201bf42cfd7SJustin Bogner     } else
1202bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
1203bf42cfd7SJustin Bogner 
1204bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1205bf42cfd7SJustin Bogner       pushRegion(OutCount);
1206ee02499aSAlex Lorenz   }
1207ee02499aSAlex Lorenz 
1208ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
1209bf42cfd7SJustin Bogner     extendRegion(S);
1210049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
1211049908b2SVedant Kumar     extendRegion(S->getTryBlock());
1212049908b2SVedant Kumar 
1213049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
1214049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
1215049908b2SVedant Kumar 
1216ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1217ee02499aSAlex Lorenz       Visit(S->getHandler(I));
1218bf42cfd7SJustin Bogner 
1219bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
1220bf42cfd7SJustin Bogner     pushRegion(ExitCount);
1221ee02499aSAlex Lorenz   }
1222ee02499aSAlex Lorenz 
1223ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1224bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1225ee02499aSAlex Lorenz   }
1226ee02499aSAlex Lorenz 
1227ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1228bf42cfd7SJustin Bogner     extendRegion(E);
1229ee02499aSAlex Lorenz 
1230bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1231bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
1232ee02499aSAlex Lorenz 
1233e3654ce7SJustin Bogner     Visit(E->getCond());
1234e3654ce7SJustin Bogner 
1235e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
12362e8c8759SVedant Kumar       // The 'then' count applies to the area immediately after the condition.
1237fa8fa044SVedant Kumar       auto Gap =
1238fa8fa044SVedant Kumar           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1239fa8fa044SVedant Kumar       if (Gap)
1240fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
12412e8c8759SVedant Kumar 
1242e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
1243bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
1244e3654ce7SJustin Bogner     }
12452e8c8759SVedant Kumar 
1246e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
1247bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
1248bf42cfd7SJustin Bogner                     E->getFalseExpr());
1249ee02499aSAlex Lorenz   }
1250ee02499aSAlex Lorenz 
1251ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
1252e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1253e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1254e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1255bf42cfd7SJustin Bogner 
1256bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1257bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
1258ee02499aSAlex Lorenz   }
1259ee02499aSAlex Lorenz 
1260ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
1261e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1262e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1263e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1264ee02499aSAlex Lorenz 
1265bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1266bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
126701a0d062SAlex Lorenz   }
1268c109102eSJustin Bogner 
1269c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
1270c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
1271c109102eSJustin Bogner     // propagate counts into them.
1272c109102eSJustin Bogner   }
1273ee02499aSAlex Lorenz };
1274ee02499aSAlex Lorenz 
12751f39fcf2SXinliang David Li std::string getCoverageSection(const CodeGenModule &CGM) {
12768a767a43SVedant Kumar   return llvm::getInstrProfSectionName(
12778a767a43SVedant Kumar       llvm::IPSK_covmap,
12788a767a43SVedant Kumar       CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1279ee02499aSAlex Lorenz }
1280ee02499aSAlex Lorenz 
1281*7cd595dfSReid Kleckner std::string normalizeFilename(StringRef Filename) {
1282*7cd595dfSReid Kleckner   llvm::SmallString<256> Path(Filename);
1283*7cd595dfSReid Kleckner   llvm::sys::fs::make_absolute(Path);
1284*7cd595dfSReid Kleckner   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1285*7cd595dfSReid Kleckner   return Path.str().str();
1286*7cd595dfSReid Kleckner }
1287*7cd595dfSReid Kleckner 
128814f8fb68SVedant Kumar } // end anonymous namespace
128914f8fb68SVedant Kumar 
1290a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1291a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1292a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1293a432d176SJustin Bogner   OS << FunctionName << ":\n";
1294a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1295a432d176SJustin Bogner   for (const auto &R : Regions) {
1296f2cf38e0SAlex Lorenz     OS.indent(2);
1297f2cf38e0SAlex Lorenz     switch (R.Kind) {
1298f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1299f2cf38e0SAlex Lorenz       break;
1300f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1301f2cf38e0SAlex Lorenz       OS << "Expansion,";
1302f2cf38e0SAlex Lorenz       break;
1303f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1304f2cf38e0SAlex Lorenz       OS << "Skipped,";
1305f2cf38e0SAlex Lorenz       break;
1306a1c4deb7SVedant Kumar     case CounterMappingRegion::GapRegion:
1307a1c4deb7SVedant Kumar       OS << "Gap,";
1308a1c4deb7SVedant Kumar       break;
1309f2cf38e0SAlex Lorenz     }
1310f2cf38e0SAlex Lorenz 
13114da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
13124da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1313f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1314f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
13154da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
13164da909b2SJustin Bogner     OS << "\n";
1317f2cf38e0SAlex Lorenz   }
1318f2cf38e0SAlex Lorenz }
1319f2cf38e0SAlex Lorenz 
1320ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord(
13212129ae53SXinliang David Li     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1322848da137SXinliang David Li     const std::string &CoverageMapping, bool IsUsed) {
1323ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1324ee02499aSAlex Lorenz   if (!FunctionRecordTy) {
1325a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1326a026a437SXinliang David Li     llvm::Type *FunctionRecordTypes[] = {
1327a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1328a026a437SXinliang David Li     };
1329ee02499aSAlex Lorenz     FunctionRecordTy =
13304dc5adc7SJustin Bogner         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
13314dc5adc7SJustin Bogner                               /*isPacked=*/true);
1332ee02499aSAlex Lorenz   }
1333ee02499aSAlex Lorenz 
1334a026a437SXinliang David Li   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1335ee02499aSAlex Lorenz   llvm::Constant *FunctionRecordVals[] = {
1336a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1337a026a437SXinliang David Li   };
1338ee02499aSAlex Lorenz   FunctionRecords.push_back(llvm::ConstantStruct::get(
1339ee02499aSAlex Lorenz       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
1340848da137SXinliang David Li   if (!IsUsed)
13412129ae53SXinliang David Li     FunctionNames.push_back(
13422129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1343ca3326c0SVedant Kumar   CoverageMappings.push_back(CoverageMapping);
1344f2cf38e0SAlex Lorenz 
1345f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1346f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1347f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1348f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1349f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1350f2cf38e0SAlex Lorenz     // expressions.
1351f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1352f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1353f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1354b31ee819SJordan Rose     llvm::SmallVector<std::string, 16> FilenameStrs;
1355f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1356b31ee819SJordan Rose     FilenameStrs.resize(FileEntries.size());
1357f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1358b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1359b31ee819SJordan Rose       auto I = Entry.second;
1360b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1361b31ee819SJordan Rose       FilenameRefs[I] = FilenameStrs[I];
1362b31ee819SJordan Rose     }
1363a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1364a432d176SJustin Bogner                                     Expressions, Regions);
1365a432d176SJustin Bogner     if (Reader.read())
1366f2cf38e0SAlex Lorenz       return;
1367a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1368f2cf38e0SAlex Lorenz   }
1369ee02499aSAlex Lorenz }
1370ee02499aSAlex Lorenz 
1371ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1372ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1373ee02499aSAlex Lorenz     return;
1374ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1375ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1376ee02499aSAlex Lorenz 
1377ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1378ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
13799e324dd1SVedant Kumar   llvm::SmallVector<StringRef, 16> FilenameRefs;
1380ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
13819e324dd1SVedant Kumar   FilenameRefs.resize(FileEntries.size());
1382ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1383ee02499aSAlex Lorenz     auto I = Entry.second;
138414f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
13859e324dd1SVedant Kumar     FilenameRefs[I] = FilenameStrs[I];
1386ee02499aSAlex Lorenz   }
1387ee02499aSAlex Lorenz 
13889e324dd1SVedant Kumar   std::string FilenamesAndCoverageMappings;
13899e324dd1SVedant Kumar   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
13909e324dd1SVedant Kumar   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
13914cd07dbeSSerge Guelton 
13924cd07dbeSSerge Guelton   // Stream the content of CoverageMappings to OS while keeping
13934cd07dbeSSerge Guelton   // memory consumption under control.
13944cd07dbeSSerge Guelton   size_t CoverageMappingSize = 0;
13954cd07dbeSSerge Guelton   for (auto &S : CoverageMappings) {
13964cd07dbeSSerge Guelton     CoverageMappingSize += S.size();
13974cd07dbeSSerge Guelton     OS << S;
13984cd07dbeSSerge Guelton     S.clear();
13994cd07dbeSSerge Guelton     S.shrink_to_fit();
14004cd07dbeSSerge Guelton   }
14014cd07dbeSSerge Guelton   CoverageMappings.clear();
14024cd07dbeSSerge Guelton   CoverageMappings.shrink_to_fit();
14034cd07dbeSSerge Guelton 
14049e324dd1SVedant Kumar   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
14059e324dd1SVedant Kumar   // Append extra zeroes if necessary to ensure that the size of the filenames
14069e324dd1SVedant Kumar   // and coverage mappings is a multiple of 8.
14079e324dd1SVedant Kumar   if (size_t Rem = OS.str().size() % 8) {
14089e324dd1SVedant Kumar     CoverageMappingSize += 8 - Rem;
1409070777dbSPeter Collingbourne     OS.write_zeros(8 - Rem);
1410ee02499aSAlex Lorenz   }
1411ee02499aSAlex Lorenz   auto *FilenamesAndMappingsVal =
14129e324dd1SVedant Kumar       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1413ee02499aSAlex Lorenz 
1414ee02499aSAlex Lorenz   // Create the deferred function records array
1415ee02499aSAlex Lorenz   auto RecordsTy =
1416ee02499aSAlex Lorenz       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1417ee02499aSAlex Lorenz   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1418ee02499aSAlex Lorenz 
141920b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
142020b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
142120b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
142220b188c0SXinliang David Li   };
142320b188c0SXinliang David Li   auto CovDataHeaderTy =
142420b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
142520b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
142620b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
142720b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
142820b188c0SXinliang David Li   };
142920b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
143020b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
143120b188c0SXinliang David Li 
1432ee02499aSAlex Lorenz   // Create the coverage data record
143320b188c0SXinliang David Li   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
143420b188c0SXinliang David Li                                 FilenamesAndMappingsVal->getType()};
1435ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
143620b188c0SXinliang David Li   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
143720b188c0SXinliang David Li                                   FilenamesAndMappingsVal};
1438ee02499aSAlex Lorenz   auto CovDataVal =
1439ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
144020b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
144120b188c0SXinliang David Li       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
144220b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1443ee02499aSAlex Lorenz 
1444ee02499aSAlex Lorenz   CovData->setSection(getCoverageSection(CGM));
1445c79099e0SGuillaume Chatelet   CovData->setAlignment(llvm::Align(8));
1446ee02499aSAlex Lorenz 
1447ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1448ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
14492129ae53SXinliang David Li   // Create the deferred function records array
14502129ae53SXinliang David Li   if (!FunctionNames.empty()) {
14512129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
14522129ae53SXinliang David Li                                            FunctionNames.size());
14532129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
14542129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
14552129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
14562129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
14572129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
14587077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
14592129ae53SXinliang David Li   }
1460ee02499aSAlex Lorenz }
1461ee02499aSAlex Lorenz 
1462ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1463ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1464ee02499aSAlex Lorenz   if (It != FileEntries.end())
1465ee02499aSAlex Lorenz     return It->second;
1466ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1467ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1468ee02499aSAlex Lorenz   return FileID;
1469ee02499aSAlex Lorenz }
1470ee02499aSAlex Lorenz 
1471ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1472ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1473ee02499aSAlex Lorenz   assert(CounterMap);
1474e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1475ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1476ee02499aSAlex Lorenz   Walker.write(OS);
1477ee02499aSAlex Lorenz }
1478ee02499aSAlex Lorenz 
1479ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1480ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1481ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1482ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1483ee02499aSAlex Lorenz   Walker.write(OS);
1484ee02499aSAlex Lorenz }
1485