1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2ee02499aSAlex Lorenz //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ee02499aSAlex Lorenz //
7ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
8ee02499aSAlex Lorenz //
9ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator
10ee02499aSAlex Lorenz //
11ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
12ee02499aSAlex Lorenz 
13ee02499aSAlex Lorenz #include "CoverageMappingGen.h"
14ee02499aSAlex Lorenz #include "CodeGenFunction.h"
15ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h"
16dd1ea9deSVedant Kumar #include "clang/Basic/Diagnostic.h"
17e08464fbSReid Kleckner #include "clang/Basic/FileManager.h"
18dd1ea9deSVedant Kumar #include "clang/Frontend/FrontendDiagnostic.h"
19ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
20e08464fbSReid Kleckner #include "llvm/ADT/Optional.h"
21bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h"
22ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h"
23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
24b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
260d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
27ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
2814f8fb68SVedant Kumar #include "llvm/Support/Path.h"
29ee02499aSAlex Lorenz 
30dd1ea9deSVedant Kumar // This selects the coverage mapping format defined when `InstrProfData.inc`
31dd1ea9deSVedant Kumar // is textually included.
32dd1ea9deSVedant Kumar #define COVMAP_V3
33dd1ea9deSVedant Kumar 
349caa3fbeSZequan Wu static llvm::cl::opt<bool> EmptyLineCommentCoverage(
359caa3fbeSZequan Wu     "emptyline-comment-coverage",
369caa3fbeSZequan Wu     llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
379caa3fbeSZequan Wu                    "disable it on test)"),
389caa3fbeSZequan Wu     llvm::cl::init(true), llvm::cl::Hidden);
399caa3fbeSZequan Wu 
40ee02499aSAlex Lorenz using namespace clang;
41ee02499aSAlex Lorenz using namespace CodeGen;
42ee02499aSAlex Lorenz using namespace llvm::coverage;
43ee02499aSAlex Lorenz 
44b46176bbSZequan Wu CoverageSourceInfo *
45b46176bbSZequan Wu CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
469caa3fbeSZequan Wu   CoverageSourceInfo *CoverageInfo =
479caa3fbeSZequan Wu       new CoverageSourceInfo(PP.getSourceManager());
48b46176bbSZequan Wu   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
499caa3fbeSZequan Wu   if (EmptyLineCommentCoverage) {
50b46176bbSZequan Wu     PP.addCommentHandler(CoverageInfo);
519caa3fbeSZequan Wu     PP.setEmptylineHandler(CoverageInfo);
52b46176bbSZequan Wu     PP.setPreprocessToken(true);
53b46176bbSZequan Wu     PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
54b46176bbSZequan Wu       // Update previous token location.
55b46176bbSZequan Wu       CoverageInfo->PrevTokLoc = Tok.getLocation();
5684fffa67SZequan Wu       if (Tok.getKind() != clang::tok::eod)
57b46176bbSZequan Wu         CoverageInfo->updateNextTokLoc(Tok.getLocation());
58b46176bbSZequan Wu     });
599caa3fbeSZequan Wu   }
60b46176bbSZequan Wu   return CoverageInfo;
61b46176bbSZequan Wu }
62b46176bbSZequan Wu 
639caa3fbeSZequan Wu void CoverageSourceInfo::AddSkippedRange(SourceRange Range) {
649caa3fbeSZequan Wu   if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
659caa3fbeSZequan Wu       PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
669caa3fbeSZequan Wu       SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
679caa3fbeSZequan Wu                                     Range.getBegin()))
689caa3fbeSZequan Wu     SkippedRanges.back().Range.setEnd(Range.getEnd());
699caa3fbeSZequan Wu   else
709caa3fbeSZequan Wu     SkippedRanges.push_back({Range, PrevTokLoc});
719caa3fbeSZequan Wu }
729caa3fbeSZequan Wu 
733919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
749caa3fbeSZequan Wu   AddSkippedRange(Range);
759caa3fbeSZequan Wu }
769caa3fbeSZequan Wu 
779caa3fbeSZequan Wu void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
789caa3fbeSZequan Wu   AddSkippedRange(Range);
79b46176bbSZequan Wu }
80b46176bbSZequan Wu 
81b46176bbSZequan Wu bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
829caa3fbeSZequan Wu   AddSkippedRange(Range);
83b46176bbSZequan Wu   return false;
84b46176bbSZequan Wu }
85b46176bbSZequan Wu 
86b46176bbSZequan Wu void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
879caa3fbeSZequan Wu   if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
88b46176bbSZequan Wu     SkippedRanges.back().NextTokLoc = Loc;
89ee02499aSAlex Lorenz }
90ee02499aSAlex Lorenz 
91ee02499aSAlex Lorenz namespace {
92ee02499aSAlex Lorenz 
939fc8faf9SAdrian Prantl /// A region of source code that can be mapped to a counter.
9409c7179bSJustin Bogner class SourceMappingRegion {
959f2967bcSAlan Phipps   /// Primary Counter that is also used for Branch Regions for "True" branches.
96ee02499aSAlex Lorenz   Counter Count;
97ee02499aSAlex Lorenz 
989f2967bcSAlan Phipps   /// Secondary Counter used for Branch Regions for "False" branches.
999f2967bcSAlan Phipps   Optional<Counter> FalseCount;
1009f2967bcSAlan Phipps 
1019fc8faf9SAdrian Prantl   /// The region's starting location.
102bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
103ee02499aSAlex Lorenz 
1049fc8faf9SAdrian Prantl   /// The region's ending location.
105bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
106ee02499aSAlex Lorenz 
107747b0e29SVedant Kumar   /// Whether this region should be emitted after its parent is emitted.
108747b0e29SVedant Kumar   bool DeferRegion;
109747b0e29SVedant Kumar 
110a1c4deb7SVedant Kumar   /// Whether this region is a gap region. The count from a gap region is set
111a1c4deb7SVedant Kumar   /// as the line execution count if there are no other regions on the line.
112a1c4deb7SVedant Kumar   bool GapRegion;
113a1c4deb7SVedant Kumar 
11409c7179bSJustin Bogner public:
115bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
116a1c4deb7SVedant Kumar                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
117a1c4deb7SVedant Kumar                       bool GapRegion = false)
118747b0e29SVedant Kumar       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
119a1c4deb7SVedant Kumar         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
120ee02499aSAlex Lorenz 
1219f2967bcSAlan Phipps   SourceMappingRegion(Counter Count, Optional<Counter> FalseCount,
1229f2967bcSAlan Phipps                       Optional<SourceLocation> LocStart,
1239f2967bcSAlan Phipps                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
1249f2967bcSAlan Phipps                       bool GapRegion = false)
1259f2967bcSAlan Phipps       : Count(Count), FalseCount(FalseCount), LocStart(LocStart),
1269f2967bcSAlan Phipps         LocEnd(LocEnd), DeferRegion(DeferRegion), GapRegion(GapRegion) {}
1279f2967bcSAlan Phipps 
12809c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
12909c7179bSJustin Bogner 
1309f2967bcSAlan Phipps   const Counter &getFalseCounter() const {
1319f2967bcSAlan Phipps     assert(FalseCount && "Region has no alternate counter");
1329f2967bcSAlan Phipps     return *FalseCount;
1339f2967bcSAlan Phipps   }
1349f2967bcSAlan Phipps 
135bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
13609c7179bSJustin Bogner 
137bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
138bf42cfd7SJustin Bogner 
139bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
140bf42cfd7SJustin Bogner 
1413cffc4c7SStephen Kelly   SourceLocation getBeginLoc() const {
142bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
143bf42cfd7SJustin Bogner     return *LocStart;
14409c7179bSJustin Bogner   }
14509c7179bSJustin Bogner 
146bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
147ee02499aSAlex Lorenz 
148a14a1f92SVedant Kumar   void setEndLoc(SourceLocation Loc) {
149a14a1f92SVedant Kumar     assert(Loc.isValid() && "Setting an invalid end location");
150a14a1f92SVedant Kumar     LocEnd = Loc;
151a14a1f92SVedant Kumar   }
152ee02499aSAlex Lorenz 
153462c77b4SCraig Topper   SourceLocation getEndLoc() const {
154bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
155bf42cfd7SJustin Bogner     return *LocEnd;
156ee02499aSAlex Lorenz   }
157747b0e29SVedant Kumar 
158747b0e29SVedant Kumar   bool isDeferred() const { return DeferRegion; }
159747b0e29SVedant Kumar 
160747b0e29SVedant Kumar   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
161a1c4deb7SVedant Kumar 
162a1c4deb7SVedant Kumar   bool isGap() const { return GapRegion; }
163a1c4deb7SVedant Kumar 
164a1c4deb7SVedant Kumar   void setGap(bool Gap) { GapRegion = Gap; }
1659f2967bcSAlan Phipps 
1669f2967bcSAlan Phipps   bool isBranch() const { return FalseCount.hasValue(); }
167ee02499aSAlex Lorenz };
168ee02499aSAlex Lorenz 
169d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
170d7369648SVedant Kumar struct SpellingRegion {
171d7369648SVedant Kumar   /// The line where the region starts.
172d7369648SVedant Kumar   unsigned LineStart;
173d7369648SVedant Kumar 
174d7369648SVedant Kumar   /// The column where the region starts.
175d7369648SVedant Kumar   unsigned ColumnStart;
176d7369648SVedant Kumar 
177d7369648SVedant Kumar   /// The line where the region ends.
178d7369648SVedant Kumar   unsigned LineEnd;
179d7369648SVedant Kumar 
180d7369648SVedant Kumar   /// The column where the region ends.
181d7369648SVedant Kumar   unsigned ColumnEnd;
182d7369648SVedant Kumar 
183d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
184d7369648SVedant Kumar                  SourceLocation LocEnd) {
185d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
186d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
187d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
188d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
189d7369648SVedant Kumar   }
190d7369648SVedant Kumar 
191fa8fa044SVedant Kumar   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
192a6e4358fSStephen Kelly       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
193fa8fa044SVedant Kumar 
194d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
195d7369648SVedant Kumar   /// top->bottom, left->right.
196d7369648SVedant Kumar   bool isInSourceOrder() const {
197d7369648SVedant Kumar     return (LineStart < LineEnd) ||
198d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
199d7369648SVedant Kumar   }
200d7369648SVedant Kumar };
201d7369648SVedant Kumar 
2029fc8faf9SAdrian Prantl /// Provides the common functionality for the different
203ee02499aSAlex Lorenz /// coverage mapping region builders.
204ee02499aSAlex Lorenz class CoverageMappingBuilder {
205ee02499aSAlex Lorenz public:
206ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
207ee02499aSAlex Lorenz   SourceManager &SM;
208ee02499aSAlex Lorenz   const LangOptions &LangOpts;
209ee02499aSAlex Lorenz 
210ee02499aSAlex Lorenz private:
2119fc8faf9SAdrian Prantl   /// Map of clang's FileIDs to IDs used for coverage mapping.
212bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
213bf42cfd7SJustin Bogner       FileIDMapping;
214ee02499aSAlex Lorenz 
215ee02499aSAlex Lorenz public:
2169fc8faf9SAdrian Prantl   /// The coverage mapping regions for this function
217ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
2189fc8faf9SAdrian Prantl   /// The source mapping regions for this function.
219f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
220ee02499aSAlex Lorenz 
2219fc8faf9SAdrian Prantl   /// A set of regions which can be used as a filter.
222fc05ee34SIgor Kudrin   ///
223fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
224fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
225fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
226fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
227fc05ee34SIgor Kudrin       SourceRegionFilter;
228fc05ee34SIgor Kudrin 
229ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
230ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
231bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
232ee02499aSAlex Lorenz 
2339fc8faf9SAdrian Prantl   /// Return the precise end location for the given token.
234ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
235bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
236bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
237bf42cfd7SJustin Bogner     unsigned TokLen =
238bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
239bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
240ee02499aSAlex Lorenz   }
241ee02499aSAlex Lorenz 
2429fc8faf9SAdrian Prantl   /// Return the start location of an included file or expanded macro.
243bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
244bf42cfd7SJustin Bogner     if (Loc.isMacroID())
245bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
246bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
247ee02499aSAlex Lorenz   }
248ee02499aSAlex Lorenz 
2499fc8faf9SAdrian Prantl   /// Return the end location of an included file or expanded macro.
250bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
251bf42cfd7SJustin Bogner     if (Loc.isMacroID())
252bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
253f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
254bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
255bf42cfd7SJustin Bogner   }
256ee02499aSAlex Lorenz 
2579fc8faf9SAdrian Prantl   /// Find out where the current file is included or macro is expanded.
258bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
259b5f8171aSRichard Smith     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
260bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
261bf42cfd7SJustin Bogner   }
262bf42cfd7SJustin Bogner 
2639fc8faf9SAdrian Prantl   /// Return true if \c Loc is a location in a built-in macro.
264682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
26599d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
266682bfbf3SJustin Bogner   }
267682bfbf3SJustin Bogner 
2689fc8faf9SAdrian Prantl   /// Check whether \c Loc is included or expanded from \c Parent.
269d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
270d9e1a61dSIgor Kudrin     do {
271d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
272d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
273d9e1a61dSIgor Kudrin         return false;
274d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
275d9e1a61dSIgor Kudrin     return true;
276d9e1a61dSIgor Kudrin   }
277d9e1a61dSIgor Kudrin 
2789fc8faf9SAdrian Prantl   /// Get the start of \c S ignoring macro arguments and builtin macros.
279bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
280f2ceec48SStephen Kelly     SourceLocation Loc = S->getBeginLoc();
281682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
282b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
283bf42cfd7SJustin Bogner     return Loc;
284bf42cfd7SJustin Bogner   }
285bf42cfd7SJustin Bogner 
2869fc8faf9SAdrian Prantl   /// Get the end of \c S ignoring macro arguments and builtin macros.
287bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
2881c301dcbSStephen Kelly     SourceLocation Loc = S->getEndLoc();
289682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
290b5f8171aSRichard Smith       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
291f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
292bf42cfd7SJustin Bogner   }
293bf42cfd7SJustin Bogner 
2949fc8faf9SAdrian Prantl   /// Find the set of files we have regions for and assign IDs
295bf42cfd7SJustin Bogner   ///
296bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
297bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
298bf42cfd7SJustin Bogner   /// expansion regions.
299bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
300bf42cfd7SJustin Bogner     FileIDMapping.clear();
301bf42cfd7SJustin Bogner 
302bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
303bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
304bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
305a6e4358fSStephen Kelly       SourceLocation Loc = Region.getBeginLoc();
306bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
307bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
308bf42cfd7SJustin Bogner         continue;
309bf42cfd7SJustin Bogner 
31093205af0SVedant Kumar       // Do not map FileID's associated with system headers.
31193205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
31293205af0SVedant Kumar         continue;
31393205af0SVedant Kumar 
314bf42cfd7SJustin Bogner       unsigned Depth = 0;
315bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
316ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
317bf42cfd7SJustin Bogner         ++Depth;
318bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
319bf42cfd7SJustin Bogner     }
320899d1392SFangrui Song     llvm::stable_sort(FileLocs, llvm::less_second());
321bf42cfd7SJustin Bogner 
322bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
323bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
324bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
325ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
326ee02499aSAlex Lorenz       if (!Entry)
327bf42cfd7SJustin Bogner         continue;
328ee02499aSAlex Lorenz 
329bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
330bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
331bf42cfd7SJustin Bogner     }
332ee02499aSAlex Lorenz   }
333ee02499aSAlex Lorenz 
3349fc8faf9SAdrian Prantl   /// Get the coverage mapping file ID for \c Loc.
335bf42cfd7SJustin Bogner   ///
336bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
337bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
338bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
339bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
340bf42cfd7SJustin Bogner       return Mapping->second.first;
341903678caSJustin Bogner     return None;
342ee02499aSAlex Lorenz   }
343ee02499aSAlex Lorenz 
344b46176bbSZequan Wu   /// This shrinks the skipped range if it spans a line that contains a
345b46176bbSZequan Wu   /// non-comment token. If shrinking the skipped range would make it empty,
346b46176bbSZequan Wu   /// this returns None.
347b46176bbSZequan Wu   Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
34884fffa67SZequan Wu                                               SourceLocation LocStart,
34984fffa67SZequan Wu                                               SourceLocation LocEnd,
350b46176bbSZequan Wu                                               SourceLocation PrevTokLoc,
351b46176bbSZequan Wu                                               SourceLocation NextTokLoc) {
35284fffa67SZequan Wu     SpellingRegion SR{SM, LocStart, LocEnd};
3539caa3fbeSZequan Wu     SR.ColumnStart = 1;
3549caa3fbeSZequan Wu     if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
3559caa3fbeSZequan Wu         SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
3569caa3fbeSZequan Wu       SR.LineStart++;
3579caa3fbeSZequan Wu     if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
3589caa3fbeSZequan Wu         SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
3599caa3fbeSZequan Wu       SR.LineEnd--;
3609caa3fbeSZequan Wu       SR.ColumnEnd++;
3619caa3fbeSZequan Wu     }
3629caa3fbeSZequan Wu     if (SR.isInSourceOrder())
363b46176bbSZequan Wu       return SR;
364b46176bbSZequan Wu     return None;
365b46176bbSZequan Wu   }
366b46176bbSZequan Wu 
3679fc8faf9SAdrian Prantl   /// Gather all the regions that were skipped by the preprocessor
368b46176bbSZequan Wu   /// using the constructs like #if or comments.
369ee02499aSAlex Lorenz   void gatherSkippedRegions() {
370ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
371ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
372ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
373ee02499aSAlex Lorenz     FileLineRanges.resize(
374ee02499aSAlex Lorenz         FileIDMapping.size(),
375ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
376ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
377ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
378ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
379ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
380ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
381ee02499aSAlex Lorenz     }
382ee02499aSAlex Lorenz 
383ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
384b46176bbSZequan Wu     for (auto &I : SkippedRanges) {
385b46176bbSZequan Wu       SourceRange Range = I.Range;
386b46176bbSZequan Wu       auto LocStart = Range.getBegin();
387b46176bbSZequan Wu       auto LocEnd = Range.getEnd();
388bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
389bf42cfd7SJustin Bogner              "region spans multiple files");
390ee02499aSAlex Lorenz 
391bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
392903678caSJustin Bogner       if (!CovFileID)
393ee02499aSAlex Lorenz         continue;
39484fffa67SZequan Wu       Optional<SpellingRegion> SR =
39584fffa67SZequan Wu           adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc);
39684fffa67SZequan Wu       if (!SR.hasValue())
397b46176bbSZequan Wu         continue;
398fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
39984fffa67SZequan Wu           *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
40084fffa67SZequan Wu           SR->ColumnEnd);
401ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
4022a8c18d9SAlexander Kornienko       // the source code of this function.
403903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
404903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
405ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
406ee02499aSAlex Lorenz     }
407ee02499aSAlex Lorenz   }
408ee02499aSAlex Lorenz 
4099fc8faf9SAdrian Prantl   /// Generate the coverage counter mapping regions from collected
410ee02499aSAlex Lorenz   /// source regions.
411fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
412bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
413bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
414ee02499aSAlex Lorenz 
415a6e4358fSStephen Kelly       SourceLocation LocStart = Region.getBeginLoc();
4168b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
417f59329b0SJustin Bogner 
41893205af0SVedant Kumar       // Ignore regions from system headers.
41993205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
42093205af0SVedant Kumar         continue;
42193205af0SVedant Kumar 
422bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
423bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
424bf42cfd7SJustin Bogner       if (!CovFileID)
425ee02499aSAlex Lorenz         continue;
426ee02499aSAlex Lorenz 
427f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
428bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
429bf42cfd7SJustin Bogner              "region spans multiple files");
430bf42cfd7SJustin Bogner 
431fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
432fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
433fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
434fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
435fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
436fc05ee34SIgor Kudrin         continue;
437fc05ee34SIgor Kudrin 
438d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
439d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
440d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
441a1c4deb7SVedant Kumar 
442a1c4deb7SVedant Kumar       if (Region.isGap()) {
443a1c4deb7SVedant Kumar         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
444a1c4deb7SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
445a1c4deb7SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
4469f2967bcSAlan Phipps       } else if (Region.isBranch()) {
4479f2967bcSAlan Phipps         MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
4489f2967bcSAlan Phipps             Region.getCounter(), Region.getFalseCounter(), *CovFileID,
4499f2967bcSAlan Phipps             SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
450a1c4deb7SVedant Kumar       } else {
451bf42cfd7SJustin Bogner         MappingRegions.push_back(CounterMappingRegion::makeRegion(
452d7369648SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
453d7369648SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
454bf42cfd7SJustin Bogner       }
455bf42cfd7SJustin Bogner     }
456a1c4deb7SVedant Kumar   }
457bf42cfd7SJustin Bogner 
4589fc8faf9SAdrian Prantl   /// Generate expansion regions for each virtual file we've seen.
459fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
460fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
461bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
462bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
463bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
464bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
465ee02499aSAlex Lorenz         continue;
466ee02499aSAlex Lorenz 
467bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
468bf42cfd7SJustin Bogner       if (!ParentFileID)
469bf42cfd7SJustin Bogner         continue;
470bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
471bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
472bf42cfd7SJustin Bogner 
473bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
474bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
475bf42cfd7SJustin Bogner              "region spans multiple files");
476fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
477bf42cfd7SJustin Bogner 
478d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
479d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
480bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
481d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
482d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
483ee02499aSAlex Lorenz     }
484fc05ee34SIgor Kudrin     return Filter;
485ee02499aSAlex Lorenz   }
486ee02499aSAlex Lorenz };
487ee02499aSAlex Lorenz 
4889fc8faf9SAdrian Prantl /// Creates unreachable coverage regions for the functions that
489ee02499aSAlex Lorenz /// are not emitted.
490ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
491ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
492ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
493ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
494ee02499aSAlex Lorenz 
495ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
496ee02499aSAlex Lorenz     if (!D->hasBody())
497ee02499aSAlex Lorenz       return;
498ee02499aSAlex Lorenz     auto Body = D->getBody();
499d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
500d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
501d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
502d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
503d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
504d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
505d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
506d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
507d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
508d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
509d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
510d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
511d9e1a61dSIgor Kudrin       }
512d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
513d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
514d9e1a61dSIgor Kudrin         assert(End.isValid() &&
515d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
516d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
517d9e1a61dSIgor Kudrin       }
518d9e1a61dSIgor Kudrin     }
519d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
520ee02499aSAlex Lorenz   }
521ee02499aSAlex Lorenz 
5229fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
523ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
524ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
525bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
526fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
527ee02499aSAlex Lorenz 
528efd319a2SVedant Kumar     if (MappingRegions.empty())
529efd319a2SVedant Kumar       return;
530efd319a2SVedant Kumar 
5315fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
532ee02499aSAlex Lorenz     Writer.write(OS);
533ee02499aSAlex Lorenz   }
534ee02499aSAlex Lorenz };
535ee02499aSAlex Lorenz 
5369fc8faf9SAdrian Prantl /// A StmtVisitor that creates coverage mapping regions which map
537ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
538ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
539ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
540ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
5419fc8faf9SAdrian Prantl   /// The map of statements to count values.
542ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
543ee02499aSAlex Lorenz 
5449fc8faf9SAdrian Prantl   /// A stack of currently live regions.
545bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
546ee02499aSAlex Lorenz 
547747b0e29SVedant Kumar   /// The currently deferred region: its end location and count can be set once
548747b0e29SVedant Kumar   /// its parent has been popped from the region stack.
549747b0e29SVedant Kumar   Optional<SourceMappingRegion> DeferredRegion;
550747b0e29SVedant Kumar 
551ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
552ee02499aSAlex Lorenz 
5539fc8faf9SAdrian Prantl   /// A location in the most recently visited file or macro.
554bf42cfd7SJustin Bogner   ///
555bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
556bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
557bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
558bf42cfd7SJustin Bogner 
5598046d22aSVedant Kumar   /// Location of the last terminated region.
5608046d22aSVedant Kumar   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
5618046d22aSVedant Kumar 
5629fc8faf9SAdrian Prantl   /// Return a counter for the subtraction of \c RHS from \c LHS
563ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
564ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
565ee02499aSAlex Lorenz   }
566ee02499aSAlex Lorenz 
5679fc8faf9SAdrian Prantl   /// Return a counter for the sum of \c LHS and \c RHS.
568ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
569ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
570ee02499aSAlex Lorenz   }
571ee02499aSAlex Lorenz 
572bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
573bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
574bf42cfd7SJustin Bogner   }
575bf42cfd7SJustin Bogner 
5769fc8faf9SAdrian Prantl   /// Return the region counter for the given statement.
577bf42cfd7SJustin Bogner   ///
578ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
579bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
580bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
581ee02499aSAlex Lorenz   }
582ee02499aSAlex Lorenz 
5839fc8faf9SAdrian Prantl   /// Push a region onto the stack.
584bf42cfd7SJustin Bogner   ///
585bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
586bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
587bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
5889f2967bcSAlan Phipps                     Optional<SourceLocation> EndLoc = None,
5899f2967bcSAlan Phipps                     Optional<Counter> FalseCount = None) {
5909f2967bcSAlan Phipps 
5919f2967bcSAlan Phipps     if (StartLoc && !FalseCount.hasValue()) {
592bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
593747b0e29SVedant Kumar       completeDeferred(Count, MostRecentLocation);
594747b0e29SVedant Kumar     }
5959f2967bcSAlan Phipps 
5969f2967bcSAlan Phipps     RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc,
5979f2967bcSAlan Phipps                              FalseCount.hasValue());
598ee02499aSAlex Lorenz 
599bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
600ee02499aSAlex Lorenz   }
601ee02499aSAlex Lorenz 
602747b0e29SVedant Kumar   /// Complete any pending deferred region by setting its end location and
603747b0e29SVedant Kumar   /// count, and then pushing it onto the region stack.
604747b0e29SVedant Kumar   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
605747b0e29SVedant Kumar     size_t Index = RegionStack.size();
606747b0e29SVedant Kumar     if (!DeferredRegion)
607747b0e29SVedant Kumar       return Index;
608747b0e29SVedant Kumar 
609747b0e29SVedant Kumar     // Consume the pending region.
610747b0e29SVedant Kumar     SourceMappingRegion DR = DeferredRegion.getValue();
611747b0e29SVedant Kumar     DeferredRegion = None;
612747b0e29SVedant Kumar 
613747b0e29SVedant Kumar     // If the region ends in an expansion, find the expansion site.
614a6e4358fSStephen Kelly     FileID StartFile = SM.getFileID(DR.getBeginLoc());
615f9a0d44eSVedant Kumar     if (SM.getFileID(DeferredEndLoc) != StartFile) {
616747b0e29SVedant Kumar       if (isNestedIn(DeferredEndLoc, StartFile)) {
617747b0e29SVedant Kumar         do {
618747b0e29SVedant Kumar           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
619747b0e29SVedant Kumar         } while (StartFile != SM.getFileID(DeferredEndLoc));
620f9a0d44eSVedant Kumar       } else {
621f9a0d44eSVedant Kumar         return Index;
622747b0e29SVedant Kumar       }
623747b0e29SVedant Kumar     }
624747b0e29SVedant Kumar 
625747b0e29SVedant Kumar     // The parent of this deferred region ends where the containing decl ends,
626747b0e29SVedant Kumar     // so the region isn't useful.
627a6e4358fSStephen Kelly     if (DR.getBeginLoc() == DeferredEndLoc)
628747b0e29SVedant Kumar       return Index;
629747b0e29SVedant Kumar 
630747b0e29SVedant Kumar     // If we're visiting statements in non-source order (e.g switch cases or
631747b0e29SVedant Kumar     // a loop condition) we can't construct a sensible deferred region.
632a6e4358fSStephen Kelly     if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
633747b0e29SVedant Kumar       return Index;
634747b0e29SVedant Kumar 
635a1c4deb7SVedant Kumar     DR.setGap(true);
636747b0e29SVedant Kumar     DR.setCounter(Count);
637747b0e29SVedant Kumar     DR.setEndLoc(DeferredEndLoc);
638747b0e29SVedant Kumar     handleFileExit(DeferredEndLoc);
639747b0e29SVedant Kumar     RegionStack.push_back(DR);
640747b0e29SVedant Kumar     return Index;
641747b0e29SVedant Kumar   }
642747b0e29SVedant Kumar 
6438046d22aSVedant Kumar   /// Complete a deferred region created after a terminated region at the
6448046d22aSVedant Kumar   /// top-level.
6458046d22aSVedant Kumar   void completeTopLevelDeferredRegion(Counter Count,
6468046d22aSVedant Kumar                                       SourceLocation DeferredEndLoc) {
6478046d22aSVedant Kumar     if (DeferredRegion || !LastTerminatedRegion)
6488046d22aSVedant Kumar       return;
6498046d22aSVedant Kumar 
6508046d22aSVedant Kumar     if (LastTerminatedRegion->second != RegionStack.size())
6518046d22aSVedant Kumar       return;
6528046d22aSVedant Kumar 
6538046d22aSVedant Kumar     SourceLocation Start = LastTerminatedRegion->first;
6548046d22aSVedant Kumar     if (SM.getFileID(Start) != SM.getMainFileID())
6558046d22aSVedant Kumar       return;
6568046d22aSVedant Kumar 
6578046d22aSVedant Kumar     SourceMappingRegion DR = RegionStack.back();
6588046d22aSVedant Kumar     DR.setStartLoc(Start);
6598046d22aSVedant Kumar     DR.setDeferred(false);
6608046d22aSVedant Kumar     DeferredRegion = DR;
6618046d22aSVedant Kumar     completeDeferred(Count, DeferredEndLoc);
6628046d22aSVedant Kumar   }
6638046d22aSVedant Kumar 
6640c3e3115SVedant Kumar   size_t locationDepth(SourceLocation Loc) {
6650c3e3115SVedant Kumar     size_t Depth = 0;
6660c3e3115SVedant Kumar     while (Loc.isValid()) {
6670c3e3115SVedant Kumar       Loc = getIncludeOrExpansionLoc(Loc);
6680c3e3115SVedant Kumar       Depth++;
6690c3e3115SVedant Kumar     }
6700c3e3115SVedant Kumar     return Depth;
6710c3e3115SVedant Kumar   }
6720c3e3115SVedant Kumar 
6739fc8faf9SAdrian Prantl   /// Pop regions from the stack into the function's list of regions.
674bf42cfd7SJustin Bogner   ///
675bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
676bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
677bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
678bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
679747b0e29SVedant Kumar     bool ParentOfDeferredRegion = false;
680bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
681bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
682bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
683a6e4358fSStephen Kelly         SourceLocation StartLoc = Region.getBeginLoc();
684bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
685bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
686bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
6879f2967bcSAlan Phipps         bool isBranch = Region.isBranch();
6880c3e3115SVedant Kumar         size_t StartDepth = locationDepth(StartLoc);
6890c3e3115SVedant Kumar         size_t EndDepth = locationDepth(EndLoc);
690bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
6910c3e3115SVedant Kumar           bool UnnestStart = StartDepth >= EndDepth;
6920c3e3115SVedant Kumar           bool UnnestEnd = EndDepth >= StartDepth;
6930c3e3115SVedant Kumar           if (UnnestEnd) {
6949f2967bcSAlan Phipps             // The region ends in a nested file or macro expansion. If the
6959f2967bcSAlan Phipps             // region is not a branch region, create a separate region for each
6969f2967bcSAlan Phipps             // expansion, and for all regions, update the EndLoc. Branch
6979f2967bcSAlan Phipps             // regions should not be split in order to keep a straightforward
6989f2967bcSAlan Phipps             // correspondance between the region and its associated branch
6999f2967bcSAlan Phipps             // condition, even if the condition spans multiple depths.
700bf42cfd7SJustin Bogner             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
701bf42cfd7SJustin Bogner             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
702bf42cfd7SJustin Bogner 
7039f2967bcSAlan Phipps             if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
7049f2967bcSAlan Phipps               SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
7059f2967bcSAlan Phipps                                          EndLoc);
706bf42cfd7SJustin Bogner 
707f14b2078SJustin Bogner             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
708dceaaadfSJustin Bogner             if (EndLoc.isInvalid())
7099f2967bcSAlan Phipps               llvm::report_fatal_error(
7109f2967bcSAlan Phipps                   "File exit not handled before popRegions");
7110c3e3115SVedant Kumar             EndDepth--;
712bf42cfd7SJustin Bogner           }
7130c3e3115SVedant Kumar           if (UnnestStart) {
7149f2967bcSAlan Phipps             // The region ends in a nested file or macro expansion. If the
7159f2967bcSAlan Phipps             // region is not a branch region, create a separate region for each
7169f2967bcSAlan Phipps             // expansion, and for all regions, update the StartLoc. Branch
7179f2967bcSAlan Phipps             // regions should not be split in order to keep a straightforward
7189f2967bcSAlan Phipps             // correspondance between the region and its associated branch
7199f2967bcSAlan Phipps             // condition, even if the condition spans multiple depths.
7200c3e3115SVedant Kumar             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
7210c3e3115SVedant Kumar             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
7220c3e3115SVedant Kumar 
7239f2967bcSAlan Phipps             if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
7249f2967bcSAlan Phipps               SourceRegions.emplace_back(Region.getCounter(), StartLoc,
7259f2967bcSAlan Phipps                                          NestedLoc);
7260c3e3115SVedant Kumar 
7270c3e3115SVedant Kumar             StartLoc = getIncludeOrExpansionLoc(StartLoc);
7280c3e3115SVedant Kumar             if (StartLoc.isInvalid())
7299f2967bcSAlan Phipps               llvm::report_fatal_error(
7309f2967bcSAlan Phipps                   "File exit not handled before popRegions");
7310c3e3115SVedant Kumar             StartDepth--;
7320c3e3115SVedant Kumar           }
7330c3e3115SVedant Kumar         }
7340c3e3115SVedant Kumar         Region.setStartLoc(StartLoc);
735bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
736bf42cfd7SJustin Bogner 
7379f2967bcSAlan Phipps         if (!isBranch) {
738bf42cfd7SJustin Bogner           MostRecentLocation = EndLoc;
7399f2967bcSAlan Phipps           // If this region happens to span an entire expansion, we need to
7409f2967bcSAlan Phipps           // make sure we don't overlap the parent region with it.
741bf42cfd7SJustin Bogner           if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
742bf42cfd7SJustin Bogner               EndLoc == getEndOfFileOrMacro(EndLoc))
743bf42cfd7SJustin Bogner             MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
7449f2967bcSAlan Phipps         }
745bf42cfd7SJustin Bogner 
746a6e4358fSStephen Kelly         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
747fa8fa044SVedant Kumar         assert(SpellingRegion(SM, Region).isInSourceOrder());
748f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
749747b0e29SVedant Kumar 
750747b0e29SVedant Kumar         if (ParentOfDeferredRegion) {
751747b0e29SVedant Kumar           ParentOfDeferredRegion = false;
752747b0e29SVedant Kumar 
753747b0e29SVedant Kumar           // If there's an existing deferred region, keep the old one, because
754747b0e29SVedant Kumar           // it means there are two consecutive returns (or a similar pattern).
755747b0e29SVedant Kumar           if (!DeferredRegion.hasValue() &&
756747b0e29SVedant Kumar               // File IDs aren't gathered within macro expansions, so it isn't
757747b0e29SVedant Kumar               // useful to try and create a deferred region inside of one.
758f9a0d44eSVedant Kumar               !EndLoc.isMacroID())
759747b0e29SVedant Kumar             DeferredRegion =
760747b0e29SVedant Kumar                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
761747b0e29SVedant Kumar         }
762747b0e29SVedant Kumar       } else if (Region.isDeferred()) {
763747b0e29SVedant Kumar         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
764747b0e29SVedant Kumar         ParentOfDeferredRegion = true;
765bf42cfd7SJustin Bogner       }
766bf42cfd7SJustin Bogner       RegionStack.pop_back();
7678046d22aSVedant Kumar 
7688046d22aSVedant Kumar       // If the zero region pushed after the last terminated region no longer
7698046d22aSVedant Kumar       // exists, clear its cached information.
7708046d22aSVedant Kumar       if (LastTerminatedRegion &&
7718046d22aSVedant Kumar           RegionStack.size() < LastTerminatedRegion->second)
7728046d22aSVedant Kumar         LastTerminatedRegion = None;
773bf42cfd7SJustin Bogner     }
774747b0e29SVedant Kumar     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
775ee02499aSAlex Lorenz   }
776ee02499aSAlex Lorenz 
7779fc8faf9SAdrian Prantl   /// Return the currently active region.
778bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
779bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
780bf42cfd7SJustin Bogner     return RegionStack.back();
781ee02499aSAlex Lorenz   }
782ee02499aSAlex Lorenz 
7837225a261SVedant Kumar   /// Propagate counts through the children of \p S if \p VisitChildren is true.
7847225a261SVedant Kumar   /// Otherwise, only emit a count for \p S itself.
7857225a261SVedant Kumar   Counter propagateCounts(Counter TopCount, const Stmt *S,
7867225a261SVedant Kumar                           bool VisitChildren = true) {
7877838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
7887838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
7897838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
7907225a261SVedant Kumar     if (VisitChildren)
791bf42cfd7SJustin Bogner       Visit(S);
792bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
793bf42cfd7SJustin Bogner     popRegions(Index);
79439f01975SVedant Kumar 
79539f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
79639f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
797f2ceec48SStephen Kelly     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
7987838696eSVedant Kumar       MostRecentLocation = EndLoc;
79939f01975SVedant Kumar 
800bf42cfd7SJustin Bogner     return ExitCount;
801ee02499aSAlex Lorenz   }
802ee02499aSAlex Lorenz 
8039f2967bcSAlan Phipps   /// Determine whether the given condition can be constant folded.
8049f2967bcSAlan Phipps   bool ConditionFoldsToBool(const Expr *Cond) {
8059f2967bcSAlan Phipps     Expr::EvalResult Result;
8069f2967bcSAlan Phipps     return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
8079f2967bcSAlan Phipps   }
8089f2967bcSAlan Phipps 
8099f2967bcSAlan Phipps   /// Create a Branch Region around an instrumentable condition for coverage
8109f2967bcSAlan Phipps   /// and add it to the function's SourceRegions.  A branch region tracks a
8119f2967bcSAlan Phipps   /// "True" counter and a "False" counter for boolean expressions that
8129f2967bcSAlan Phipps   /// result in the generation of a branch.
8139f2967bcSAlan Phipps   void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) {
8149f2967bcSAlan Phipps     // Check for NULL conditions.
8159f2967bcSAlan Phipps     if (!C)
8169f2967bcSAlan Phipps       return;
8179f2967bcSAlan Phipps 
8189f2967bcSAlan Phipps     // Ensure we are an instrumentable condition (i.e. no "&&" or "||").  Push
8199f2967bcSAlan Phipps     // region onto RegionStack but immediately pop it (which adds it to the
8209f2967bcSAlan Phipps     // function's SourceRegions) because it doesn't apply to any other source
8219f2967bcSAlan Phipps     // code other than the Condition.
8229f2967bcSAlan Phipps     if (CodeGenFunction::isInstrumentedCondition(C)) {
8239f2967bcSAlan Phipps       // If a condition can fold to true or false, the corresponding branch
8249f2967bcSAlan Phipps       // will be removed.  Create a region with both counters hard-coded to
8259f2967bcSAlan Phipps       // zero. This allows us to visualize them in a special way.
8269f2967bcSAlan Phipps       // Alternatively, we can prevent any optimization done via
8279f2967bcSAlan Phipps       // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
8289f2967bcSAlan Phipps       // CodeGenFunction.c always returns false, but that is very heavy-handed.
8299f2967bcSAlan Phipps       if (ConditionFoldsToBool(C))
8309f2967bcSAlan Phipps         popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
8319f2967bcSAlan Phipps                               Counter::getZero()));
8329f2967bcSAlan Phipps       else
8339f2967bcSAlan Phipps         // Otherwise, create a region with the True counter and False counter.
8349f2967bcSAlan Phipps         popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt));
8359f2967bcSAlan Phipps     }
8369f2967bcSAlan Phipps   }
8379f2967bcSAlan Phipps 
8389f2967bcSAlan Phipps   /// Create a Branch Region around a SwitchCase for code coverage
8399f2967bcSAlan Phipps   /// and add it to the function's SourceRegions.
8409f2967bcSAlan Phipps   void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
8419f2967bcSAlan Phipps                               Counter FalseCnt) {
8429f2967bcSAlan Phipps     // Push region onto RegionStack but immediately pop it (which adds it to
8439f2967bcSAlan Phipps     // the function's SourceRegions) because it doesn't apply to any other
8449f2967bcSAlan Phipps     // source other than the SwitchCase.
8459f2967bcSAlan Phipps     popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
8469f2967bcSAlan Phipps   }
8479f2967bcSAlan Phipps 
8489fc8faf9SAdrian Prantl   /// Check whether a region with bounds \c StartLoc and \c EndLoc
8490a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
8509f2967bcSAlan Phipps   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
8519f2967bcSAlan Phipps                             bool isBranch = false) {
8520a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
8530a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
8540a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
855a6e4358fSStephen Kelly                           return Region.getBeginLoc() == StartLoc &&
8569f2967bcSAlan Phipps                                  Region.getEndLoc() == EndLoc &&
8579f2967bcSAlan Phipps                                  Region.isBranch() == isBranch;
8580a7c9d11SIgor Kudrin                         });
8590a7c9d11SIgor Kudrin   }
8600a7c9d11SIgor Kudrin 
8619fc8faf9SAdrian Prantl   /// Adjust the most recently visited location to \c EndLoc.
862bf42cfd7SJustin Bogner   ///
863bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
864bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
865bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
8660a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
8670a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
8680a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
8690a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
8700a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
87196ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
8720a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
8730a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
8749f2967bcSAlan Phipps                              MostRecentLocation, getRegion().isBranch()))
875bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
876ee02499aSAlex Lorenz   }
877ee02499aSAlex Lorenz 
8789fc8faf9SAdrian Prantl   /// Adjust regions and state when \c NewLoc exits a file.
879bf42cfd7SJustin Bogner   ///
880bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
881bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
882bf42cfd7SJustin Bogner   /// for the exited file.
883bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
884e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
885e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
886bf42cfd7SJustin Bogner       return;
887bf42cfd7SJustin Bogner 
888bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
889bf42cfd7SJustin Bogner     // find the common ancestor.
890bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
891bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
892bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
893bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
894bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
895bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
896bf42cfd7SJustin Bogner         // to adjust our location to the new file.
897bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
898bf42cfd7SJustin Bogner         return;
899bf42cfd7SJustin Bogner       }
900bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
901ee02499aSAlex Lorenz     }
902ee02499aSAlex Lorenz 
903bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
904bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
90557d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
90657d3f145SPete Cooper       if (!I.hasStartLoc())
907bf42cfd7SJustin Bogner         continue;
908a6e4358fSStephen Kelly       SourceLocation Loc = I.getBeginLoc();
909bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
91057d3f145SPete Cooper         ParentCounter = I.getCounter();
911bf42cfd7SJustin Bogner         break;
912ee02499aSAlex Lorenz       }
913bf42cfd7SJustin Bogner 
914bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
915bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
916bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
917bf42cfd7SJustin Bogner         // we've seen this region.
9189f2967bcSAlan Phipps         if (StartLocs.insert(Loc).second) {
9199f2967bcSAlan Phipps           if (I.isBranch())
9209f2967bcSAlan Phipps             SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc,
9219f2967bcSAlan Phipps                                        getEndOfFileOrMacro(Loc), I.isBranch());
9229f2967bcSAlan Phipps           else
92357d3f145SPete Cooper             SourceRegions.emplace_back(I.getCounter(), Loc,
924bf42cfd7SJustin Bogner                                        getEndOfFileOrMacro(Loc));
9259f2967bcSAlan Phipps         }
926bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
927ee02499aSAlex Lorenz       }
92857d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
929bf42cfd7SJustin Bogner     }
930bf42cfd7SJustin Bogner 
931bf42cfd7SJustin Bogner     if (ParentCounter) {
932bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
933bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
934bf42cfd7SJustin Bogner       // corresponding to the parent.
935bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
936bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
937bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
938fa8fa044SVedant Kumar         if (StartLocs.insert(FileStart).second) {
939bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
940bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
941fa8fa044SVedant Kumar           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
942fa8fa044SVedant Kumar         }
943bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
944bf42cfd7SJustin Bogner       }
945bf42cfd7SJustin Bogner     }
946bf42cfd7SJustin Bogner 
947bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
948bf42cfd7SJustin Bogner   }
949bf42cfd7SJustin Bogner 
9509fc8faf9SAdrian Prantl   /// Ensure that \c S is included in the current region.
951bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
952bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
953bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
954bf42cfd7SJustin Bogner 
955bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
956bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
957bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
958747b0e29SVedant Kumar 
959747b0e29SVedant Kumar     completeDeferred(Region.getCounter(), StartLoc);
960bf42cfd7SJustin Bogner   }
961bf42cfd7SJustin Bogner 
9629fc8faf9SAdrian Prantl   /// Mark \c S as a terminator, starting a zero region.
963bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
964bf42cfd7SJustin Bogner     extendRegion(S);
965bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
9668046d22aSVedant Kumar     SourceLocation EndLoc = getEnd(S);
967bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
9688046d22aSVedant Kumar       Region.setEndLoc(EndLoc);
969bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
9708046d22aSVedant Kumar     auto &ZeroRegion = getRegion();
9718046d22aSVedant Kumar     ZeroRegion.setDeferred(true);
9728046d22aSVedant Kumar     LastTerminatedRegion = {EndLoc, RegionStack.size()};
973bf42cfd7SJustin Bogner   }
974ee02499aSAlex Lorenz 
975fa8fa044SVedant Kumar   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
976fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
977fa8fa044SVedant Kumar                                            SourceLocation BeforeLoc) {
978d83511ddSZequan Wu     size_t StartDepth = locationDepth(AfterLoc);
979d83511ddSZequan Wu     size_t EndDepth = locationDepth(BeforeLoc);
980d83511ddSZequan Wu     while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
981d83511ddSZequan Wu       bool UnnestStart = StartDepth >= EndDepth;
982d83511ddSZequan Wu       bool UnnestEnd = EndDepth >= StartDepth;
983d83511ddSZequan Wu       if (UnnestEnd) {
9844544a63bSSterling Augustine         assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
9854544a63bSSterling Augustine                                       BeforeLoc));
986d83511ddSZequan Wu 
987d83511ddSZequan Wu         BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
988d83511ddSZequan Wu         assert(BeforeLoc.isValid());
989d83511ddSZequan Wu         EndDepth--;
990d83511ddSZequan Wu       }
991d83511ddSZequan Wu       if (UnnestStart) {
992*fc97a63dSSterling Augustine         assert(SM.isWrittenInSameFile(AfterLoc,
993*fc97a63dSSterling Augustine                                       getEndOfFileOrMacro(AfterLoc)));
994d83511ddSZequan Wu 
995d83511ddSZequan Wu         AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
996d83511ddSZequan Wu         assert(AfterLoc.isValid());
997d83511ddSZequan Wu         AfterLoc = getPreciseTokenLocEnd(AfterLoc);
998d83511ddSZequan Wu         assert(AfterLoc.isValid());
999d83511ddSZequan Wu         StartDepth--;
1000d83511ddSZequan Wu       }
1001d83511ddSZequan Wu     }
1002d83511ddSZequan Wu     AfterLoc = getPreciseTokenLocEnd(AfterLoc);
10039500a720SZequan Wu     // If the start and end locations of the gap are both within the same macro
10049500a720SZequan Wu     // file, the range may not be in source order.
10059500a720SZequan Wu     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
10069500a720SZequan Wu       return None;
1007fa8fa044SVedant Kumar     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
1008fa8fa044SVedant Kumar       return None;
1009fa8fa044SVedant Kumar     return {{AfterLoc, BeforeLoc}};
1010fa8fa044SVedant Kumar   }
1011fa8fa044SVedant Kumar 
10122e8c8759SVedant Kumar   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
10132e8c8759SVedant Kumar   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
10142e8c8759SVedant Kumar                             Counter Count) {
1015fa8fa044SVedant Kumar     if (StartLoc == EndLoc)
10162e8c8759SVedant Kumar       return;
1017fa8fa044SVedant Kumar     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
10182e8c8759SVedant Kumar     handleFileExit(StartLoc);
10192e8c8759SVedant Kumar     size_t Index = pushRegion(Count, StartLoc, EndLoc);
10202e8c8759SVedant Kumar     getRegion().setGap(true);
10212e8c8759SVedant Kumar     handleFileExit(EndLoc);
10222e8c8759SVedant Kumar     popRegions(Index);
10232e8c8759SVedant Kumar   }
10242e8c8759SVedant Kumar 
10259fc8faf9SAdrian Prantl   /// Keep counts of breaks and continues inside loops.
1026ee02499aSAlex Lorenz   struct BreakContinue {
1027ee02499aSAlex Lorenz     Counter BreakCount;
1028ee02499aSAlex Lorenz     Counter ContinueCount;
1029ee02499aSAlex Lorenz   };
1030ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
1031ee02499aSAlex Lorenz 
1032ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
1033ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
1034e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
1035ee02499aSAlex Lorenz       const LangOptions &LangOpts)
1036747b0e29SVedant Kumar       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
1037747b0e29SVedant Kumar         DeferredRegion(None) {}
1038ee02499aSAlex Lorenz 
10399fc8faf9SAdrian Prantl   /// Write the mapping data to the output stream
1040ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
1041ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
1042bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
1043fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
1044747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
1045fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
1046ee02499aSAlex Lorenz     gatherSkippedRegions();
1047ee02499aSAlex Lorenz 
1048efd319a2SVedant Kumar     if (MappingRegions.empty())
1049efd319a2SVedant Kumar       return;
1050efd319a2SVedant Kumar 
10514da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
10524da909b2SJustin Bogner                                  MappingRegions);
1053ee02499aSAlex Lorenz     Writer.write(OS);
1054ee02499aSAlex Lorenz   }
1055ee02499aSAlex Lorenz 
1056ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
1057f2ceec48SStephen Kelly     if (S->getBeginLoc().isValid())
1058bf42cfd7SJustin Bogner       extendRegion(S);
1059642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
1060642f173aSBenjamin Kramer       if (Child)
1061642f173aSBenjamin Kramer         this->Visit(Child);
1062bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
1063ee02499aSAlex Lorenz   }
1064ee02499aSAlex Lorenz 
1065ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
1066747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
1067747b0e29SVedant Kumar 
1068bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
1069efd319a2SVedant Kumar 
1070efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
1071efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1072efd319a2SVedant Kumar       return;
1073efd319a2SVedant Kumar 
10747225a261SVedant Kumar     // Do not visit the artificial children nodes of defaulted methods. The
10757225a261SVedant Kumar     // lexer may not be able to report back precise token end locations for
10767225a261SVedant Kumar     // these children nodes (llvm.org/PR39822), and moreover users will not be
10777225a261SVedant Kumar     // able to see coverage for them.
10787225a261SVedant Kumar     bool Defaulted = false;
10797225a261SVedant Kumar     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
10807225a261SVedant Kumar       Defaulted = Method->isDefaulted();
10817225a261SVedant Kumar 
10827225a261SVedant Kumar     propagateCounts(getRegionCounter(Body), Body,
10837225a261SVedant Kumar                     /*VisitChildren=*/!Defaulted);
1084747b0e29SVedant Kumar     assert(RegionStack.empty() && "Regions entered but never exited");
1085747b0e29SVedant Kumar 
108661763b65SVedant Kumar     // Discard the last uncompleted deferred region in a decl, if one exists.
108761763b65SVedant Kumar     // This prevents lines at the end of a function containing only whitespace
108861763b65SVedant Kumar     // or closing braces from being marked as uncovered.
1089ef8e05ffSVedant Kumar     DeferredRegion = None;
1090341bf429SVedant Kumar   }
1091ee02499aSAlex Lorenz 
1092ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
1093bf42cfd7SJustin Bogner     extendRegion(S);
1094ee02499aSAlex Lorenz     if (S->getRetValue())
1095ee02499aSAlex Lorenz       Visit(S->getRetValue());
1096bf42cfd7SJustin Bogner     terminateRegion(S);
1097ee02499aSAlex Lorenz   }
1098ee02499aSAlex Lorenz 
1099565e37c7SXun Li   void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1100565e37c7SXun Li     extendRegion(S);
1101565e37c7SXun Li     Visit(S->getBody());
1102565e37c7SXun Li   }
1103565e37c7SXun Li 
1104565e37c7SXun Li   void VisitCoreturnStmt(const CoreturnStmt *S) {
1105565e37c7SXun Li     extendRegion(S);
1106565e37c7SXun Li     if (S->getOperand())
1107565e37c7SXun Li       Visit(S->getOperand());
1108565e37c7SXun Li     terminateRegion(S);
1109565e37c7SXun Li   }
1110565e37c7SXun Li 
1111f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1112f959febfSJustin Bogner     extendRegion(E);
1113f959febfSJustin Bogner     if (E->getSubExpr())
1114f959febfSJustin Bogner       Visit(E->getSubExpr());
1115f959febfSJustin Bogner     terminateRegion(E);
1116f959febfSJustin Bogner   }
1117f959febfSJustin Bogner 
1118bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1119ee02499aSAlex Lorenz 
1120ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
11218046d22aSVedant Kumar     Counter LabelCount = getRegionCounter(S);
1122bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
11238046d22aSVedant Kumar     completeTopLevelDeferredRegion(LabelCount, Start);
1124d781d97eSVedant Kumar     completeDeferred(LabelCount, Start);
1125bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
1126bf42cfd7SJustin Bogner     handleFileExit(Start);
11278046d22aSVedant Kumar     pushRegion(LabelCount, Start);
1128ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1129ee02499aSAlex Lorenz   }
1130ee02499aSAlex Lorenz 
1131ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
1132ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1133ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
1134bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
11357f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
11367f53fbfcSEli Friedman     // case statements, not just the most recent one.
1137bf42cfd7SJustin Bogner     terminateRegion(S);
1138ee02499aSAlex Lorenz   }
1139ee02499aSAlex Lorenz 
1140ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
1141ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1142ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
1143bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1144bf42cfd7SJustin Bogner     terminateRegion(S);
1145ee02499aSAlex Lorenz   }
1146ee02499aSAlex Lorenz 
1147181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
1148181dfe4cSEli Friedman     VisitStmt(E);
1149181dfe4cSEli Friedman 
1150181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
1151181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
1152181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
1153181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
1154181dfe4cSEli Friedman       terminateRegion(E);
1155181dfe4cSEli Friedman   }
1156181dfe4cSEli Friedman 
1157ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
1158bf42cfd7SJustin Bogner     extendRegion(S);
1159ee02499aSAlex Lorenz 
1160bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1161bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1162bf42cfd7SJustin Bogner 
1163bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
1164bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
1165bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1166bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1167ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1168bf42cfd7SJustin Bogner 
1169bf42cfd7SJustin Bogner     // Go back to handle the condition.
1170bf42cfd7SJustin Bogner     Counter CondCount =
1171bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1172bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1173bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
1174bf42cfd7SJustin Bogner 
1175fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1176d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1177fa8fa044SVedant Kumar     if (Gap)
1178fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1179fa8fa044SVedant Kumar 
1180bf42cfd7SJustin Bogner     Counter OutCount =
1181bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1182bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1183bf42cfd7SJustin Bogner       pushRegion(OutCount);
11849f2967bcSAlan Phipps 
11859f2967bcSAlan Phipps     // Create Branch Region around condition.
11869f2967bcSAlan Phipps     createBranchRegion(S->getCond(), BodyCount,
11879f2967bcSAlan Phipps                        subtractCounters(CondCount, BodyCount));
1188ee02499aSAlex Lorenz   }
1189ee02499aSAlex Lorenz 
1190ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
1191bf42cfd7SJustin Bogner     extendRegion(S);
1192ee02499aSAlex Lorenz 
1193bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1194bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1195bf42cfd7SJustin Bogner 
1196bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
1197bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1198bf42cfd7SJustin Bogner     Counter BackedgeCount =
1199bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1200ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1201bf42cfd7SJustin Bogner 
1202bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1203bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
1204bf42cfd7SJustin Bogner 
1205bf42cfd7SJustin Bogner     Counter OutCount =
1206bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1207bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1208bf42cfd7SJustin Bogner       pushRegion(OutCount);
12099f2967bcSAlan Phipps 
12109f2967bcSAlan Phipps     // Create Branch Region around condition.
12119f2967bcSAlan Phipps     createBranchRegion(S->getCond(), BodyCount,
12129f2967bcSAlan Phipps                        subtractCounters(CondCount, BodyCount));
1213ee02499aSAlex Lorenz   }
1214ee02499aSAlex Lorenz 
1215ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
1216bf42cfd7SJustin Bogner     extendRegion(S);
1217ee02499aSAlex Lorenz     if (S->getInit())
1218ee02499aSAlex Lorenz       Visit(S->getInit());
1219ee02499aSAlex Lorenz 
1220bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1221bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1222bf42cfd7SJustin Bogner 
12233e2ae49aSVedant Kumar     // The loop increment may contain a break or continue.
12243e2ae49aSVedant Kumar     if (S->getInc())
12253e2ae49aSVedant Kumar       BreakContinueStack.emplace_back();
12263e2ae49aSVedant Kumar 
1227bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
12283e2ae49aSVedant Kumar     BreakContinueStack.emplace_back();
1229bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1230bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
12313e2ae49aSVedant Kumar     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1232ee02499aSAlex Lorenz 
1233ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
1234ee02499aSAlex Lorenz     // the count for all the continue statements.
12353e2ae49aSVedant Kumar     BreakContinue IncrementBC;
12363e2ae49aSVedant Kumar     if (const Stmt *Inc = S->getInc()) {
12373e2ae49aSVedant Kumar       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
12383e2ae49aSVedant Kumar       IncrementBC = BreakContinueStack.pop_back_val();
12393e2ae49aSVedant Kumar     }
1240bf42cfd7SJustin Bogner 
1241bf42cfd7SJustin Bogner     // Go back to handle the condition.
12423e2ae49aSVedant Kumar     Counter CondCount = addCounters(
12433e2ae49aSVedant Kumar         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
12443e2ae49aSVedant Kumar         IncrementBC.ContinueCount);
1245bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
1246bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
1247bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
1248ee02499aSAlex Lorenz     }
1249ee02499aSAlex Lorenz 
1250fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1251d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1252fa8fa044SVedant Kumar     if (Gap)
1253fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1254fa8fa044SVedant Kumar 
12553e2ae49aSVedant Kumar     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
12563e2ae49aSVedant Kumar                                    subtractCounters(CondCount, BodyCount));
1257bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1258bf42cfd7SJustin Bogner       pushRegion(OutCount);
12599f2967bcSAlan Phipps 
12609f2967bcSAlan Phipps     // Create Branch Region around condition.
12619f2967bcSAlan Phipps     createBranchRegion(S->getCond(), BodyCount,
12629f2967bcSAlan Phipps                        subtractCounters(CondCount, BodyCount));
1263ee02499aSAlex Lorenz   }
1264ee02499aSAlex Lorenz 
1265ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1266bf42cfd7SJustin Bogner     extendRegion(S);
12678baa5001SRichard Smith     if (S->getInit())
12688baa5001SRichard Smith       Visit(S->getInit());
1269bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
1270ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
1271bf42cfd7SJustin Bogner 
1272bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1273bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1274bf42cfd7SJustin Bogner 
1275ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1276bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1277bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1278ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1279bf42cfd7SJustin Bogner 
1280fa8fa044SVedant Kumar     // The body count applies to the area immediately after the range.
1281d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1282fa8fa044SVedant Kumar     if (Gap)
1283fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1284fa8fa044SVedant Kumar 
12851587432dSJustin Bogner     Counter LoopCount =
12861587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
12871587432dSJustin Bogner     Counter OutCount =
12881587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1289bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1290bf42cfd7SJustin Bogner       pushRegion(OutCount);
12919f2967bcSAlan Phipps 
12929f2967bcSAlan Phipps     // Create Branch Region around condition.
12939f2967bcSAlan Phipps     createBranchRegion(S->getCond(), BodyCount,
12949f2967bcSAlan Phipps                        subtractCounters(LoopCount, BodyCount));
1295ee02499aSAlex Lorenz   }
1296ee02499aSAlex Lorenz 
1297ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1298bf42cfd7SJustin Bogner     extendRegion(S);
1299ee02499aSAlex Lorenz     Visit(S->getElement());
1300bf42cfd7SJustin Bogner 
1301bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1302bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1303bf42cfd7SJustin Bogner 
1304ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1305bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1306bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1307ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1308bf42cfd7SJustin Bogner 
1309fa8fa044SVedant Kumar     // The body count applies to the area immediately after the collection.
1310d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1311fa8fa044SVedant Kumar     if (Gap)
1312fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1313fa8fa044SVedant Kumar 
13141587432dSJustin Bogner     Counter LoopCount =
13151587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
13161587432dSJustin Bogner     Counter OutCount =
13171587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1318bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1319bf42cfd7SJustin Bogner       pushRegion(OutCount);
1320ee02499aSAlex Lorenz   }
1321ee02499aSAlex Lorenz 
1322ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
1323bf42cfd7SJustin Bogner     extendRegion(S);
1324f2a6ec55SVedant Kumar     if (S->getInit())
1325f2a6ec55SVedant Kumar       Visit(S->getInit());
1326ee02499aSAlex Lorenz     Visit(S->getCond());
1327bf42cfd7SJustin Bogner 
1328ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1329bf42cfd7SJustin Bogner 
1330bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
1331bf42cfd7SJustin Bogner     extendRegion(Body);
1332bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1333bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
13347f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
13357f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
13367f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
1337859bf4d2SVedant Kumar         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1338859bf4d2SVedant Kumar         getRegion().setGap(true);
1339b5841332SRichard Trieu         for (const auto *Child : CS->children())
1340bf42cfd7SJustin Bogner           Visit(Child);
13417f53fbfcSEli Friedman 
13427f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
13437f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
13447f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
13457f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
13467f53fbfcSEli Friedman         }
13477f53fbfcSEli Friedman 
1348bf42cfd7SJustin Bogner         popRegions(Index);
1349ee02499aSAlex Lorenz       }
135087ea3b05SVedant Kumar     } else
1351bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
1352ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1353bf42cfd7SJustin Bogner 
1354ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
1355ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
1356ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1357bf42cfd7SJustin Bogner 
13589f2967bcSAlan Phipps     Counter ParentCount = getRegion().getCounter();
1359bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
13603836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
136108780529SAlex Lorenz     pushRegion(ExitCount);
136208780529SAlex Lorenz 
136308780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
136408780529SAlex Lorenz     // in a different file.
136508780529SAlex Lorenz     MostRecentLocation = getStart(S);
13663836482aSVedant Kumar     handleFileExit(ExitLoc);
13679f2967bcSAlan Phipps 
13689f2967bcSAlan Phipps     // Create a Branch Region around each Case. Subtract the case's
13699f2967bcSAlan Phipps     // counter from the Parent counter to track the "False" branch count.
13709f2967bcSAlan Phipps     Counter CaseCountSum;
13719f2967bcSAlan Phipps     bool HasDefaultCase = false;
13729f2967bcSAlan Phipps     const SwitchCase *Case = S->getSwitchCaseList();
13739f2967bcSAlan Phipps     for (; Case; Case = Case->getNextSwitchCase()) {
13749f2967bcSAlan Phipps       HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
13759f2967bcSAlan Phipps       CaseCountSum = addCounters(CaseCountSum, getRegionCounter(Case));
13769f2967bcSAlan Phipps       createSwitchCaseRegion(
13779f2967bcSAlan Phipps           Case, getRegionCounter(Case),
13789f2967bcSAlan Phipps           subtractCounters(ParentCount, getRegionCounter(Case)));
13799f2967bcSAlan Phipps     }
13809f2967bcSAlan Phipps 
13819f2967bcSAlan Phipps     // If no explicit default case exists, create a branch region to represent
13829f2967bcSAlan Phipps     // the hidden branch, which will be added later by the CodeGen. This region
13839f2967bcSAlan Phipps     // will be associated with the switch statement's condition.
13849f2967bcSAlan Phipps     if (!HasDefaultCase) {
13859f2967bcSAlan Phipps       Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
13869f2967bcSAlan Phipps       Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
13879f2967bcSAlan Phipps       createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
13889f2967bcSAlan Phipps     }
1389ee02499aSAlex Lorenz   }
1390ee02499aSAlex Lorenz 
1391bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
1392bf42cfd7SJustin Bogner     extendRegion(S);
1393ee02499aSAlex Lorenz 
1394bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
1395bf42cfd7SJustin Bogner 
1396bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1397bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
1398bf42cfd7SJustin Bogner     // the first case in a switch.
1399a6e4358fSStephen Kelly     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1400bf42cfd7SJustin Bogner       Parent.setCounter(Count);
1401bf42cfd7SJustin Bogner     else
1402bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
1403bf42cfd7SJustin Bogner 
1404376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1405bf42cfd7SJustin Bogner       Visit(CS->getLHS());
1406bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
1407bf42cfd7SJustin Bogner         Visit(RHS);
1408bf42cfd7SJustin Bogner     }
1409ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1410ee02499aSAlex Lorenz   }
1411ee02499aSAlex Lorenz 
1412ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
1413bf42cfd7SJustin Bogner     extendRegion(S);
14149d2a16b9SVedant Kumar     if (S->getInit())
14159d2a16b9SVedant Kumar       Visit(S->getInit());
14169d2a16b9SVedant Kumar 
1417055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
1418055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
1419055ebc34SJustin Bogner     extendRegion(S->getCond());
1420ee02499aSAlex Lorenz 
1421bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1422bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
1423ee02499aSAlex Lorenz 
142491f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
142591f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
142691f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
142791f2e3c9SJustin Bogner 
14282e8c8759SVedant Kumar     // The 'then' count applies to the area immediately after the condition.
1429d83511ddSZequan Wu     auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
1430fa8fa044SVedant Kumar     if (Gap)
1431fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
14322e8c8759SVedant Kumar 
1433bf42cfd7SJustin Bogner     extendRegion(S->getThen());
1434bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1435bf42cfd7SJustin Bogner 
1436bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1437bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
14382e8c8759SVedant Kumar       // The 'else' count applies to the area immediately after the 'then'.
1439d83511ddSZequan Wu       Gap = findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
1440fa8fa044SVedant Kumar       if (Gap)
1441fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
14422e8c8759SVedant Kumar       extendRegion(Else);
1443bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1444bf42cfd7SJustin Bogner     } else
1445bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
1446bf42cfd7SJustin Bogner 
1447bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1448bf42cfd7SJustin Bogner       pushRegion(OutCount);
14499f2967bcSAlan Phipps 
14509f2967bcSAlan Phipps     // Create Branch Region around condition.
14519f2967bcSAlan Phipps     createBranchRegion(S->getCond(), ThenCount,
14529f2967bcSAlan Phipps                        subtractCounters(ParentCount, ThenCount));
1453ee02499aSAlex Lorenz   }
1454ee02499aSAlex Lorenz 
1455ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
1456bf42cfd7SJustin Bogner     extendRegion(S);
1457049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
1458049908b2SVedant Kumar     extendRegion(S->getTryBlock());
1459049908b2SVedant Kumar 
1460049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
1461049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
1462049908b2SVedant Kumar 
1463ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1464ee02499aSAlex Lorenz       Visit(S->getHandler(I));
1465bf42cfd7SJustin Bogner 
1466bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
1467bf42cfd7SJustin Bogner     pushRegion(ExitCount);
1468ee02499aSAlex Lorenz   }
1469ee02499aSAlex Lorenz 
1470ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1471bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1472ee02499aSAlex Lorenz   }
1473ee02499aSAlex Lorenz 
1474ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1475bf42cfd7SJustin Bogner     extendRegion(E);
1476ee02499aSAlex Lorenz 
1477bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1478bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
1479ee02499aSAlex Lorenz 
14804dc08cc3SZequan Wu     propagateCounts(ParentCount, E->getCond());
1481e3654ce7SJustin Bogner 
1482e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
14832e8c8759SVedant Kumar       // The 'then' count applies to the area immediately after the condition.
1484fa8fa044SVedant Kumar       auto Gap =
1485fa8fa044SVedant Kumar           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1486fa8fa044SVedant Kumar       if (Gap)
1487fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
14882e8c8759SVedant Kumar 
1489e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
1490bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
1491e3654ce7SJustin Bogner     }
14922e8c8759SVedant Kumar 
1493e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
1494bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
1495bf42cfd7SJustin Bogner                     E->getFalseExpr());
14969f2967bcSAlan Phipps 
14979f2967bcSAlan Phipps     // Create Branch Region around condition.
14989f2967bcSAlan Phipps     createBranchRegion(E->getCond(), TrueCount,
14999f2967bcSAlan Phipps                        subtractCounters(ParentCount, TrueCount));
1500ee02499aSAlex Lorenz   }
1501ee02499aSAlex Lorenz 
1502ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
1503e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1504e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1505e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1506bf42cfd7SJustin Bogner 
15079f2967bcSAlan Phipps     // Counter tracks the right hand side of a logical and operator.
1508bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1509bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
15109f2967bcSAlan Phipps 
15119f2967bcSAlan Phipps     // Extract the RHS's Execution Counter.
15129f2967bcSAlan Phipps     Counter RHSExecCnt = getRegionCounter(E);
15139f2967bcSAlan Phipps 
15149f2967bcSAlan Phipps     // Extract the RHS's "True" Instance Counter.
15159f2967bcSAlan Phipps     Counter RHSTrueCnt = getRegionCounter(E->getRHS());
15169f2967bcSAlan Phipps 
15179f2967bcSAlan Phipps     // Extract the Parent Region Counter.
15189f2967bcSAlan Phipps     Counter ParentCnt = getRegion().getCounter();
15199f2967bcSAlan Phipps 
15209f2967bcSAlan Phipps     // Create Branch Region around LHS condition.
15219f2967bcSAlan Phipps     createBranchRegion(E->getLHS(), RHSExecCnt,
15229f2967bcSAlan Phipps                        subtractCounters(ParentCnt, RHSExecCnt));
15239f2967bcSAlan Phipps 
15249f2967bcSAlan Phipps     // Create Branch Region around RHS condition.
15259f2967bcSAlan Phipps     createBranchRegion(E->getRHS(), RHSTrueCnt,
15269f2967bcSAlan Phipps                        subtractCounters(RHSExecCnt, RHSTrueCnt));
1527ee02499aSAlex Lorenz   }
1528ee02499aSAlex Lorenz 
1529ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
1530e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1531e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1532e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1533ee02499aSAlex Lorenz 
15349f2967bcSAlan Phipps     // Counter tracks the right hand side of a logical or operator.
1535bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1536bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
15379f2967bcSAlan Phipps 
15389f2967bcSAlan Phipps     // Extract the RHS's Execution Counter.
15399f2967bcSAlan Phipps     Counter RHSExecCnt = getRegionCounter(E);
15409f2967bcSAlan Phipps 
15419f2967bcSAlan Phipps     // Extract the RHS's "False" Instance Counter.
15429f2967bcSAlan Phipps     Counter RHSFalseCnt = getRegionCounter(E->getRHS());
15439f2967bcSAlan Phipps 
15449f2967bcSAlan Phipps     // Extract the Parent Region Counter.
15459f2967bcSAlan Phipps     Counter ParentCnt = getRegion().getCounter();
15469f2967bcSAlan Phipps 
15479f2967bcSAlan Phipps     // Create Branch Region around LHS condition.
15489f2967bcSAlan Phipps     createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
15499f2967bcSAlan Phipps                        RHSExecCnt);
15509f2967bcSAlan Phipps 
15519f2967bcSAlan Phipps     // Create Branch Region around RHS condition.
15529f2967bcSAlan Phipps     createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
15539f2967bcSAlan Phipps                        RHSFalseCnt);
155401a0d062SAlex Lorenz   }
1555c109102eSJustin Bogner 
1556c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
1557c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
1558c109102eSJustin Bogner     // propagate counts into them.
1559c109102eSJustin Bogner   }
1560ee02499aSAlex Lorenz };
1561ee02499aSAlex Lorenz 
156214f8fb68SVedant Kumar } // end anonymous namespace
156314f8fb68SVedant Kumar 
1564a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1565a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1566a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1567a432d176SJustin Bogner   OS << FunctionName << ":\n";
1568a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1569a432d176SJustin Bogner   for (const auto &R : Regions) {
1570f2cf38e0SAlex Lorenz     OS.indent(2);
1571f2cf38e0SAlex Lorenz     switch (R.Kind) {
1572f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1573f2cf38e0SAlex Lorenz       break;
1574f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1575f2cf38e0SAlex Lorenz       OS << "Expansion,";
1576f2cf38e0SAlex Lorenz       break;
1577f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1578f2cf38e0SAlex Lorenz       OS << "Skipped,";
1579f2cf38e0SAlex Lorenz       break;
1580a1c4deb7SVedant Kumar     case CounterMappingRegion::GapRegion:
1581a1c4deb7SVedant Kumar       OS << "Gap,";
1582a1c4deb7SVedant Kumar       break;
15839f2967bcSAlan Phipps     case CounterMappingRegion::BranchRegion:
15849f2967bcSAlan Phipps       OS << "Branch,";
15859f2967bcSAlan Phipps       break;
1586f2cf38e0SAlex Lorenz     }
1587f2cf38e0SAlex Lorenz 
15884da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
15894da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1590f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
15919f2967bcSAlan Phipps 
15929f2967bcSAlan Phipps     if (R.Kind == CounterMappingRegion::BranchRegion) {
15939f2967bcSAlan Phipps       OS << ", ";
15949f2967bcSAlan Phipps       Ctx.dump(R.FalseCount, OS);
15959f2967bcSAlan Phipps     }
15969f2967bcSAlan Phipps 
1597f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
15984da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
15994da909b2SJustin Bogner     OS << "\n";
1600f2cf38e0SAlex Lorenz   }
1601f2cf38e0SAlex Lorenz }
1602f2cf38e0SAlex Lorenz 
1603c3324450SKeith Smiley CoverageMappingModuleGen::CoverageMappingModuleGen(
1604c3324450SKeith Smiley     CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
1605c3324450SKeith Smiley     : CGM(CGM), SourceInfo(SourceInfo) {
1606c3324450SKeith Smiley   ProfilePrefixMap = CGM.getCodeGenOpts().ProfilePrefixMap;
1607c3324450SKeith Smiley }
1608c3324450SKeith Smiley 
1609c3324450SKeith Smiley std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
1610c3324450SKeith Smiley   llvm::SmallString<256> Path(Filename);
1611fbf8b957SPetr Hosek   llvm::sys::fs::make_absolute(Path);
1612c3324450SKeith Smiley   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1613c3324450SKeith Smiley   for (const auto &Entry : ProfilePrefixMap) {
1614c3324450SKeith Smiley     if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second))
1615c3324450SKeith Smiley       break;
1616c3324450SKeith Smiley   }
1617c3324450SKeith Smiley   return Path.str().str();
1618c3324450SKeith Smiley }
1619c3324450SKeith Smiley 
1620dd1ea9deSVedant Kumar static std::string getInstrProfSection(const CodeGenModule &CGM,
1621dd1ea9deSVedant Kumar                                        llvm::InstrProfSectKind SK) {
1622dd1ea9deSVedant Kumar   return llvm::getInstrProfSectionName(
1623dd1ea9deSVedant Kumar       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1624dd1ea9deSVedant Kumar }
1625dd1ea9deSVedant Kumar 
1626dd1ea9deSVedant Kumar void CoverageMappingModuleGen::emitFunctionMappingRecord(
1627dd1ea9deSVedant Kumar     const FunctionInfo &Info, uint64_t FilenamesRef) {
162899317124SVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1629dd1ea9deSVedant Kumar 
1630dd1ea9deSVedant Kumar   // Assign a name to the function record. This is used to merge duplicates.
1631dd1ea9deSVedant Kumar   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1632dd1ea9deSVedant Kumar 
1633dd1ea9deSVedant Kumar   // A dummy description for a function included-but-not-used in a TU can be
1634dd1ea9deSVedant Kumar   // replaced by full description provided by a different TU. The two kinds of
1635dd1ea9deSVedant Kumar   // descriptions play distinct roles: therefore, assign them different names
1636dd1ea9deSVedant Kumar   // to prevent `linkonce_odr` merging.
1637dd1ea9deSVedant Kumar   if (Info.IsUsed)
1638dd1ea9deSVedant Kumar     FuncRecordName += "u";
1639dd1ea9deSVedant Kumar 
1640dd1ea9deSVedant Kumar   // Create the function record type.
1641dd1ea9deSVedant Kumar   const uint64_t NameHash = Info.NameHash;
1642dd1ea9deSVedant Kumar   const uint64_t FuncHash = Info.FuncHash;
1643dd1ea9deSVedant Kumar   const std::string &CoverageMapping = Info.CoverageMapping;
164433888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
164533888717SVedant Kumar   llvm::Type *FunctionRecordTypes[] = {
164633888717SVedant Kumar #include "llvm/ProfileData/InstrProfData.inc"
164733888717SVedant Kumar   };
1648dd1ea9deSVedant Kumar   auto *FunctionRecordTy =
164933888717SVedant Kumar       llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
165033888717SVedant Kumar                             /*isPacked=*/true);
165199317124SVedant Kumar 
1652dd1ea9deSVedant Kumar   // Create the function record constant.
165333888717SVedant Kumar #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
165433888717SVedant Kumar   llvm::Constant *FunctionRecordVals[] = {
165533888717SVedant Kumar       #include "llvm/ProfileData/InstrProfData.inc"
165633888717SVedant Kumar   };
1657dd1ea9deSVedant Kumar   auto *FuncRecordConstant = llvm::ConstantStruct::get(
1658dd1ea9deSVedant Kumar       FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1659dd1ea9deSVedant Kumar 
1660dd1ea9deSVedant Kumar   // Create the function record global.
1661dd1ea9deSVedant Kumar   auto *FuncRecord = new llvm::GlobalVariable(
1662dd1ea9deSVedant Kumar       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1663dd1ea9deSVedant Kumar       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1664dd1ea9deSVedant Kumar       FuncRecordName);
1665dd1ea9deSVedant Kumar   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1666dd1ea9deSVedant Kumar   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1667dd1ea9deSVedant Kumar   FuncRecord->setAlignment(llvm::Align(8));
1668dd1ea9deSVedant Kumar   if (CGM.supportsCOMDAT())
1669dd1ea9deSVedant Kumar     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1670dd1ea9deSVedant Kumar 
1671dd1ea9deSVedant Kumar   // Make sure the data doesn't get deleted.
1672dd1ea9deSVedant Kumar   CGM.addUsedGlobal(FuncRecord);
1673dd1ea9deSVedant Kumar }
1674dd1ea9deSVedant Kumar 
1675dd1ea9deSVedant Kumar void CoverageMappingModuleGen::addFunctionMappingRecord(
1676dd1ea9deSVedant Kumar     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1677dd1ea9deSVedant Kumar     const std::string &CoverageMapping, bool IsUsed) {
1678dd1ea9deSVedant Kumar   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1679dd1ea9deSVedant Kumar   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1680dd1ea9deSVedant Kumar   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1681dd1ea9deSVedant Kumar 
1682848da137SXinliang David Li   if (!IsUsed)
16832129ae53SXinliang David Li     FunctionNames.push_back(
16842129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1685f2cf38e0SAlex Lorenz 
1686f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1687f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1688f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1689f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1690f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1691f2cf38e0SAlex Lorenz     // expressions.
1692f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1693f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1694f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1695fbf8b957SPetr Hosek     llvm::SmallVector<std::string, 16> FilenameStrs;
1696fbf8b957SPetr Hosek     llvm::SmallVector<StringRef, 16> FilenameRefs;
1697fbf8b957SPetr Hosek     FilenameStrs.resize(FileEntries.size());
1698fbf8b957SPetr Hosek     FilenameRefs.resize(FileEntries.size());
1699b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1700b31ee819SJordan Rose       auto I = Entry.second;
1701b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1702fbf8b957SPetr Hosek       FilenameRefs[I] = FilenameStrs[I];
1703b31ee819SJordan Rose     }
1704a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1705a432d176SJustin Bogner                                     Expressions, Regions);
1706a432d176SJustin Bogner     if (Reader.read())
1707f2cf38e0SAlex Lorenz       return;
1708a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1709f2cf38e0SAlex Lorenz   }
1710ee02499aSAlex Lorenz }
1711ee02499aSAlex Lorenz 
1712ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1713ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1714ee02499aSAlex Lorenz     return;
1715ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1716ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1717ee02499aSAlex Lorenz 
1718ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1719ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
1720fbf8b957SPetr Hosek   llvm::SmallVector<StringRef, 16> FilenameRefs;
1721fbf8b957SPetr Hosek   FilenameStrs.resize(FileEntries.size());
1722fbf8b957SPetr Hosek   FilenameRefs.resize(FileEntries.size());
1723ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1724ee02499aSAlex Lorenz     auto I = Entry.second;
172514f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1726fbf8b957SPetr Hosek     FilenameRefs[I] = FilenameStrs[I];
1727ee02499aSAlex Lorenz   }
1728ee02499aSAlex Lorenz 
1729dd1ea9deSVedant Kumar   std::string Filenames;
1730dd1ea9deSVedant Kumar   {
1731dd1ea9deSVedant Kumar     llvm::raw_string_ostream OS(Filenames);
1732fbf8b957SPetr Hosek     CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
17334cd07dbeSSerge Guelton   }
1734dd1ea9deSVedant Kumar   auto *FilenamesVal =
1735dd1ea9deSVedant Kumar       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1736dd1ea9deSVedant Kumar   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
17374cd07dbeSSerge Guelton 
1738dd1ea9deSVedant Kumar   // Emit the function records.
1739dd1ea9deSVedant Kumar   for (const FunctionInfo &Info : FunctionRecords)
1740dd1ea9deSVedant Kumar     emitFunctionMappingRecord(Info, FilenamesRef);
1741ee02499aSAlex Lorenz 
1742dd1ea9deSVedant Kumar   const unsigned NRecords = 0;
1743dd1ea9deSVedant Kumar   const size_t FilenamesSize = Filenames.size();
1744dd1ea9deSVedant Kumar   const unsigned CoverageMappingSize = 0;
174520b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
174620b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
174720b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
174820b188c0SXinliang David Li   };
174920b188c0SXinliang David Li   auto CovDataHeaderTy =
175020b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
175120b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
175220b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
175320b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
175420b188c0SXinliang David Li   };
175520b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
175620b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
175720b188c0SXinliang David Li 
1758ee02499aSAlex Lorenz   // Create the coverage data record
1759dd1ea9deSVedant Kumar   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1760ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1761dd1ea9deSVedant Kumar   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1762ee02499aSAlex Lorenz   auto CovDataVal =
1763ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
176420b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
1765dd1ea9deSVedant Kumar       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
176620b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1767ee02499aSAlex Lorenz 
1768dd1ea9deSVedant Kumar   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1769c79099e0SGuillaume Chatelet   CovData->setAlignment(llvm::Align(8));
1770ee02499aSAlex Lorenz 
1771ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1772ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
17732129ae53SXinliang David Li   // Create the deferred function records array
17742129ae53SXinliang David Li   if (!FunctionNames.empty()) {
17752129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
17762129ae53SXinliang David Li                                            FunctionNames.size());
17772129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
17782129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
17792129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
17802129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
17812129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
17827077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
17832129ae53SXinliang David Li   }
1784ee02499aSAlex Lorenz }
1785ee02499aSAlex Lorenz 
1786ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1787ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1788ee02499aSAlex Lorenz   if (It != FileEntries.end())
1789ee02499aSAlex Lorenz     return It->second;
1790fbf8b957SPetr Hosek   unsigned FileID = FileEntries.size();
1791ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1792ee02499aSAlex Lorenz   return FileID;
1793ee02499aSAlex Lorenz }
1794ee02499aSAlex Lorenz 
1795ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1796ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1797ee02499aSAlex Lorenz   assert(CounterMap);
1798e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1799ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1800ee02499aSAlex Lorenz   Walker.write(OS);
1801ee02499aSAlex Lorenz }
1802ee02499aSAlex Lorenz 
1803ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1804ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1805ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1806ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1807ee02499aSAlex Lorenz   Walker.write(OS);
1808ee02499aSAlex Lorenz }
1809