1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2ee02499aSAlex Lorenz //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ee02499aSAlex Lorenz //
7ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
8ee02499aSAlex Lorenz //
9ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator
10ee02499aSAlex Lorenz //
11ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
12ee02499aSAlex Lorenz 
13ee02499aSAlex Lorenz #include "CoverageMappingGen.h"
14ee02499aSAlex Lorenz #include "CodeGenFunction.h"
15ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h"
16dd1ea9deSVedant Kumar #include "clang/Basic/Diagnostic.h"
17e08464fbSReid Kleckner #include "clang/Basic/FileManager.h"
18dd1ea9deSVedant Kumar #include "clang/Frontend/FrontendDiagnostic.h"
19ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
20e08464fbSReid Kleckner #include "llvm/ADT/Optional.h"
21bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h"
22ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h"
23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
24b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
260d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
27ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
2814f8fb68SVedant Kumar #include "llvm/Support/Path.h"
29ee02499aSAlex Lorenz 
30dd1ea9deSVedant Kumar // This selects the coverage mapping format defined when `InstrProfData.inc`
31dd1ea9deSVedant Kumar // is textually included.
32dd1ea9deSVedant Kumar #define COVMAP_V3
33dd1ea9deSVedant Kumar 
34ee02499aSAlex Lorenz using namespace clang;
35ee02499aSAlex Lorenz using namespace CodeGen;
36ee02499aSAlex Lorenz using namespace llvm::coverage;
37ee02499aSAlex Lorenz 
38*b46176bbSZequan Wu CoverageSourceInfo *
39*b46176bbSZequan Wu CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
40*b46176bbSZequan Wu   CoverageSourceInfo *CoverageInfo = new CoverageSourceInfo();
41*b46176bbSZequan Wu   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
42*b46176bbSZequan Wu   PP.addCommentHandler(CoverageInfo);
43*b46176bbSZequan Wu   PP.setPreprocessToken(true);
44*b46176bbSZequan Wu   PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
45*b46176bbSZequan Wu     // Update previous token location.
46*b46176bbSZequan Wu     CoverageInfo->PrevTokLoc = Tok.getLocation();
47*b46176bbSZequan Wu     CoverageInfo->updateNextTokLoc(Tok.getLocation());
48*b46176bbSZequan Wu   });
49*b46176bbSZequan Wu   return CoverageInfo;
50*b46176bbSZequan Wu }
51*b46176bbSZequan Wu 
523919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
53*b46176bbSZequan Wu   SkippedRanges.push_back({Range});
54*b46176bbSZequan Wu }
55*b46176bbSZequan Wu 
56*b46176bbSZequan Wu bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
57*b46176bbSZequan Wu   SkippedRanges.push_back({Range, PrevTokLoc});
58*b46176bbSZequan Wu   AfterComment = true;
59*b46176bbSZequan Wu   return false;
60*b46176bbSZequan Wu }
61*b46176bbSZequan Wu 
62*b46176bbSZequan Wu void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
63*b46176bbSZequan Wu   if (AfterComment) {
64*b46176bbSZequan Wu     SkippedRanges.back().NextTokLoc = Loc;
65*b46176bbSZequan Wu     AfterComment = false;
66*b46176bbSZequan Wu   }
67ee02499aSAlex Lorenz }
68ee02499aSAlex Lorenz 
69ee02499aSAlex Lorenz namespace {
70ee02499aSAlex Lorenz 
719fc8faf9SAdrian Prantl /// A region of source code that can be mapped to a counter.
7209c7179bSJustin Bogner class SourceMappingRegion {
73ee02499aSAlex Lorenz   Counter Count;
74ee02499aSAlex Lorenz 
759fc8faf9SAdrian Prantl   /// The region's starting location.
76bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
77ee02499aSAlex Lorenz 
789fc8faf9SAdrian Prantl   /// The region's ending location.
79bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
80ee02499aSAlex Lorenz 
81747b0e29SVedant Kumar   /// Whether this region should be emitted after its parent is emitted.
82747b0e29SVedant Kumar   bool DeferRegion;
83747b0e29SVedant Kumar 
84a1c4deb7SVedant Kumar   /// Whether this region is a gap region. The count from a gap region is set
85a1c4deb7SVedant Kumar   /// as the line execution count if there are no other regions on the line.
86a1c4deb7SVedant Kumar   bool GapRegion;
87a1c4deb7SVedant Kumar 
8809c7179bSJustin Bogner public:
89bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
90a1c4deb7SVedant Kumar                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
91a1c4deb7SVedant Kumar                       bool GapRegion = false)
92747b0e29SVedant Kumar       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
93a1c4deb7SVedant Kumar         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
94ee02499aSAlex Lorenz 
9509c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
9609c7179bSJustin Bogner 
97bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
9809c7179bSJustin Bogner 
99bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
100bf42cfd7SJustin Bogner 
101bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
102bf42cfd7SJustin Bogner 
1033cffc4c7SStephen Kelly   SourceLocation getBeginLoc() const {
104bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
105bf42cfd7SJustin Bogner     return *LocStart;
10609c7179bSJustin Bogner   }
10709c7179bSJustin Bogner 
108bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
109ee02499aSAlex Lorenz 
110a14a1f92SVedant Kumar   void setEndLoc(SourceLocation Loc) {
111a14a1f92SVedant Kumar     assert(Loc.isValid() && "Setting an invalid end location");
112a14a1f92SVedant Kumar     LocEnd = Loc;
113a14a1f92SVedant Kumar   }
114ee02499aSAlex Lorenz 
115462c77b4SCraig Topper   SourceLocation getEndLoc() const {
116bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
117bf42cfd7SJustin Bogner     return *LocEnd;
118ee02499aSAlex Lorenz   }
119747b0e29SVedant Kumar 
120747b0e29SVedant Kumar   bool isDeferred() const { return DeferRegion; }
121747b0e29SVedant Kumar 
122747b0e29SVedant Kumar   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
123a1c4deb7SVedant Kumar 
124a1c4deb7SVedant Kumar   bool isGap() const { return GapRegion; }
125a1c4deb7SVedant Kumar 
126a1c4deb7SVedant Kumar   void setGap(bool Gap) { GapRegion = Gap; }
127ee02499aSAlex Lorenz };
128ee02499aSAlex Lorenz 
129d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
130d7369648SVedant Kumar struct SpellingRegion {
131d7369648SVedant Kumar   /// The line where the region starts.
132d7369648SVedant Kumar   unsigned LineStart;
133d7369648SVedant Kumar 
134d7369648SVedant Kumar   /// The column where the region starts.
135d7369648SVedant Kumar   unsigned ColumnStart;
136d7369648SVedant Kumar 
137d7369648SVedant Kumar   /// The line where the region ends.
138d7369648SVedant Kumar   unsigned LineEnd;
139d7369648SVedant Kumar 
140d7369648SVedant Kumar   /// The column where the region ends.
141d7369648SVedant Kumar   unsigned ColumnEnd;
142d7369648SVedant Kumar 
143d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
144d7369648SVedant Kumar                  SourceLocation LocEnd) {
145d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
146d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
147d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
148d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
149d7369648SVedant Kumar   }
150d7369648SVedant Kumar 
151fa8fa044SVedant Kumar   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
152a6e4358fSStephen Kelly       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
153fa8fa044SVedant Kumar 
154d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
155d7369648SVedant Kumar   /// top->bottom, left->right.
156d7369648SVedant Kumar   bool isInSourceOrder() const {
157d7369648SVedant Kumar     return (LineStart < LineEnd) ||
158d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
159d7369648SVedant Kumar   }
160d7369648SVedant Kumar };
161d7369648SVedant Kumar 
1629fc8faf9SAdrian Prantl /// Provides the common functionality for the different
163ee02499aSAlex Lorenz /// coverage mapping region builders.
164ee02499aSAlex Lorenz class CoverageMappingBuilder {
165ee02499aSAlex Lorenz public:
166ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
167ee02499aSAlex Lorenz   SourceManager &SM;
168ee02499aSAlex Lorenz   const LangOptions &LangOpts;
169ee02499aSAlex Lorenz 
170ee02499aSAlex Lorenz private:
1719fc8faf9SAdrian Prantl   /// Map of clang's FileIDs to IDs used for coverage mapping.
172bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
173bf42cfd7SJustin Bogner       FileIDMapping;
174ee02499aSAlex Lorenz 
175ee02499aSAlex Lorenz public:
1769fc8faf9SAdrian Prantl   /// The coverage mapping regions for this function
177ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
1789fc8faf9SAdrian Prantl   /// The source mapping regions for this function.
179f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
180ee02499aSAlex Lorenz 
1819fc8faf9SAdrian Prantl   /// A set of regions which can be used as a filter.
182fc05ee34SIgor Kudrin   ///
183fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
184fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
185fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
186fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
187fc05ee34SIgor Kudrin       SourceRegionFilter;
188fc05ee34SIgor Kudrin 
189ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
190ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
191bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
192ee02499aSAlex Lorenz 
1939fc8faf9SAdrian Prantl   /// Return the precise end location for the given token.
194ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
195bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
196bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
197bf42cfd7SJustin Bogner     unsigned TokLen =
198bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
199bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
200ee02499aSAlex Lorenz   }
201ee02499aSAlex Lorenz 
2029fc8faf9SAdrian Prantl   /// Return the start location of an included file or expanded macro.
203bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
204bf42cfd7SJustin Bogner     if (Loc.isMacroID())
205bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
206bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
207ee02499aSAlex Lorenz   }
208ee02499aSAlex Lorenz 
2099fc8faf9SAdrian Prantl   /// Return the end location of an included file or expanded macro.
210bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
211bf42cfd7SJustin Bogner     if (Loc.isMacroID())
212bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
213f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
214bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
215bf42cfd7SJustin Bogner   }
216ee02499aSAlex Lorenz 
2179fc8faf9SAdrian Prantl   /// Find out where the current file is included or macro is expanded.
218bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
219b5f8171aSRichard Smith     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
220bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
221bf42cfd7SJustin Bogner   }
222bf42cfd7SJustin Bogner 
2239fc8faf9SAdrian Prantl   /// Return true if \c Loc is a location in a built-in macro.
224682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
22599d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
226682bfbf3SJustin Bogner   }
227682bfbf3SJustin Bogner 
2289fc8faf9SAdrian Prantl   /// Check whether \c Loc is included or expanded from \c Parent.
229d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
230d9e1a61dSIgor Kudrin     do {
231d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
232d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
233d9e1a61dSIgor Kudrin         return false;
234d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
235d9e1a61dSIgor Kudrin     return true;
236d9e1a61dSIgor Kudrin   }
237d9e1a61dSIgor Kudrin 
2389fc8faf9SAdrian Prantl   /// Get the start of \c S ignoring macro arguments and builtin macros.
239bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
240f2ceec48SStephen Kelly     SourceLocation Loc = S->getBeginLoc();
241682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
242b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
243bf42cfd7SJustin Bogner     return Loc;
244bf42cfd7SJustin Bogner   }
245bf42cfd7SJustin Bogner 
2469fc8faf9SAdrian Prantl   /// Get the end of \c S ignoring macro arguments and builtin macros.
247bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
2481c301dcbSStephen Kelly     SourceLocation Loc = S->getEndLoc();
249682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
250b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
251f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
252bf42cfd7SJustin Bogner   }
253bf42cfd7SJustin Bogner 
2549fc8faf9SAdrian Prantl   /// Find the set of files we have regions for and assign IDs
255bf42cfd7SJustin Bogner   ///
256bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
257bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
258bf42cfd7SJustin Bogner   /// expansion regions.
259bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
260bf42cfd7SJustin Bogner     FileIDMapping.clear();
261bf42cfd7SJustin Bogner 
262bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
263bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
264bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
265a6e4358fSStephen Kelly       SourceLocation Loc = Region.getBeginLoc();
266bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
267bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
268bf42cfd7SJustin Bogner         continue;
269bf42cfd7SJustin Bogner 
27093205af0SVedant Kumar       // Do not map FileID's associated with system headers.
27193205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
27293205af0SVedant Kumar         continue;
27393205af0SVedant Kumar 
274bf42cfd7SJustin Bogner       unsigned Depth = 0;
275bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
276ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
277bf42cfd7SJustin Bogner         ++Depth;
278bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
279bf42cfd7SJustin Bogner     }
280899d1392SFangrui Song     llvm::stable_sort(FileLocs, llvm::less_second());
281bf42cfd7SJustin Bogner 
282bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
283bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
284bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
285ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
286ee02499aSAlex Lorenz       if (!Entry)
287bf42cfd7SJustin Bogner         continue;
288ee02499aSAlex Lorenz 
289bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
290bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
291bf42cfd7SJustin Bogner     }
292ee02499aSAlex Lorenz   }
293ee02499aSAlex Lorenz 
2949fc8faf9SAdrian Prantl   /// Get the coverage mapping file ID for \c Loc.
295bf42cfd7SJustin Bogner   ///
296bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
297bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
298bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
299bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
300bf42cfd7SJustin Bogner       return Mapping->second.first;
301903678caSJustin Bogner     return None;
302ee02499aSAlex Lorenz   }
303ee02499aSAlex Lorenz 
304*b46176bbSZequan Wu   /// This shrinks the skipped range if it spans a line that contains a
305*b46176bbSZequan Wu   /// non-comment token. If shrinking the skipped range would make it empty,
306*b46176bbSZequan Wu   /// this returns None.
307*b46176bbSZequan Wu   Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
308*b46176bbSZequan Wu                                               SpellingRegion SR,
309*b46176bbSZequan Wu                                               SourceLocation PrevTokLoc,
310*b46176bbSZequan Wu                                               SourceLocation NextTokLoc) {
311*b46176bbSZequan Wu     // If Range begin location is invalid, it's not a comment region.
312*b46176bbSZequan Wu     if (PrevTokLoc.isInvalid())
313*b46176bbSZequan Wu       return SR;
314*b46176bbSZequan Wu     unsigned PrevTokLine = SM.getSpellingLineNumber(PrevTokLoc);
315*b46176bbSZequan Wu     unsigned NextTokLine = SM.getSpellingLineNumber(NextTokLoc);
316*b46176bbSZequan Wu     SpellingRegion newSR(SR);
317*b46176bbSZequan Wu     if (SR.LineStart == PrevTokLine) {
318*b46176bbSZequan Wu       newSR.LineStart = SR.LineStart + 1;
319*b46176bbSZequan Wu       newSR.ColumnStart = 1;
320*b46176bbSZequan Wu     }
321*b46176bbSZequan Wu     if (SR.LineEnd == NextTokLine) {
322*b46176bbSZequan Wu       newSR.LineEnd = SR.LineEnd - 1;
323*b46176bbSZequan Wu       newSR.ColumnEnd = SR.ColumnStart + 1;
324*b46176bbSZequan Wu     }
325*b46176bbSZequan Wu     if (newSR.isInSourceOrder())
326*b46176bbSZequan Wu       return newSR;
327*b46176bbSZequan Wu     return None;
328*b46176bbSZequan Wu   }
329*b46176bbSZequan Wu 
3309fc8faf9SAdrian Prantl   /// Gather all the regions that were skipped by the preprocessor
331*b46176bbSZequan Wu   /// using the constructs like #if or comments.
332ee02499aSAlex Lorenz   void gatherSkippedRegions() {
333ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
334ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
335ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
336ee02499aSAlex Lorenz     FileLineRanges.resize(
337ee02499aSAlex Lorenz         FileIDMapping.size(),
338ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
339ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
340ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
341ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
342ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
343ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
344ee02499aSAlex Lorenz     }
345ee02499aSAlex Lorenz 
346ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
347*b46176bbSZequan Wu     for (auto &I : SkippedRanges) {
348*b46176bbSZequan Wu       SourceRange Range = I.Range;
349*b46176bbSZequan Wu       auto LocStart = Range.getBegin();
350*b46176bbSZequan Wu       auto LocEnd = Range.getEnd();
351bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
352bf42cfd7SJustin Bogner              "region spans multiple files");
353ee02499aSAlex Lorenz 
354bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
355903678caSJustin Bogner       if (!CovFileID)
356ee02499aSAlex Lorenz         continue;
357d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
358*b46176bbSZequan Wu       if (Optional<SpellingRegion> res =
359*b46176bbSZequan Wu               adjustSkippedRange(SM, SR, I.PrevTokLoc, I.NextTokLoc))
360*b46176bbSZequan Wu         SR = res.getValue();
361*b46176bbSZequan Wu       else
362*b46176bbSZequan Wu         continue;
363fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
364d7369648SVedant Kumar           *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
365ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
3662a8c18d9SAlexander Kornienko       // the source code of this function.
367903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
368903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
369ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
370ee02499aSAlex Lorenz     }
371ee02499aSAlex Lorenz   }
372ee02499aSAlex Lorenz 
3739fc8faf9SAdrian Prantl   /// Generate the coverage counter mapping regions from collected
374ee02499aSAlex Lorenz   /// source regions.
375fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
376bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
377bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
378ee02499aSAlex Lorenz 
379a6e4358fSStephen Kelly       SourceLocation LocStart = Region.getBeginLoc();
3808b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
381f59329b0SJustin Bogner 
38293205af0SVedant Kumar       // Ignore regions from system headers.
38393205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
38493205af0SVedant Kumar         continue;
38593205af0SVedant Kumar 
386bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
387bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
388bf42cfd7SJustin Bogner       if (!CovFileID)
389ee02499aSAlex Lorenz         continue;
390ee02499aSAlex Lorenz 
391f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
392bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
393bf42cfd7SJustin Bogner              "region spans multiple files");
394bf42cfd7SJustin Bogner 
395fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
396fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
397fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
398fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
399fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
400fc05ee34SIgor Kudrin         continue;
401fc05ee34SIgor Kudrin 
402d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
403d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
404d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
405a1c4deb7SVedant Kumar 
406a1c4deb7SVedant Kumar       if (Region.isGap()) {
407a1c4deb7SVedant Kumar         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
408a1c4deb7SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
409a1c4deb7SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
410a1c4deb7SVedant Kumar       } else {
411bf42cfd7SJustin Bogner         MappingRegions.push_back(CounterMappingRegion::makeRegion(
412d7369648SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
413d7369648SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
414bf42cfd7SJustin Bogner       }
415bf42cfd7SJustin Bogner     }
416a1c4deb7SVedant Kumar   }
417bf42cfd7SJustin Bogner 
4189fc8faf9SAdrian Prantl   /// Generate expansion regions for each virtual file we've seen.
419fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
420fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
421bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
422bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
423bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
424bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
425ee02499aSAlex Lorenz         continue;
426ee02499aSAlex Lorenz 
427bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
428bf42cfd7SJustin Bogner       if (!ParentFileID)
429bf42cfd7SJustin Bogner         continue;
430bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
431bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
432bf42cfd7SJustin Bogner 
433bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
434bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
435bf42cfd7SJustin Bogner              "region spans multiple files");
436fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
437bf42cfd7SJustin Bogner 
438d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
439d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
440bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
441d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
442d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
443ee02499aSAlex Lorenz     }
444fc05ee34SIgor Kudrin     return Filter;
445ee02499aSAlex Lorenz   }
446ee02499aSAlex Lorenz };
447ee02499aSAlex Lorenz 
4489fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that
449ee02499aSAlex Lorenz /// are not emitted.
450ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
451ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
452ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
453ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
454ee02499aSAlex Lorenz 
455ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
456ee02499aSAlex Lorenz     if (!D->hasBody())
457ee02499aSAlex Lorenz       return;
458ee02499aSAlex Lorenz     auto Body = D->getBody();
459d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
460d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
461d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
462d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
463d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
464d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
465d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
466d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
467d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
468d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
469d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
470d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
471d9e1a61dSIgor Kudrin       }
472d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
473d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
474d9e1a61dSIgor Kudrin         assert(End.isValid() &&
475d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
476d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
477d9e1a61dSIgor Kudrin       }
478d9e1a61dSIgor Kudrin     }
479d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
480ee02499aSAlex Lorenz   }
481ee02499aSAlex Lorenz 
4829fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
483ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
484ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
485bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
486fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
487ee02499aSAlex Lorenz 
488efd319a2SVedant Kumar     if (MappingRegions.empty())
489efd319a2SVedant Kumar       return;
490efd319a2SVedant Kumar 
4915fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
492ee02499aSAlex Lorenz     Writer.write(OS);
493ee02499aSAlex Lorenz   }
494ee02499aSAlex Lorenz };
495ee02499aSAlex Lorenz 
4969fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map
497ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
498ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
499ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
500ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
5019fc8faf9SAdrian Prantl   /// The map of statements to count values.
502ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
503ee02499aSAlex Lorenz 
5049fc8faf9SAdrian Prantl   /// A stack of currently live regions.
505bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
506ee02499aSAlex Lorenz 
507747b0e29SVedant Kumar   /// The currently deferred region: its end location and count can be set once
508747b0e29SVedant Kumar   /// its parent has been popped from the region stack.
509747b0e29SVedant Kumar   Optional<SourceMappingRegion> DeferredRegion;
510747b0e29SVedant Kumar 
511ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
512ee02499aSAlex Lorenz 
5139fc8faf9SAdrian Prantl   /// A location in the most recently visited file or macro.
514bf42cfd7SJustin Bogner   ///
515bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
516bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
517bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
518bf42cfd7SJustin Bogner 
5198046d22aSVedant Kumar   /// Location of the last terminated region.
5208046d22aSVedant Kumar   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
5218046d22aSVedant Kumar 
5229fc8faf9SAdrian Prantl   /// Return a counter for the subtraction of \c RHS from \c LHS
523ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
524ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
525ee02499aSAlex Lorenz   }
526ee02499aSAlex Lorenz 
5279fc8faf9SAdrian Prantl   /// Return a counter for the sum of \c LHS and \c RHS.
528ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
529ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
530ee02499aSAlex Lorenz   }
531ee02499aSAlex Lorenz 
532bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
533bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
534bf42cfd7SJustin Bogner   }
535bf42cfd7SJustin Bogner 
5369fc8faf9SAdrian Prantl   /// Return the region counter for the given statement.
537bf42cfd7SJustin Bogner   ///
538ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
539bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
540bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
541ee02499aSAlex Lorenz   }
542ee02499aSAlex Lorenz 
5439fc8faf9SAdrian Prantl   /// Push a region onto the stack.
544bf42cfd7SJustin Bogner   ///
545bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
546bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
547bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
548bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
549747b0e29SVedant Kumar     if (StartLoc) {
550bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
551747b0e29SVedant Kumar       completeDeferred(Count, MostRecentLocation);
552747b0e29SVedant Kumar     }
553bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
554ee02499aSAlex Lorenz 
555bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
556ee02499aSAlex Lorenz   }
557ee02499aSAlex Lorenz 
558747b0e29SVedant Kumar   /// Complete any pending deferred region by setting its end location and
559747b0e29SVedant Kumar   /// count, and then pushing it onto the region stack.
560747b0e29SVedant Kumar   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
561747b0e29SVedant Kumar     size_t Index = RegionStack.size();
562747b0e29SVedant Kumar     if (!DeferredRegion)
563747b0e29SVedant Kumar       return Index;
564747b0e29SVedant Kumar 
565747b0e29SVedant Kumar     // Consume the pending region.
566747b0e29SVedant Kumar     SourceMappingRegion DR = DeferredRegion.getValue();
567747b0e29SVedant Kumar     DeferredRegion = None;
568747b0e29SVedant Kumar 
569747b0e29SVedant Kumar     // If the region ends in an expansion, find the expansion site.
570a6e4358fSStephen Kelly     FileID StartFile = SM.getFileID(DR.getBeginLoc());
571f9a0d44eSVedant Kumar     if (SM.getFileID(DeferredEndLoc) != StartFile) {
572747b0e29SVedant Kumar       if (isNestedIn(DeferredEndLoc, StartFile)) {
573747b0e29SVedant Kumar         do {
574747b0e29SVedant Kumar           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
575747b0e29SVedant Kumar         } while (StartFile != SM.getFileID(DeferredEndLoc));
576f9a0d44eSVedant Kumar       } else {
577f9a0d44eSVedant Kumar         return Index;
578747b0e29SVedant Kumar       }
579747b0e29SVedant Kumar     }
580747b0e29SVedant Kumar 
581747b0e29SVedant Kumar     // The parent of this deferred region ends where the containing decl ends,
582747b0e29SVedant Kumar     // so the region isn't useful.
583a6e4358fSStephen Kelly     if (DR.getBeginLoc() == DeferredEndLoc)
584747b0e29SVedant Kumar       return Index;
585747b0e29SVedant Kumar 
586747b0e29SVedant Kumar     // If we're visiting statements in non-source order (e.g switch cases or
587747b0e29SVedant Kumar     // a loop condition) we can't construct a sensible deferred region.
588a6e4358fSStephen Kelly     if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
589747b0e29SVedant Kumar       return Index;
590747b0e29SVedant Kumar 
591a1c4deb7SVedant Kumar     DR.setGap(true);
592747b0e29SVedant Kumar     DR.setCounter(Count);
593747b0e29SVedant Kumar     DR.setEndLoc(DeferredEndLoc);
594747b0e29SVedant Kumar     handleFileExit(DeferredEndLoc);
595747b0e29SVedant Kumar     RegionStack.push_back(DR);
596747b0e29SVedant Kumar     return Index;
597747b0e29SVedant Kumar   }
598747b0e29SVedant Kumar 
5998046d22aSVedant Kumar   /// Complete a deferred region created after a terminated region at the
6008046d22aSVedant Kumar   /// top-level.
6018046d22aSVedant Kumar   void completeTopLevelDeferredRegion(Counter Count,
6028046d22aSVedant Kumar                                       SourceLocation DeferredEndLoc) {
6038046d22aSVedant Kumar     if (DeferredRegion || !LastTerminatedRegion)
6048046d22aSVedant Kumar       return;
6058046d22aSVedant Kumar 
6068046d22aSVedant Kumar     if (LastTerminatedRegion->second != RegionStack.size())
6078046d22aSVedant Kumar       return;
6088046d22aSVedant Kumar 
6098046d22aSVedant Kumar     SourceLocation Start = LastTerminatedRegion->first;
6108046d22aSVedant Kumar     if (SM.getFileID(Start) != SM.getMainFileID())
6118046d22aSVedant Kumar       return;
6128046d22aSVedant Kumar 
6138046d22aSVedant Kumar     SourceMappingRegion DR = RegionStack.back();
6148046d22aSVedant Kumar     DR.setStartLoc(Start);
6158046d22aSVedant Kumar     DR.setDeferred(false);
6168046d22aSVedant Kumar     DeferredRegion = DR;
6178046d22aSVedant Kumar     completeDeferred(Count, DeferredEndLoc);
6188046d22aSVedant Kumar   }
6198046d22aSVedant Kumar 
6200c3e3115SVedant Kumar   size_t locationDepth(SourceLocation Loc) {
6210c3e3115SVedant Kumar     size_t Depth = 0;
6220c3e3115SVedant Kumar     while (Loc.isValid()) {
6230c3e3115SVedant Kumar       Loc = getIncludeOrExpansionLoc(Loc);
6240c3e3115SVedant Kumar       Depth++;
6250c3e3115SVedant Kumar     }
6260c3e3115SVedant Kumar     return Depth;
6270c3e3115SVedant Kumar   }
6280c3e3115SVedant Kumar 
6299fc8faf9SAdrian Prantl   /// Pop regions from the stack into the function's list of regions.
630bf42cfd7SJustin Bogner   ///
631bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
632bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
633bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
634bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
635747b0e29SVedant Kumar     bool ParentOfDeferredRegion = false;
636bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
637bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
638bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
639a6e4358fSStephen Kelly         SourceLocation StartLoc = Region.getBeginLoc();
640bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
641bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
642bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
6430c3e3115SVedant Kumar         size_t StartDepth = locationDepth(StartLoc);
6440c3e3115SVedant Kumar         size_t EndDepth = locationDepth(EndLoc);
645bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
6460c3e3115SVedant Kumar           bool UnnestStart = StartDepth >= EndDepth;
6470c3e3115SVedant Kumar           bool UnnestEnd = EndDepth >= StartDepth;
6480c3e3115SVedant Kumar           if (UnnestEnd) {
649bf42cfd7SJustin Bogner             // The region ends in a nested file or macro expansion. Create a
650bf42cfd7SJustin Bogner             // separate region for each expansion.
651bf42cfd7SJustin Bogner             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
652bf42cfd7SJustin Bogner             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
653bf42cfd7SJustin Bogner 
6548545dae2SIgor Kudrin             if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
655bf42cfd7SJustin Bogner               SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
656bf42cfd7SJustin Bogner 
657f14b2078SJustin Bogner             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
658dceaaadfSJustin Bogner             if (EndLoc.isInvalid())
659dceaaadfSJustin Bogner               llvm::report_fatal_error("File exit not handled before popRegions");
6600c3e3115SVedant Kumar             EndDepth--;
661bf42cfd7SJustin Bogner           }
6620c3e3115SVedant Kumar           if (UnnestStart) {
6630c3e3115SVedant Kumar             // The region begins in a nested file or macro expansion. Create a
6640c3e3115SVedant Kumar             // separate region for each expansion.
6650c3e3115SVedant Kumar             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
6660c3e3115SVedant Kumar             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
6670c3e3115SVedant Kumar 
6680c3e3115SVedant Kumar             if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
6690c3e3115SVedant Kumar               SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
6700c3e3115SVedant Kumar 
6710c3e3115SVedant Kumar             StartLoc = getIncludeOrExpansionLoc(StartLoc);
6720c3e3115SVedant Kumar             if (StartLoc.isInvalid())
6730c3e3115SVedant Kumar               llvm::report_fatal_error("File exit not handled before popRegions");
6740c3e3115SVedant Kumar             StartDepth--;
6750c3e3115SVedant Kumar           }
6760c3e3115SVedant Kumar         }
6770c3e3115SVedant Kumar         Region.setStartLoc(StartLoc);
678bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
679bf42cfd7SJustin Bogner 
680bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
681bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
682bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
683bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
684bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
685bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
686bf42cfd7SJustin Bogner 
687a6e4358fSStephen Kelly         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
688fa8fa044SVedant Kumar         assert(SpellingRegion(SM, Region).isInSourceOrder());
689f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
690747b0e29SVedant Kumar 
691747b0e29SVedant Kumar         if (ParentOfDeferredRegion) {
692747b0e29SVedant Kumar           ParentOfDeferredRegion = false;
693747b0e29SVedant Kumar 
694747b0e29SVedant Kumar           // If there's an existing deferred region, keep the old one, because
695747b0e29SVedant Kumar           // it means there are two consecutive returns (or a similar pattern).
696747b0e29SVedant Kumar           if (!DeferredRegion.hasValue() &&
697747b0e29SVedant Kumar               // File IDs aren't gathered within macro expansions, so it isn't
698747b0e29SVedant Kumar               // useful to try and create a deferred region inside of one.
699f9a0d44eSVedant Kumar               !EndLoc.isMacroID())
700747b0e29SVedant Kumar             DeferredRegion =
701747b0e29SVedant Kumar                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
702747b0e29SVedant Kumar         }
703747b0e29SVedant Kumar       } else if (Region.isDeferred()) {
704747b0e29SVedant Kumar         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
705747b0e29SVedant Kumar         ParentOfDeferredRegion = true;
706bf42cfd7SJustin Bogner       }
707bf42cfd7SJustin Bogner       RegionStack.pop_back();
7088046d22aSVedant Kumar 
7098046d22aSVedant Kumar       // If the zero region pushed after the last terminated region no longer
7108046d22aSVedant Kumar       // exists, clear its cached information.
7118046d22aSVedant Kumar       if (LastTerminatedRegion &&
7128046d22aSVedant Kumar           RegionStack.size() < LastTerminatedRegion->second)
7138046d22aSVedant Kumar         LastTerminatedRegion = None;
714bf42cfd7SJustin Bogner     }
715747b0e29SVedant Kumar     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
716ee02499aSAlex Lorenz   }
717ee02499aSAlex Lorenz 
7189fc8faf9SAdrian Prantl   /// Return the currently active region.
719bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
720bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
721bf42cfd7SJustin Bogner     return RegionStack.back();
722ee02499aSAlex Lorenz   }
723ee02499aSAlex Lorenz 
7247225a261SVedant Kumar   /// Propagate counts through the children of \p S if \p VisitChildren is true.
7257225a261SVedant Kumar   /// Otherwise, only emit a count for \p S itself.
7267225a261SVedant Kumar   Counter propagateCounts(Counter TopCount, const Stmt *S,
7277225a261SVedant Kumar                           bool VisitChildren = true) {
7287838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
7297838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
7307838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
7317225a261SVedant Kumar     if (VisitChildren)
732bf42cfd7SJustin Bogner       Visit(S);
733bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
734bf42cfd7SJustin Bogner     popRegions(Index);
73539f01975SVedant Kumar 
73639f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
73739f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
738f2ceec48SStephen Kelly     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
7397838696eSVedant Kumar       MostRecentLocation = EndLoc;
74039f01975SVedant Kumar 
741bf42cfd7SJustin Bogner     return ExitCount;
742ee02499aSAlex Lorenz   }
743ee02499aSAlex Lorenz 
7449fc8faf9SAdrian Prantl   /// Check whether a region with bounds \c StartLoc and \c EndLoc
7450a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
7460a7c9d11SIgor Kudrin   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
7470a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
7480a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
7490a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
750a6e4358fSStephen Kelly                           return Region.getBeginLoc() == StartLoc &&
7510a7c9d11SIgor Kudrin                                  Region.getEndLoc() == EndLoc;
7520a7c9d11SIgor Kudrin                         });
7530a7c9d11SIgor Kudrin   }
7540a7c9d11SIgor Kudrin 
7559fc8faf9SAdrian Prantl   /// Adjust the most recently visited location to \c EndLoc.
756bf42cfd7SJustin Bogner   ///
757bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
758bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
759bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
7600a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
7610a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
7620a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
7630a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
7640a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
76596ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
7660a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
7670a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
7680a7c9d11SIgor Kudrin                              MostRecentLocation))
769bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
770ee02499aSAlex Lorenz   }
771ee02499aSAlex Lorenz 
7729fc8faf9SAdrian Prantl   /// Adjust regions and state when \c NewLoc exits a file.
773bf42cfd7SJustin Bogner   ///
774bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
775bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
776bf42cfd7SJustin Bogner   /// for the exited file.
777bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
778e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
779e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
780bf42cfd7SJustin Bogner       return;
781bf42cfd7SJustin Bogner 
782bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
783bf42cfd7SJustin Bogner     // find the common ancestor.
784bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
785bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
786bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
787bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
788bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
789bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
790bf42cfd7SJustin Bogner         // to adjust our location to the new file.
791bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
792bf42cfd7SJustin Bogner         return;
793bf42cfd7SJustin Bogner       }
794bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
795ee02499aSAlex Lorenz     }
796ee02499aSAlex Lorenz 
797bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
798bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
79957d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
80057d3f145SPete Cooper       if (!I.hasStartLoc())
801bf42cfd7SJustin Bogner         continue;
802a6e4358fSStephen Kelly       SourceLocation Loc = I.getBeginLoc();
803bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
80457d3f145SPete Cooper         ParentCounter = I.getCounter();
805bf42cfd7SJustin Bogner         break;
806ee02499aSAlex Lorenz       }
807bf42cfd7SJustin Bogner 
808bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
809bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
810bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
811bf42cfd7SJustin Bogner         // we've seen this region.
812bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
81357d3f145SPete Cooper           SourceRegions.emplace_back(I.getCounter(), Loc,
814bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
815bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
816ee02499aSAlex Lorenz       }
81757d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
818bf42cfd7SJustin Bogner     }
819bf42cfd7SJustin Bogner 
820bf42cfd7SJustin Bogner     if (ParentCounter) {
821bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
822bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
823bf42cfd7SJustin Bogner       // corresponding to the parent.
824bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
825bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
826bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
827fa8fa044SVedant Kumar         if (StartLocs.insert(FileStart).second) {
828bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
829bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
830fa8fa044SVedant Kumar           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
831fa8fa044SVedant Kumar         }
832bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
833bf42cfd7SJustin Bogner       }
834bf42cfd7SJustin Bogner     }
835bf42cfd7SJustin Bogner 
836bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
837bf42cfd7SJustin Bogner   }
838bf42cfd7SJustin Bogner 
8399fc8faf9SAdrian Prantl   /// Ensure that \c S is included in the current region.
840bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
841bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
842bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
843bf42cfd7SJustin Bogner 
844bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
845bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
846bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
847747b0e29SVedant Kumar 
848747b0e29SVedant Kumar     completeDeferred(Region.getCounter(), StartLoc);
849bf42cfd7SJustin Bogner   }
850bf42cfd7SJustin Bogner 
8519fc8faf9SAdrian Prantl   /// Mark \c S as a terminator, starting a zero region.
852bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
853bf42cfd7SJustin Bogner     extendRegion(S);
854bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
8558046d22aSVedant Kumar     SourceLocation EndLoc = getEnd(S);
856bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
8578046d22aSVedant Kumar       Region.setEndLoc(EndLoc);
858bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
8598046d22aSVedant Kumar     auto &ZeroRegion = getRegion();
8608046d22aSVedant Kumar     ZeroRegion.setDeferred(true);
8618046d22aSVedant Kumar     LastTerminatedRegion = {EndLoc, RegionStack.size()};
862bf42cfd7SJustin Bogner   }
863ee02499aSAlex Lorenz 
864fa8fa044SVedant Kumar   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
865fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
866fa8fa044SVedant Kumar                                            SourceLocation BeforeLoc) {
867fa8fa044SVedant Kumar     // If the start and end locations of the gap are both within the same macro
868fa8fa044SVedant Kumar     // file, the range may not be in source order.
869fa8fa044SVedant Kumar     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
870fa8fa044SVedant Kumar       return None;
871fa8fa044SVedant Kumar     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
872fa8fa044SVedant Kumar       return None;
873fa8fa044SVedant Kumar     return {{AfterLoc, BeforeLoc}};
874fa8fa044SVedant Kumar   }
875fa8fa044SVedant Kumar 
876fa8fa044SVedant Kumar   /// Find the source range after \p AfterStmt and before \p BeforeStmt.
877fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
878fa8fa044SVedant Kumar                                            const Stmt *BeforeStmt) {
879fa8fa044SVedant Kumar     return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
880fa8fa044SVedant Kumar                               getStart(BeforeStmt));
881fa8fa044SVedant Kumar   }
882fa8fa044SVedant Kumar 
8832e8c8759SVedant Kumar   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
8842e8c8759SVedant Kumar   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
8852e8c8759SVedant Kumar                             Counter Count) {
886fa8fa044SVedant Kumar     if (StartLoc == EndLoc)
8872e8c8759SVedant Kumar       return;
888fa8fa044SVedant Kumar     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
8892e8c8759SVedant Kumar     handleFileExit(StartLoc);
8902e8c8759SVedant Kumar     size_t Index = pushRegion(Count, StartLoc, EndLoc);
8912e8c8759SVedant Kumar     getRegion().setGap(true);
8922e8c8759SVedant Kumar     handleFileExit(EndLoc);
8932e8c8759SVedant Kumar     popRegions(Index);
8942e8c8759SVedant Kumar   }
8952e8c8759SVedant Kumar 
8969fc8faf9SAdrian Prantl   /// Keep counts of breaks and continues inside loops.
897ee02499aSAlex Lorenz   struct BreakContinue {
898ee02499aSAlex Lorenz     Counter BreakCount;
899ee02499aSAlex Lorenz     Counter ContinueCount;
900ee02499aSAlex Lorenz   };
901ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
902ee02499aSAlex Lorenz 
903ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
904ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
905e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
906ee02499aSAlex Lorenz       const LangOptions &LangOpts)
907747b0e29SVedant Kumar       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
908747b0e29SVedant Kumar         DeferredRegion(None) {}
909ee02499aSAlex Lorenz 
9109fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
911ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
912ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
913bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
914fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
915747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
916fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
917ee02499aSAlex Lorenz     gatherSkippedRegions();
918ee02499aSAlex Lorenz 
919efd319a2SVedant Kumar     if (MappingRegions.empty())
920efd319a2SVedant Kumar       return;
921efd319a2SVedant Kumar 
9224da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
9234da909b2SJustin Bogner                                  MappingRegions);
924ee02499aSAlex Lorenz     Writer.write(OS);
925ee02499aSAlex Lorenz   }
926ee02499aSAlex Lorenz 
927ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
928f2ceec48SStephen Kelly     if (S->getBeginLoc().isValid())
929bf42cfd7SJustin Bogner       extendRegion(S);
930642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
931642f173aSBenjamin Kramer       if (Child)
932642f173aSBenjamin Kramer         this->Visit(Child);
933bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
934ee02499aSAlex Lorenz   }
935ee02499aSAlex Lorenz 
936ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
937747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
938747b0e29SVedant Kumar 
939bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
940efd319a2SVedant Kumar 
941efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
942efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
943efd319a2SVedant Kumar       return;
944efd319a2SVedant Kumar 
9457225a261SVedant Kumar     // Do not visit the artificial children nodes of defaulted methods. The
9467225a261SVedant Kumar     // lexer may not be able to report back precise token end locations for
9477225a261SVedant Kumar     // these children nodes (llvm.org/PR39822), and moreover users will not be
9487225a261SVedant Kumar     // able to see coverage for them.
9497225a261SVedant Kumar     bool Defaulted = false;
9507225a261SVedant Kumar     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
9517225a261SVedant Kumar       Defaulted = Method->isDefaulted();
9527225a261SVedant Kumar 
9537225a261SVedant Kumar     propagateCounts(getRegionCounter(Body), Body,
9547225a261SVedant Kumar                     /*VisitChildren=*/!Defaulted);
955747b0e29SVedant Kumar     assert(RegionStack.empty() && "Regions entered but never exited");
956747b0e29SVedant Kumar 
95761763b65SVedant Kumar     // Discard the last uncompleted deferred region in a decl, if one exists.
95861763b65SVedant Kumar     // This prevents lines at the end of a function containing only whitespace
95961763b65SVedant Kumar     // or closing braces from being marked as uncovered.
960ef8e05ffSVedant Kumar     DeferredRegion = None;
961341bf429SVedant Kumar   }
962ee02499aSAlex Lorenz 
963ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
964bf42cfd7SJustin Bogner     extendRegion(S);
965ee02499aSAlex Lorenz     if (S->getRetValue())
966ee02499aSAlex Lorenz       Visit(S->getRetValue());
967bf42cfd7SJustin Bogner     terminateRegion(S);
968ee02499aSAlex Lorenz   }
969ee02499aSAlex Lorenz 
970565e37c7SXun Li   void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
971565e37c7SXun Li     extendRegion(S);
972565e37c7SXun Li     Visit(S->getBody());
973565e37c7SXun Li   }
974565e37c7SXun Li 
975565e37c7SXun Li   void VisitCoreturnStmt(const CoreturnStmt *S) {
976565e37c7SXun Li     extendRegion(S);
977565e37c7SXun Li     if (S->getOperand())
978565e37c7SXun Li       Visit(S->getOperand());
979565e37c7SXun Li     terminateRegion(S);
980565e37c7SXun Li   }
981565e37c7SXun Li 
982f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
983f959febfSJustin Bogner     extendRegion(E);
984f959febfSJustin Bogner     if (E->getSubExpr())
985f959febfSJustin Bogner       Visit(E->getSubExpr());
986f959febfSJustin Bogner     terminateRegion(E);
987f959febfSJustin Bogner   }
988f959febfSJustin Bogner 
989bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
990ee02499aSAlex Lorenz 
991ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
9928046d22aSVedant Kumar     Counter LabelCount = getRegionCounter(S);
993bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
9948046d22aSVedant Kumar     completeTopLevelDeferredRegion(LabelCount, Start);
995d781d97eSVedant Kumar     completeDeferred(LabelCount, Start);
996bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
997bf42cfd7SJustin Bogner     handleFileExit(Start);
9988046d22aSVedant Kumar     pushRegion(LabelCount, Start);
999ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1000ee02499aSAlex Lorenz   }
1001ee02499aSAlex Lorenz 
1002ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
1003ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1004ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
1005bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
10067f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
10077f53fbfcSEli Friedman     // case statements, not just the most recent one.
1008bf42cfd7SJustin Bogner     terminateRegion(S);
1009ee02499aSAlex Lorenz   }
1010ee02499aSAlex Lorenz 
1011ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
1012ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1013ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
1014bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1015bf42cfd7SJustin Bogner     terminateRegion(S);
1016ee02499aSAlex Lorenz   }
1017ee02499aSAlex Lorenz 
1018181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
1019181dfe4cSEli Friedman     VisitStmt(E);
1020181dfe4cSEli Friedman 
1021181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
1022181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
1023181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
1024181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
1025181dfe4cSEli Friedman       terminateRegion(E);
1026181dfe4cSEli Friedman   }
1027181dfe4cSEli Friedman 
1028ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
1029bf42cfd7SJustin Bogner     extendRegion(S);
1030ee02499aSAlex Lorenz 
1031bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1032bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1033bf42cfd7SJustin Bogner 
1034bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
1035bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
1036bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1037bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1038ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1039bf42cfd7SJustin Bogner 
1040bf42cfd7SJustin Bogner     // Go back to handle the condition.
1041bf42cfd7SJustin Bogner     Counter CondCount =
1042bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1043bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1044bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
1045bf42cfd7SJustin Bogner 
1046fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1047fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
1048fa8fa044SVedant Kumar     if (Gap)
1049fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1050fa8fa044SVedant Kumar 
1051bf42cfd7SJustin Bogner     Counter OutCount =
1052bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1053bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1054bf42cfd7SJustin Bogner       pushRegion(OutCount);
1055ee02499aSAlex Lorenz   }
1056ee02499aSAlex Lorenz 
1057ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
1058bf42cfd7SJustin Bogner     extendRegion(S);
1059ee02499aSAlex Lorenz 
1060bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1061bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1062bf42cfd7SJustin Bogner 
1063bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
1064bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1065bf42cfd7SJustin Bogner     Counter BackedgeCount =
1066bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1067ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1068bf42cfd7SJustin Bogner 
1069bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1070bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1071bf42cfd7SJustin Bogner 
1072bf42cfd7SJustin Bogner     Counter OutCount =
1073bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1074bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1075bf42cfd7SJustin Bogner       pushRegion(OutCount);
1076ee02499aSAlex Lorenz   }
1077ee02499aSAlex Lorenz 
1078ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
1079bf42cfd7SJustin Bogner     extendRegion(S);
1080ee02499aSAlex Lorenz     if (S->getInit())
1081ee02499aSAlex Lorenz       Visit(S->getInit());
1082ee02499aSAlex Lorenz 
1083bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1084bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1085bf42cfd7SJustin Bogner 
10863e2ae49aSVedant Kumar     // The loop increment may contain a break or continue.
10873e2ae49aSVedant Kumar     if (S->getInc())
10883e2ae49aSVedant Kumar       BreakContinueStack.emplace_back();
10893e2ae49aSVedant Kumar 
1090bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
10913e2ae49aSVedant Kumar     BreakContinueStack.emplace_back();
1092bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1093bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
10943e2ae49aSVedant Kumar     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1095ee02499aSAlex Lorenz 
1096ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
1097ee02499aSAlex Lorenz     // the count for all the continue statements.
10983e2ae49aSVedant Kumar     BreakContinue IncrementBC;
10993e2ae49aSVedant Kumar     if (const Stmt *Inc = S->getInc()) {
11003e2ae49aSVedant Kumar       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
11013e2ae49aSVedant Kumar       IncrementBC = BreakContinueStack.pop_back_val();
11023e2ae49aSVedant Kumar     }
1103bf42cfd7SJustin Bogner 
1104bf42cfd7SJustin Bogner     // Go back to handle the condition.
11053e2ae49aSVedant Kumar     Counter CondCount = addCounters(
11063e2ae49aSVedant Kumar         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
11073e2ae49aSVedant Kumar         IncrementBC.ContinueCount);
1108bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
1109bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
1110bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
1111ee02499aSAlex Lorenz     }
1112ee02499aSAlex Lorenz 
1113fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1114fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1115fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1116fa8fa044SVedant Kumar     if (Gap)
1117fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1118fa8fa044SVedant Kumar 
11193e2ae49aSVedant Kumar     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
11203e2ae49aSVedant Kumar                                    subtractCounters(CondCount, BodyCount));
1121bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1122bf42cfd7SJustin Bogner       pushRegion(OutCount);
1123ee02499aSAlex Lorenz   }
1124ee02499aSAlex Lorenz 
1125ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1126bf42cfd7SJustin Bogner     extendRegion(S);
11278baa5001SRichard Smith     if (S->getInit())
11288baa5001SRichard Smith       Visit(S->getInit());
1129bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
1130ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
1131bf42cfd7SJustin Bogner 
1132bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1133bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1134bf42cfd7SJustin Bogner 
1135ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1136bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1137bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1138ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1139bf42cfd7SJustin Bogner 
1140fa8fa044SVedant Kumar     // The body count applies to the area immediately after the range.
1141fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1142fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1143fa8fa044SVedant Kumar     if (Gap)
1144fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1145fa8fa044SVedant Kumar 
11461587432dSJustin Bogner     Counter LoopCount =
11471587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
11481587432dSJustin Bogner     Counter OutCount =
11491587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1150bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1151bf42cfd7SJustin Bogner       pushRegion(OutCount);
1152ee02499aSAlex Lorenz   }
1153ee02499aSAlex Lorenz 
1154ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1155bf42cfd7SJustin Bogner     extendRegion(S);
1156ee02499aSAlex Lorenz     Visit(S->getElement());
1157bf42cfd7SJustin Bogner 
1158bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1159bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1160bf42cfd7SJustin Bogner 
1161ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1162bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1163bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1164ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1165bf42cfd7SJustin Bogner 
1166fa8fa044SVedant Kumar     // The body count applies to the area immediately after the collection.
1167fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1168fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1169fa8fa044SVedant Kumar     if (Gap)
1170fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1171fa8fa044SVedant Kumar 
11721587432dSJustin Bogner     Counter LoopCount =
11731587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
11741587432dSJustin Bogner     Counter OutCount =
11751587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1176bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1177bf42cfd7SJustin Bogner       pushRegion(OutCount);
1178ee02499aSAlex Lorenz   }
1179ee02499aSAlex Lorenz 
1180ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
1181bf42cfd7SJustin Bogner     extendRegion(S);
1182f2a6ec55SVedant Kumar     if (S->getInit())
1183f2a6ec55SVedant Kumar       Visit(S->getInit());
1184ee02499aSAlex Lorenz     Visit(S->getCond());
1185bf42cfd7SJustin Bogner 
1186ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1187bf42cfd7SJustin Bogner 
1188bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
1189bf42cfd7SJustin Bogner     extendRegion(Body);
1190bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1191bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
11927f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
11937f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
11947f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
1195859bf4d2SVedant Kumar         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1196859bf4d2SVedant Kumar         getRegion().setGap(true);
1197b5841332SRichard Trieu         for (const auto *Child : CS->children())
1198bf42cfd7SJustin Bogner           Visit(Child);
11997f53fbfcSEli Friedman 
12007f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
12017f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
12027f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
12037f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
12047f53fbfcSEli Friedman         }
12057f53fbfcSEli Friedman 
1206bf42cfd7SJustin Bogner         popRegions(Index);
1207ee02499aSAlex Lorenz       }
120887ea3b05SVedant Kumar     } else
1209bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
1210ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1211bf42cfd7SJustin Bogner 
1212ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
1213ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
1214ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1215bf42cfd7SJustin Bogner 
1216bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
12173836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
121808780529SAlex Lorenz     pushRegion(ExitCount);
121908780529SAlex Lorenz 
122008780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
122108780529SAlex Lorenz     // in a different file.
122208780529SAlex Lorenz     MostRecentLocation = getStart(S);
12233836482aSVedant Kumar     handleFileExit(ExitLoc);
1224ee02499aSAlex Lorenz   }
1225ee02499aSAlex Lorenz 
1226bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
1227bf42cfd7SJustin Bogner     extendRegion(S);
1228ee02499aSAlex Lorenz 
1229bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
1230bf42cfd7SJustin Bogner 
1231bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1232bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
1233bf42cfd7SJustin Bogner     // the first case in a switch.
1234a6e4358fSStephen Kelly     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1235bf42cfd7SJustin Bogner       Parent.setCounter(Count);
1236bf42cfd7SJustin Bogner     else
1237bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
1238bf42cfd7SJustin Bogner 
1239376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1240bf42cfd7SJustin Bogner       Visit(CS->getLHS());
1241bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
1242bf42cfd7SJustin Bogner         Visit(RHS);
1243bf42cfd7SJustin Bogner     }
1244ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1245ee02499aSAlex Lorenz   }
1246ee02499aSAlex Lorenz 
1247ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
1248bf42cfd7SJustin Bogner     extendRegion(S);
12499d2a16b9SVedant Kumar     if (S->getInit())
12509d2a16b9SVedant Kumar       Visit(S->getInit());
12519d2a16b9SVedant Kumar 
1252055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
1253055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
1254055ebc34SJustin Bogner     extendRegion(S->getCond());
1255ee02499aSAlex Lorenz 
1256bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1257bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
1258ee02499aSAlex Lorenz 
125991f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
126091f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
126191f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
126291f2e3c9SJustin Bogner 
12632e8c8759SVedant Kumar     // The 'then' count applies to the area immediately after the condition.
1264fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1265fa8fa044SVedant Kumar     if (Gap)
1266fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
12672e8c8759SVedant Kumar 
1268bf42cfd7SJustin Bogner     extendRegion(S->getThen());
1269bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1270bf42cfd7SJustin Bogner 
1271bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1272bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
12732e8c8759SVedant Kumar       // The 'else' count applies to the area immediately after the 'then'.
1274fa8fa044SVedant Kumar       Gap = findGapAreaBetween(S->getThen(), Else);
1275fa8fa044SVedant Kumar       if (Gap)
1276fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
12772e8c8759SVedant Kumar       extendRegion(Else);
1278bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1279bf42cfd7SJustin Bogner     } else
1280bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
1281bf42cfd7SJustin Bogner 
1282bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1283bf42cfd7SJustin Bogner       pushRegion(OutCount);
1284ee02499aSAlex Lorenz   }
1285ee02499aSAlex Lorenz 
1286ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
1287bf42cfd7SJustin Bogner     extendRegion(S);
1288049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
1289049908b2SVedant Kumar     extendRegion(S->getTryBlock());
1290049908b2SVedant Kumar 
1291049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
1292049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
1293049908b2SVedant Kumar 
1294ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1295ee02499aSAlex Lorenz       Visit(S->getHandler(I));
1296bf42cfd7SJustin Bogner 
1297bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
1298bf42cfd7SJustin Bogner     pushRegion(ExitCount);
1299ee02499aSAlex Lorenz   }
1300ee02499aSAlex Lorenz 
1301ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1302bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1303ee02499aSAlex Lorenz   }
1304ee02499aSAlex Lorenz 
1305ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1306bf42cfd7SJustin Bogner     extendRegion(E);
1307ee02499aSAlex Lorenz 
1308bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1309bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
1310ee02499aSAlex Lorenz 
1311e3654ce7SJustin Bogner     Visit(E->getCond());
1312e3654ce7SJustin Bogner 
1313e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
13142e8c8759SVedant Kumar       // The 'then' count applies to the area immediately after the condition.
1315fa8fa044SVedant Kumar       auto Gap =
1316fa8fa044SVedant Kumar           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1317fa8fa044SVedant Kumar       if (Gap)
1318fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
13192e8c8759SVedant Kumar 
1320e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
1321bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
1322e3654ce7SJustin Bogner     }
13232e8c8759SVedant Kumar 
1324e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
1325bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
1326bf42cfd7SJustin Bogner                     E->getFalseExpr());
1327ee02499aSAlex Lorenz   }
1328ee02499aSAlex Lorenz 
1329ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
1330e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1331e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1332e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1333bf42cfd7SJustin Bogner 
1334bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1335bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
1336ee02499aSAlex Lorenz   }
1337ee02499aSAlex Lorenz 
1338ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
1339e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1340e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1341e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1342ee02499aSAlex Lorenz 
1343bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1344bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
134501a0d062SAlex Lorenz   }
1346c109102eSJustin Bogner 
1347c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
1348c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
1349c109102eSJustin Bogner     // propagate counts into them.
1350c109102eSJustin Bogner   }
1351ee02499aSAlex Lorenz };
1352ee02499aSAlex Lorenz 
13537cd595dfSReid Kleckner std::string normalizeFilename(StringRef Filename) {
13547cd595dfSReid Kleckner   llvm::SmallString<256> Path(Filename);
13557cd595dfSReid Kleckner   llvm::sys::fs::make_absolute(Path);
13567cd595dfSReid Kleckner   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1357509e21a1SJonas Devlieghere   return std::string(Path);
13587cd595dfSReid Kleckner }
13597cd595dfSReid Kleckner 
136014f8fb68SVedant Kumar } // end anonymous namespace
136114f8fb68SVedant Kumar 
1362a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1363a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1364a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1365a432d176SJustin Bogner   OS << FunctionName << ":\n";
1366a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1367a432d176SJustin Bogner   for (const auto &R : Regions) {
1368f2cf38e0SAlex Lorenz     OS.indent(2);
1369f2cf38e0SAlex Lorenz     switch (R.Kind) {
1370f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1371f2cf38e0SAlex Lorenz       break;
1372f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1373f2cf38e0SAlex Lorenz       OS << "Expansion,";
1374f2cf38e0SAlex Lorenz       break;
1375f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1376f2cf38e0SAlex Lorenz       OS << "Skipped,";
1377f2cf38e0SAlex Lorenz       break;
1378a1c4deb7SVedant Kumar     case CounterMappingRegion::GapRegion:
1379a1c4deb7SVedant Kumar       OS << "Gap,";
1380a1c4deb7SVedant Kumar       break;
1381f2cf38e0SAlex Lorenz     }
1382f2cf38e0SAlex Lorenz 
13834da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
13844da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1385f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1386f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
13874da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
13884da909b2SJustin Bogner     OS << "\n";
1389f2cf38e0SAlex Lorenz   }
1390f2cf38e0SAlex Lorenz }
1391f2cf38e0SAlex Lorenz 
1392dd1ea9deSVedant Kumar static std::string getInstrProfSection(const CodeGenModule &CGM,
1393dd1ea9deSVedant Kumar                                        llvm::InstrProfSectKind SK) {
1394dd1ea9deSVedant Kumar   return llvm::getInstrProfSectionName(
1395dd1ea9deSVedant Kumar       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1396dd1ea9deSVedant Kumar }
1397dd1ea9deSVedant Kumar 
1398dd1ea9deSVedant Kumar void CoverageMappingModuleGen::emitFunctionMappingRecord(
1399dd1ea9deSVedant Kumar     const FunctionInfo &Info, uint64_t FilenamesRef) {
140099317124SVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1401dd1ea9deSVedant Kumar 
1402dd1ea9deSVedant Kumar   // Assign a name to the function record. This is used to merge duplicates.
1403dd1ea9deSVedant Kumar   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1404dd1ea9deSVedant Kumar 
1405dd1ea9deSVedant Kumar   // A dummy description for a function included-but-not-used in a TU can be
1406dd1ea9deSVedant Kumar   // replaced by full description provided by a different TU. The two kinds of
1407dd1ea9deSVedant Kumar   // descriptions play distinct roles: therefore, assign them different names
1408dd1ea9deSVedant Kumar   // to prevent `linkonce_odr` merging.
1409dd1ea9deSVedant Kumar   if (Info.IsUsed)
1410dd1ea9deSVedant Kumar     FuncRecordName += "u";
1411dd1ea9deSVedant Kumar 
1412dd1ea9deSVedant Kumar   // Create the function record type.
1413dd1ea9deSVedant Kumar   const uint64_t NameHash = Info.NameHash;
1414dd1ea9deSVedant Kumar   const uint64_t FuncHash = Info.FuncHash;
1415dd1ea9deSVedant Kumar   const std::string &CoverageMapping = Info.CoverageMapping;
141633888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
141733888717SVedant Kumar   llvm::Type *FunctionRecordTypes[] = {
141833888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc"
141933888717SVedant Kumar   };
1420dd1ea9deSVedant Kumar   auto *FunctionRecordTy =
142133888717SVedant Kumar       llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
142233888717SVedant Kumar                             /*isPacked=*/true);
142399317124SVedant Kumar 
1424dd1ea9deSVedant Kumar   // Create the function record constant.
142533888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
142633888717SVedant Kumar   llvm::Constant *FunctionRecordVals[] = {
142733888717SVedant Kumar       #include "llvm/ProfileData/InstrProfData.inc"
142833888717SVedant Kumar   };
1429dd1ea9deSVedant Kumar   auto *FuncRecordConstant = llvm::ConstantStruct::get(
1430dd1ea9deSVedant Kumar       FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1431dd1ea9deSVedant Kumar 
1432dd1ea9deSVedant Kumar   // Create the function record global.
1433dd1ea9deSVedant Kumar   auto *FuncRecord = new llvm::GlobalVariable(
1434dd1ea9deSVedant Kumar       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1435dd1ea9deSVedant Kumar       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1436dd1ea9deSVedant Kumar       FuncRecordName);
1437dd1ea9deSVedant Kumar   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1438dd1ea9deSVedant Kumar   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1439dd1ea9deSVedant Kumar   FuncRecord->setAlignment(llvm::Align(8));
1440dd1ea9deSVedant Kumar   if (CGM.supportsCOMDAT())
1441dd1ea9deSVedant Kumar     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1442dd1ea9deSVedant Kumar 
1443dd1ea9deSVedant Kumar   // Make sure the data doesn't get deleted.
1444dd1ea9deSVedant Kumar   CGM.addUsedGlobal(FuncRecord);
1445dd1ea9deSVedant Kumar }
1446dd1ea9deSVedant Kumar 
1447dd1ea9deSVedant Kumar void CoverageMappingModuleGen::addFunctionMappingRecord(
1448dd1ea9deSVedant Kumar     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1449dd1ea9deSVedant Kumar     const std::string &CoverageMapping, bool IsUsed) {
1450dd1ea9deSVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1451dd1ea9deSVedant Kumar   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1452dd1ea9deSVedant Kumar   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1453dd1ea9deSVedant Kumar 
1454848da137SXinliang David Li   if (!IsUsed)
14552129ae53SXinliang David Li     FunctionNames.push_back(
14562129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1457f2cf38e0SAlex Lorenz 
1458f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1459f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1460f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1461f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1462f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1463f2cf38e0SAlex Lorenz     // expressions.
1464f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1465f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1466f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1467b31ee819SJordan Rose     llvm::SmallVector<std::string, 16> FilenameStrs;
1468f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1469b31ee819SJordan Rose     FilenameStrs.resize(FileEntries.size());
1470f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1471b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1472b31ee819SJordan Rose       auto I = Entry.second;
1473b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1474b31ee819SJordan Rose       FilenameRefs[I] = FilenameStrs[I];
1475b31ee819SJordan Rose     }
1476a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1477a432d176SJustin Bogner                                     Expressions, Regions);
1478a432d176SJustin Bogner     if (Reader.read())
1479f2cf38e0SAlex Lorenz       return;
1480a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1481f2cf38e0SAlex Lorenz   }
1482ee02499aSAlex Lorenz }
1483ee02499aSAlex Lorenz 
1484ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1485ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1486ee02499aSAlex Lorenz     return;
1487ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1488ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1489ee02499aSAlex Lorenz 
1490ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1491ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
14929e324dd1SVedant Kumar   llvm::SmallVector<StringRef, 16> FilenameRefs;
1493ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
14949e324dd1SVedant Kumar   FilenameRefs.resize(FileEntries.size());
1495ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1496ee02499aSAlex Lorenz     auto I = Entry.second;
149714f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
14989e324dd1SVedant Kumar     FilenameRefs[I] = FilenameStrs[I];
1499ee02499aSAlex Lorenz   }
1500ee02499aSAlex Lorenz 
1501dd1ea9deSVedant Kumar   std::string Filenames;
1502dd1ea9deSVedant Kumar   {
1503dd1ea9deSVedant Kumar     llvm::raw_string_ostream OS(Filenames);
15049e324dd1SVedant Kumar     CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
15054cd07dbeSSerge Guelton   }
1506dd1ea9deSVedant Kumar   auto *FilenamesVal =
1507dd1ea9deSVedant Kumar       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1508dd1ea9deSVedant Kumar   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
15094cd07dbeSSerge Guelton 
1510dd1ea9deSVedant Kumar   // Emit the function records.
1511dd1ea9deSVedant Kumar   for (const FunctionInfo &Info : FunctionRecords)
1512dd1ea9deSVedant Kumar     emitFunctionMappingRecord(Info, FilenamesRef);
1513ee02499aSAlex Lorenz 
1514dd1ea9deSVedant Kumar   const unsigned NRecords = 0;
1515dd1ea9deSVedant Kumar   const size_t FilenamesSize = Filenames.size();
1516dd1ea9deSVedant Kumar   const unsigned CoverageMappingSize = 0;
151720b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
151820b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
151920b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
152020b188c0SXinliang David Li   };
152120b188c0SXinliang David Li   auto CovDataHeaderTy =
152220b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
152320b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
152420b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
152520b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
152620b188c0SXinliang David Li   };
152720b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
152820b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
152920b188c0SXinliang David Li 
1530ee02499aSAlex Lorenz   // Create the coverage data record
1531dd1ea9deSVedant Kumar   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1532ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1533dd1ea9deSVedant Kumar   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1534ee02499aSAlex Lorenz   auto CovDataVal =
1535ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
153620b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
1537dd1ea9deSVedant Kumar       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
153820b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1539ee02499aSAlex Lorenz 
1540dd1ea9deSVedant Kumar   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1541c79099e0SGuillaume Chatelet   CovData->setAlignment(llvm::Align(8));
1542ee02499aSAlex Lorenz 
1543ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1544ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
15452129ae53SXinliang David Li   // Create the deferred function records array
15462129ae53SXinliang David Li   if (!FunctionNames.empty()) {
15472129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
15482129ae53SXinliang David Li                                            FunctionNames.size());
15492129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
15502129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
15512129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
15522129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
15532129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
15547077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
15552129ae53SXinliang David Li   }
1556ee02499aSAlex Lorenz }
1557ee02499aSAlex Lorenz 
1558ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1559ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1560ee02499aSAlex Lorenz   if (It != FileEntries.end())
1561ee02499aSAlex Lorenz     return It->second;
1562ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1563ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1564ee02499aSAlex Lorenz   return FileID;
1565ee02499aSAlex Lorenz }
1566ee02499aSAlex Lorenz 
1567ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1568ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1569ee02499aSAlex Lorenz   assert(CounterMap);
1570e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1571ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1572ee02499aSAlex Lorenz   Walker.write(OS);
1573ee02499aSAlex Lorenz }
1574ee02499aSAlex Lorenz 
1575ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1576ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1577ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1578ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1579ee02499aSAlex Lorenz   Walker.write(OS);
1580ee02499aSAlex Lorenz }
1581