1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2ee02499aSAlex Lorenz //
3ee02499aSAlex Lorenz //                     The LLVM Compiler Infrastructure
4ee02499aSAlex Lorenz //
5ee02499aSAlex Lorenz // This file is distributed under the University of Illinois Open Source
6ee02499aSAlex Lorenz // License. See LICENSE.TXT for details.
7ee02499aSAlex Lorenz //
8ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
9ee02499aSAlex Lorenz //
10ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator
11ee02499aSAlex Lorenz //
12ee02499aSAlex Lorenz //===----------------------------------------------------------------------===//
13ee02499aSAlex Lorenz 
14ee02499aSAlex Lorenz #include "CoverageMappingGen.h"
15ee02499aSAlex Lorenz #include "CodeGenFunction.h"
16ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h"
17ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h"
18bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h"
19ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h"
20bf42cfd7SJustin Bogner #include "llvm/ADT/Optional.h"
21b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h"
22b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
240d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
25ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
2614f8fb68SVedant Kumar #include "llvm/Support/Path.h"
27ee02499aSAlex Lorenz 
28ee02499aSAlex Lorenz using namespace clang;
29ee02499aSAlex Lorenz using namespace CodeGen;
30ee02499aSAlex Lorenz using namespace llvm::coverage;
31ee02499aSAlex Lorenz 
323919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
33ee02499aSAlex Lorenz   SkippedRanges.push_back(Range);
34ee02499aSAlex Lorenz }
35ee02499aSAlex Lorenz 
36ee02499aSAlex Lorenz namespace {
37ee02499aSAlex Lorenz 
38ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter.
3909c7179bSJustin Bogner class SourceMappingRegion {
40ee02499aSAlex Lorenz   Counter Count;
41ee02499aSAlex Lorenz 
42ee02499aSAlex Lorenz   /// \brief The region's starting location.
43bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
44ee02499aSAlex Lorenz 
45ee02499aSAlex Lorenz   /// \brief The region's ending location.
46bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
47ee02499aSAlex Lorenz 
48747b0e29SVedant Kumar   /// Whether this region should be emitted after its parent is emitted.
49747b0e29SVedant Kumar   bool DeferRegion;
50747b0e29SVedant Kumar 
51a1c4deb7SVedant Kumar   /// Whether this region is a gap region. The count from a gap region is set
52a1c4deb7SVedant Kumar   /// as the line execution count if there are no other regions on the line.
53a1c4deb7SVedant Kumar   bool GapRegion;
54a1c4deb7SVedant Kumar 
5509c7179bSJustin Bogner public:
56bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
57a1c4deb7SVedant Kumar                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
58a1c4deb7SVedant Kumar                       bool GapRegion = false)
59747b0e29SVedant Kumar       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
60a1c4deb7SVedant Kumar         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
61ee02499aSAlex Lorenz 
6209c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
6309c7179bSJustin Bogner 
64bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
6509c7179bSJustin Bogner 
66bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
67bf42cfd7SJustin Bogner 
68bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
69bf42cfd7SJustin Bogner 
70462c77b4SCraig Topper   SourceLocation getStartLoc() const {
71bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
72bf42cfd7SJustin Bogner     return *LocStart;
7309c7179bSJustin Bogner   }
7409c7179bSJustin Bogner 
75bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
76ee02499aSAlex Lorenz 
77bf42cfd7SJustin Bogner   void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
78ee02499aSAlex Lorenz 
79462c77b4SCraig Topper   SourceLocation getEndLoc() const {
80bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
81bf42cfd7SJustin Bogner     return *LocEnd;
82ee02499aSAlex Lorenz   }
83747b0e29SVedant Kumar 
84747b0e29SVedant Kumar   bool isDeferred() const { return DeferRegion; }
85747b0e29SVedant Kumar 
86747b0e29SVedant Kumar   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
87a1c4deb7SVedant Kumar 
88a1c4deb7SVedant Kumar   bool isGap() const { return GapRegion; }
89a1c4deb7SVedant Kumar 
90a1c4deb7SVedant Kumar   void setGap(bool Gap) { GapRegion = Gap; }
91ee02499aSAlex Lorenz };
92ee02499aSAlex Lorenz 
93d7369648SVedant Kumar /// Spelling locations for the start and end of a source region.
94d7369648SVedant Kumar struct SpellingRegion {
95d7369648SVedant Kumar   /// The line where the region starts.
96d7369648SVedant Kumar   unsigned LineStart;
97d7369648SVedant Kumar 
98d7369648SVedant Kumar   /// The column where the region starts.
99d7369648SVedant Kumar   unsigned ColumnStart;
100d7369648SVedant Kumar 
101d7369648SVedant Kumar   /// The line where the region ends.
102d7369648SVedant Kumar   unsigned LineEnd;
103d7369648SVedant Kumar 
104d7369648SVedant Kumar   /// The column where the region ends.
105d7369648SVedant Kumar   unsigned ColumnEnd;
106d7369648SVedant Kumar 
107d7369648SVedant Kumar   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
108d7369648SVedant Kumar                  SourceLocation LocEnd) {
109d7369648SVedant Kumar     LineStart = SM.getSpellingLineNumber(LocStart);
110d7369648SVedant Kumar     ColumnStart = SM.getSpellingColumnNumber(LocStart);
111d7369648SVedant Kumar     LineEnd = SM.getSpellingLineNumber(LocEnd);
112d7369648SVedant Kumar     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
113d7369648SVedant Kumar   }
114d7369648SVedant Kumar 
115*fa8fa044SVedant Kumar   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
116*fa8fa044SVedant Kumar       : SpellingRegion(SM, R.getStartLoc(), R.getEndLoc()) {}
117*fa8fa044SVedant Kumar 
118d7369648SVedant Kumar   /// Check if the start and end locations appear in source order, i.e
119d7369648SVedant Kumar   /// top->bottom, left->right.
120d7369648SVedant Kumar   bool isInSourceOrder() const {
121d7369648SVedant Kumar     return (LineStart < LineEnd) ||
122d7369648SVedant Kumar            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
123d7369648SVedant Kumar   }
124d7369648SVedant Kumar };
125d7369648SVedant Kumar 
126ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different
127ee02499aSAlex Lorenz /// coverage mapping region builders.
128ee02499aSAlex Lorenz class CoverageMappingBuilder {
129ee02499aSAlex Lorenz public:
130ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
131ee02499aSAlex Lorenz   SourceManager &SM;
132ee02499aSAlex Lorenz   const LangOptions &LangOpts;
133ee02499aSAlex Lorenz 
134ee02499aSAlex Lorenz private:
135bf42cfd7SJustin Bogner   /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
136bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
137bf42cfd7SJustin Bogner       FileIDMapping;
138ee02499aSAlex Lorenz 
139ee02499aSAlex Lorenz public:
140ee02499aSAlex Lorenz   /// \brief The coverage mapping regions for this function
141ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
142ee02499aSAlex Lorenz   /// \brief The source mapping regions for this function.
143f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
144ee02499aSAlex Lorenz 
145fc05ee34SIgor Kudrin   /// \brief A set of regions which can be used as a filter.
146fc05ee34SIgor Kudrin   ///
147fc05ee34SIgor Kudrin   /// It is produced by emitExpansionRegions() and is used in
148fc05ee34SIgor Kudrin   /// emitSourceRegions() to suppress producing code regions if
149fc05ee34SIgor Kudrin   /// the same area is covered by expansion regions.
150fc05ee34SIgor Kudrin   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
151fc05ee34SIgor Kudrin       SourceRegionFilter;
152fc05ee34SIgor Kudrin 
153ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
154ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
155bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
156ee02499aSAlex Lorenz 
157ee02499aSAlex Lorenz   /// \brief Return the precise end location for the given token.
158ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
159bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
160bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
161bf42cfd7SJustin Bogner     unsigned TokLen =
162bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
163bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
164ee02499aSAlex Lorenz   }
165ee02499aSAlex Lorenz 
166bf42cfd7SJustin Bogner   /// \brief Return the start location of an included file or expanded macro.
167bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
168bf42cfd7SJustin Bogner     if (Loc.isMacroID())
169bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
170bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
171ee02499aSAlex Lorenz   }
172ee02499aSAlex Lorenz 
173bf42cfd7SJustin Bogner   /// \brief Return the end location of an included file or expanded macro.
174bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
175bf42cfd7SJustin Bogner     if (Loc.isMacroID())
176bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
177f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
178bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
179bf42cfd7SJustin Bogner   }
180ee02499aSAlex Lorenz 
181bf42cfd7SJustin Bogner   /// \brief Find out where the current file is included or macro is expanded.
182bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
183bf42cfd7SJustin Bogner     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
184bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
185bf42cfd7SJustin Bogner   }
186bf42cfd7SJustin Bogner 
187682bfbf3SJustin Bogner   /// \brief Return true if \c Loc is a location in a built-in macro.
188682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
18999d1b295SMehdi Amini     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
190682bfbf3SJustin Bogner   }
191682bfbf3SJustin Bogner 
192d9e1a61dSIgor Kudrin   /// \brief Check whether \c Loc is included or expanded from \c Parent.
193d9e1a61dSIgor Kudrin   bool isNestedIn(SourceLocation Loc, FileID Parent) {
194d9e1a61dSIgor Kudrin     do {
195d9e1a61dSIgor Kudrin       Loc = getIncludeOrExpansionLoc(Loc);
196d9e1a61dSIgor Kudrin       if (Loc.isInvalid())
197d9e1a61dSIgor Kudrin         return false;
198d9e1a61dSIgor Kudrin     } while (!SM.isInFileID(Loc, Parent));
199d9e1a61dSIgor Kudrin     return true;
200d9e1a61dSIgor Kudrin   }
201d9e1a61dSIgor Kudrin 
202682bfbf3SJustin Bogner   /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
203bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
204bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocStart();
205682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
206bf42cfd7SJustin Bogner       Loc = SM.getImmediateExpansionRange(Loc).first;
207bf42cfd7SJustin Bogner     return Loc;
208bf42cfd7SJustin Bogner   }
209bf42cfd7SJustin Bogner 
210682bfbf3SJustin Bogner   /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
211bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
212bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocEnd();
213682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
214bf42cfd7SJustin Bogner       Loc = SM.getImmediateExpansionRange(Loc).first;
215f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
216bf42cfd7SJustin Bogner   }
217bf42cfd7SJustin Bogner 
218bf42cfd7SJustin Bogner   /// \brief Find the set of files we have regions for and assign IDs
219bf42cfd7SJustin Bogner   ///
220bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
221bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
222bf42cfd7SJustin Bogner   /// expansion regions.
223bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
224bf42cfd7SJustin Bogner     FileIDMapping.clear();
225bf42cfd7SJustin Bogner 
226bc6b80a0SVedant Kumar     llvm::SmallSet<FileID, 8> Visited;
227bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
228bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
229bf42cfd7SJustin Bogner       SourceLocation Loc = Region.getStartLoc();
230bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
231bc6b80a0SVedant Kumar       if (!Visited.insert(File).second)
232bf42cfd7SJustin Bogner         continue;
233bf42cfd7SJustin Bogner 
23493205af0SVedant Kumar       // Do not map FileID's associated with system headers.
23593205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
23693205af0SVedant Kumar         continue;
23793205af0SVedant Kumar 
238bf42cfd7SJustin Bogner       unsigned Depth = 0;
239bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
240ed1fe5d0SYaron Keren            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
241bf42cfd7SJustin Bogner         ++Depth;
242bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
243bf42cfd7SJustin Bogner     }
244bf42cfd7SJustin Bogner     std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
245bf42cfd7SJustin Bogner 
246bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
247bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
248bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
249ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
250ee02499aSAlex Lorenz       if (!Entry)
251bf42cfd7SJustin Bogner         continue;
252ee02499aSAlex Lorenz 
253bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
254bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
255bf42cfd7SJustin Bogner     }
256ee02499aSAlex Lorenz   }
257ee02499aSAlex Lorenz 
258bf42cfd7SJustin Bogner   /// \brief Get the coverage mapping file ID for \c Loc.
259bf42cfd7SJustin Bogner   ///
260bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
261bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
262bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
263bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
264bf42cfd7SJustin Bogner       return Mapping->second.first;
265903678caSJustin Bogner     return None;
266ee02499aSAlex Lorenz   }
267ee02499aSAlex Lorenz 
268ee02499aSAlex Lorenz   /// \brief Gather all the regions that were skipped by the preprocessor
269ee02499aSAlex Lorenz   /// using the constructs like #if.
270ee02499aSAlex Lorenz   void gatherSkippedRegions() {
271ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
272ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
273ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
274ee02499aSAlex Lorenz     FileLineRanges.resize(
275ee02499aSAlex Lorenz         FileIDMapping.size(),
276ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
277ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
278ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
279ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
280ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
281ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
282ee02499aSAlex Lorenz     }
283ee02499aSAlex Lorenz 
284ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
285ee02499aSAlex Lorenz     for (const auto &I : SkippedRanges) {
286ee02499aSAlex Lorenz       auto LocStart = I.getBegin();
287ee02499aSAlex Lorenz       auto LocEnd = I.getEnd();
288bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
289bf42cfd7SJustin Bogner              "region spans multiple files");
290ee02499aSAlex Lorenz 
291bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
292903678caSJustin Bogner       if (!CovFileID)
293ee02499aSAlex Lorenz         continue;
294d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
295fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
296d7369648SVedant Kumar           *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
297ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
298ee02499aSAlex Lorenz       // the souce code of this function.
299903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
300903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
301ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
302ee02499aSAlex Lorenz     }
303ee02499aSAlex Lorenz   }
304ee02499aSAlex Lorenz 
305ee02499aSAlex Lorenz   /// \brief Generate the coverage counter mapping regions from collected
306ee02499aSAlex Lorenz   /// source regions.
307fc05ee34SIgor Kudrin   void emitSourceRegions(const SourceRegionFilter &Filter) {
308bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
309bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
310ee02499aSAlex Lorenz 
311bf42cfd7SJustin Bogner       SourceLocation LocStart = Region.getStartLoc();
3128b563665SYaron Keren       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
313f59329b0SJustin Bogner 
31493205af0SVedant Kumar       // Ignore regions from system headers.
31593205af0SVedant Kumar       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
31693205af0SVedant Kumar         continue;
31793205af0SVedant Kumar 
318bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
319bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
320bf42cfd7SJustin Bogner       if (!CovFileID)
321ee02499aSAlex Lorenz         continue;
322ee02499aSAlex Lorenz 
323f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
324bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
325bf42cfd7SJustin Bogner              "region spans multiple files");
326bf42cfd7SJustin Bogner 
327fc05ee34SIgor Kudrin       // Don't add code regions for the area covered by expansion regions.
328fc05ee34SIgor Kudrin       // This not only suppresses redundant regions, but sometimes prevents
329fc05ee34SIgor Kudrin       // creating regions with wrong counters if, for example, a statement's
330fc05ee34SIgor Kudrin       // body ends at the end of a nested macro.
331fc05ee34SIgor Kudrin       if (Filter.count(std::make_pair(LocStart, LocEnd)))
332fc05ee34SIgor Kudrin         continue;
333fc05ee34SIgor Kudrin 
334d7369648SVedant Kumar       // Find the spelling locations for the mapping region.
335d7369648SVedant Kumar       SpellingRegion SR{SM, LocStart, LocEnd};
336d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
337a1c4deb7SVedant Kumar 
338a1c4deb7SVedant Kumar       if (Region.isGap()) {
339a1c4deb7SVedant Kumar         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
340a1c4deb7SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
341a1c4deb7SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
342a1c4deb7SVedant Kumar       } else {
343bf42cfd7SJustin Bogner         MappingRegions.push_back(CounterMappingRegion::makeRegion(
344d7369648SVedant Kumar             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
345d7369648SVedant Kumar             SR.LineEnd, SR.ColumnEnd));
346bf42cfd7SJustin Bogner       }
347bf42cfd7SJustin Bogner     }
348a1c4deb7SVedant Kumar   }
349bf42cfd7SJustin Bogner 
350bf42cfd7SJustin Bogner   /// \brief Generate expansion regions for each virtual file we've seen.
351fc05ee34SIgor Kudrin   SourceRegionFilter emitExpansionRegions() {
352fc05ee34SIgor Kudrin     SourceRegionFilter Filter;
353bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
354bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
355bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
356bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
357ee02499aSAlex Lorenz         continue;
358ee02499aSAlex Lorenz 
359bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
360bf42cfd7SJustin Bogner       if (!ParentFileID)
361bf42cfd7SJustin Bogner         continue;
362bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
363bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
364bf42cfd7SJustin Bogner 
365bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
366bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
367bf42cfd7SJustin Bogner              "region spans multiple files");
368fc05ee34SIgor Kudrin       Filter.insert(std::make_pair(ParentLoc, LocEnd));
369bf42cfd7SJustin Bogner 
370d7369648SVedant Kumar       SpellingRegion SR{SM, ParentLoc, LocEnd};
371d7369648SVedant Kumar       assert(SR.isInSourceOrder() && "region start and end out of order");
372bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
373d7369648SVedant Kumar           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
374d7369648SVedant Kumar           SR.LineEnd, SR.ColumnEnd));
375ee02499aSAlex Lorenz     }
376fc05ee34SIgor Kudrin     return Filter;
377ee02499aSAlex Lorenz   }
378ee02499aSAlex Lorenz };
379ee02499aSAlex Lorenz 
380ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that
381ee02499aSAlex Lorenz /// are not emitted.
382ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
383ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
384ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
385ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
386ee02499aSAlex Lorenz 
387ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
388ee02499aSAlex Lorenz     if (!D->hasBody())
389ee02499aSAlex Lorenz       return;
390ee02499aSAlex Lorenz     auto Body = D->getBody();
391d9e1a61dSIgor Kudrin     SourceLocation Start = getStart(Body);
392d9e1a61dSIgor Kudrin     SourceLocation End = getEnd(Body);
393d9e1a61dSIgor Kudrin     if (!SM.isWrittenInSameFile(Start, End)) {
394d9e1a61dSIgor Kudrin       // Walk up to find the common ancestor.
395d9e1a61dSIgor Kudrin       // Correct the locations accordingly.
396d9e1a61dSIgor Kudrin       FileID StartFileID = SM.getFileID(Start);
397d9e1a61dSIgor Kudrin       FileID EndFileID = SM.getFileID(End);
398d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
399d9e1a61dSIgor Kudrin         Start = getIncludeOrExpansionLoc(Start);
400d9e1a61dSIgor Kudrin         assert(Start.isValid() &&
401d9e1a61dSIgor Kudrin                "Declaration start location not nested within a known region");
402d9e1a61dSIgor Kudrin         StartFileID = SM.getFileID(Start);
403d9e1a61dSIgor Kudrin       }
404d9e1a61dSIgor Kudrin       while (StartFileID != EndFileID) {
405d9e1a61dSIgor Kudrin         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
406d9e1a61dSIgor Kudrin         assert(End.isValid() &&
407d9e1a61dSIgor Kudrin                "Declaration end location not nested within a known region");
408d9e1a61dSIgor Kudrin         EndFileID = SM.getFileID(End);
409d9e1a61dSIgor Kudrin       }
410d9e1a61dSIgor Kudrin     }
411d9e1a61dSIgor Kudrin     SourceRegions.emplace_back(Counter(), Start, End);
412ee02499aSAlex Lorenz   }
413ee02499aSAlex Lorenz 
414ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
415ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
416ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
417bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
418fc05ee34SIgor Kudrin     emitSourceRegions(SourceRegionFilter());
419ee02499aSAlex Lorenz 
420efd319a2SVedant Kumar     if (MappingRegions.empty())
421efd319a2SVedant Kumar       return;
422efd319a2SVedant Kumar 
4235fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
424ee02499aSAlex Lorenz     Writer.write(OS);
425ee02499aSAlex Lorenz   }
426ee02499aSAlex Lorenz };
427ee02499aSAlex Lorenz 
428ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map
429ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
430ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
431ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
432ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
433ee02499aSAlex Lorenz   /// \brief The map of statements to count values.
434ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
435ee02499aSAlex Lorenz 
436bf42cfd7SJustin Bogner   /// \brief A stack of currently live regions.
437bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
438ee02499aSAlex Lorenz 
439747b0e29SVedant Kumar   /// The currently deferred region: its end location and count can be set once
440747b0e29SVedant Kumar   /// its parent has been popped from the region stack.
441747b0e29SVedant Kumar   Optional<SourceMappingRegion> DeferredRegion;
442747b0e29SVedant Kumar 
443ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
444ee02499aSAlex Lorenz 
445bf42cfd7SJustin Bogner   /// \brief A location in the most recently visited file or macro.
446bf42cfd7SJustin Bogner   ///
447bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
448bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
449bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
450bf42cfd7SJustin Bogner 
4518046d22aSVedant Kumar   /// Location of the last terminated region.
4528046d22aSVedant Kumar   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
4538046d22aSVedant Kumar 
454bf42cfd7SJustin Bogner   /// \brief Return a counter for the subtraction of \c RHS from \c LHS
455ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
456ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
457ee02499aSAlex Lorenz   }
458ee02499aSAlex Lorenz 
459bf42cfd7SJustin Bogner   /// \brief Return a counter for the sum of \c LHS and \c RHS.
460ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
461ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
462ee02499aSAlex Lorenz   }
463ee02499aSAlex Lorenz 
464bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
465bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
466bf42cfd7SJustin Bogner   }
467bf42cfd7SJustin Bogner 
468ee02499aSAlex Lorenz   /// \brief Return the region counter for the given statement.
469bf42cfd7SJustin Bogner   ///
470ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
471bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
472bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
473ee02499aSAlex Lorenz   }
474ee02499aSAlex Lorenz 
475bf42cfd7SJustin Bogner   /// \brief Push a region onto the stack.
476bf42cfd7SJustin Bogner   ///
477bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
478bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
479bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
480bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
481747b0e29SVedant Kumar     if (StartLoc) {
482bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
483747b0e29SVedant Kumar       completeDeferred(Count, MostRecentLocation);
484747b0e29SVedant Kumar     }
485bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
486ee02499aSAlex Lorenz 
487bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
488ee02499aSAlex Lorenz   }
489ee02499aSAlex Lorenz 
490747b0e29SVedant Kumar   /// Complete any pending deferred region by setting its end location and
491747b0e29SVedant Kumar   /// count, and then pushing it onto the region stack.
492747b0e29SVedant Kumar   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
493747b0e29SVedant Kumar     size_t Index = RegionStack.size();
494747b0e29SVedant Kumar     if (!DeferredRegion)
495747b0e29SVedant Kumar       return Index;
496747b0e29SVedant Kumar 
497747b0e29SVedant Kumar     // Consume the pending region.
498747b0e29SVedant Kumar     SourceMappingRegion DR = DeferredRegion.getValue();
499747b0e29SVedant Kumar     DeferredRegion = None;
500747b0e29SVedant Kumar 
501747b0e29SVedant Kumar     // If the region ends in an expansion, find the expansion site.
502747b0e29SVedant Kumar     FileID StartFile = SM.getFileID(DR.getStartLoc());
503f9a0d44eSVedant Kumar     if (SM.getFileID(DeferredEndLoc) != StartFile) {
504747b0e29SVedant Kumar       if (isNestedIn(DeferredEndLoc, StartFile)) {
505747b0e29SVedant Kumar         do {
506747b0e29SVedant Kumar           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
507747b0e29SVedant Kumar         } while (StartFile != SM.getFileID(DeferredEndLoc));
508f9a0d44eSVedant Kumar       } else {
509f9a0d44eSVedant Kumar         return Index;
510747b0e29SVedant Kumar       }
511747b0e29SVedant Kumar     }
512747b0e29SVedant Kumar 
513747b0e29SVedant Kumar     // The parent of this deferred region ends where the containing decl ends,
514747b0e29SVedant Kumar     // so the region isn't useful.
515747b0e29SVedant Kumar     if (DR.getStartLoc() == DeferredEndLoc)
516747b0e29SVedant Kumar       return Index;
517747b0e29SVedant Kumar 
518747b0e29SVedant Kumar     // If we're visiting statements in non-source order (e.g switch cases or
519747b0e29SVedant Kumar     // a loop condition) we can't construct a sensible deferred region.
520747b0e29SVedant Kumar     if (!SpellingRegion(SM, DR.getStartLoc(), DeferredEndLoc).isInSourceOrder())
521747b0e29SVedant Kumar       return Index;
522747b0e29SVedant Kumar 
523a1c4deb7SVedant Kumar     DR.setGap(true);
524747b0e29SVedant Kumar     DR.setCounter(Count);
525747b0e29SVedant Kumar     DR.setEndLoc(DeferredEndLoc);
526747b0e29SVedant Kumar     handleFileExit(DeferredEndLoc);
527747b0e29SVedant Kumar     RegionStack.push_back(DR);
528747b0e29SVedant Kumar     return Index;
529747b0e29SVedant Kumar   }
530747b0e29SVedant Kumar 
5318046d22aSVedant Kumar   /// Complete a deferred region created after a terminated region at the
5328046d22aSVedant Kumar   /// top-level.
5338046d22aSVedant Kumar   void completeTopLevelDeferredRegion(Counter Count,
5348046d22aSVedant Kumar                                       SourceLocation DeferredEndLoc) {
5358046d22aSVedant Kumar     if (DeferredRegion || !LastTerminatedRegion)
5368046d22aSVedant Kumar       return;
5378046d22aSVedant Kumar 
5388046d22aSVedant Kumar     if (LastTerminatedRegion->second != RegionStack.size())
5398046d22aSVedant Kumar       return;
5408046d22aSVedant Kumar 
5418046d22aSVedant Kumar     SourceLocation Start = LastTerminatedRegion->first;
5428046d22aSVedant Kumar     if (SM.getFileID(Start) != SM.getMainFileID())
5438046d22aSVedant Kumar       return;
5448046d22aSVedant Kumar 
5458046d22aSVedant Kumar     SourceMappingRegion DR = RegionStack.back();
5468046d22aSVedant Kumar     DR.setStartLoc(Start);
5478046d22aSVedant Kumar     DR.setDeferred(false);
5488046d22aSVedant Kumar     DeferredRegion = DR;
5498046d22aSVedant Kumar     completeDeferred(Count, DeferredEndLoc);
5508046d22aSVedant Kumar   }
5518046d22aSVedant Kumar 
552bf42cfd7SJustin Bogner   /// \brief Pop regions from the stack into the function's list of regions.
553bf42cfd7SJustin Bogner   ///
554bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
555bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
556bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
557bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
558747b0e29SVedant Kumar     bool ParentOfDeferredRegion = false;
559bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
560bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
561bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
562bf42cfd7SJustin Bogner         SourceLocation StartLoc = Region.getStartLoc();
563bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
564bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
565bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
566bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
567bf42cfd7SJustin Bogner           // The region ends in a nested file or macro expansion. Create a
568bf42cfd7SJustin Bogner           // separate region for each expansion.
569bf42cfd7SJustin Bogner           SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
570bf42cfd7SJustin Bogner           assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
571bf42cfd7SJustin Bogner 
5728545dae2SIgor Kudrin           if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
573bf42cfd7SJustin Bogner             SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
574bf42cfd7SJustin Bogner 
575f14b2078SJustin Bogner           EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
576dceaaadfSJustin Bogner           if (EndLoc.isInvalid())
577dceaaadfSJustin Bogner             llvm::report_fatal_error("File exit not handled before popRegions");
578bf42cfd7SJustin Bogner         }
579bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
580bf42cfd7SJustin Bogner 
581bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
582bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
583bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
584bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
585bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
586bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
587bf42cfd7SJustin Bogner 
588bf42cfd7SJustin Bogner         assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
589*fa8fa044SVedant Kumar         assert(SpellingRegion(SM, Region).isInSourceOrder());
590f36a5c4aSCraig Topper         SourceRegions.push_back(Region);
591747b0e29SVedant Kumar 
592747b0e29SVedant Kumar         if (ParentOfDeferredRegion) {
593747b0e29SVedant Kumar           ParentOfDeferredRegion = false;
594747b0e29SVedant Kumar 
595747b0e29SVedant Kumar           // If there's an existing deferred region, keep the old one, because
596747b0e29SVedant Kumar           // it means there are two consecutive returns (or a similar pattern).
597747b0e29SVedant Kumar           if (!DeferredRegion.hasValue() &&
598747b0e29SVedant Kumar               // File IDs aren't gathered within macro expansions, so it isn't
599747b0e29SVedant Kumar               // useful to try and create a deferred region inside of one.
600f9a0d44eSVedant Kumar               !EndLoc.isMacroID())
601747b0e29SVedant Kumar             DeferredRegion =
602747b0e29SVedant Kumar                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
603747b0e29SVedant Kumar         }
604747b0e29SVedant Kumar       } else if (Region.isDeferred()) {
605747b0e29SVedant Kumar         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
606747b0e29SVedant Kumar         ParentOfDeferredRegion = true;
607bf42cfd7SJustin Bogner       }
608bf42cfd7SJustin Bogner       RegionStack.pop_back();
6098046d22aSVedant Kumar 
6108046d22aSVedant Kumar       // If the zero region pushed after the last terminated region no longer
6118046d22aSVedant Kumar       // exists, clear its cached information.
6128046d22aSVedant Kumar       if (LastTerminatedRegion &&
6138046d22aSVedant Kumar           RegionStack.size() < LastTerminatedRegion->second)
6148046d22aSVedant Kumar         LastTerminatedRegion = None;
615bf42cfd7SJustin Bogner     }
616747b0e29SVedant Kumar     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
617ee02499aSAlex Lorenz   }
618ee02499aSAlex Lorenz 
619bf42cfd7SJustin Bogner   /// \brief Return the currently active region.
620bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
621bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
622bf42cfd7SJustin Bogner     return RegionStack.back();
623ee02499aSAlex Lorenz   }
624ee02499aSAlex Lorenz 
625bf42cfd7SJustin Bogner   /// \brief Propagate counts through the children of \c S.
626bf42cfd7SJustin Bogner   Counter propagateCounts(Counter TopCount, const Stmt *S) {
6277838696eSVedant Kumar     SourceLocation StartLoc = getStart(S);
6287838696eSVedant Kumar     SourceLocation EndLoc = getEnd(S);
6297838696eSVedant Kumar     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
630bf42cfd7SJustin Bogner     Visit(S);
631bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
632bf42cfd7SJustin Bogner     popRegions(Index);
63339f01975SVedant Kumar 
63439f01975SVedant Kumar     // The statement may be spanned by an expansion. Make sure we handle a file
63539f01975SVedant Kumar     // exit out of this expansion before moving to the next statement.
6367838696eSVedant Kumar     if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart()))
6377838696eSVedant Kumar       MostRecentLocation = EndLoc;
63839f01975SVedant Kumar 
639bf42cfd7SJustin Bogner     return ExitCount;
640ee02499aSAlex Lorenz   }
641ee02499aSAlex Lorenz 
6420a7c9d11SIgor Kudrin   /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
6430a7c9d11SIgor Kudrin   /// is already added to \c SourceRegions.
6440a7c9d11SIgor Kudrin   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
6450a7c9d11SIgor Kudrin     return SourceRegions.rend() !=
6460a7c9d11SIgor Kudrin            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
6470a7c9d11SIgor Kudrin                         [&](const SourceMappingRegion &Region) {
6480a7c9d11SIgor Kudrin                           return Region.getStartLoc() == StartLoc &&
6490a7c9d11SIgor Kudrin                                  Region.getEndLoc() == EndLoc;
6500a7c9d11SIgor Kudrin                         });
6510a7c9d11SIgor Kudrin   }
6520a7c9d11SIgor Kudrin 
653bf42cfd7SJustin Bogner   /// \brief Adjust the most recently visited location to \c EndLoc.
654bf42cfd7SJustin Bogner   ///
655bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
656bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
657bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
6580a7c9d11SIgor Kudrin     // The code region for a whole macro is created in handleFileExit() when
6590a7c9d11SIgor Kudrin     // it detects exiting of the virtual file of that macro. If we visited
6600a7c9d11SIgor Kudrin     // statements in non-source order, we might already have such a region
6610a7c9d11SIgor Kudrin     // added, for example, if a body of a loop is divided among multiple
6620a7c9d11SIgor Kudrin     // macros. Avoid adding duplicate regions in such case.
66396ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
6640a7c9d11SIgor Kudrin         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
6650a7c9d11SIgor Kudrin         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
6660a7c9d11SIgor Kudrin                              MostRecentLocation))
667bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
668ee02499aSAlex Lorenz   }
669ee02499aSAlex Lorenz 
670bf42cfd7SJustin Bogner   /// \brief Adjust regions and state when \c NewLoc exits a file.
671bf42cfd7SJustin Bogner   ///
672bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
673bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
674bf42cfd7SJustin Bogner   /// for the exited file.
675bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
676e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
677e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
678bf42cfd7SJustin Bogner       return;
679bf42cfd7SJustin Bogner 
680bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
681bf42cfd7SJustin Bogner     // find the common ancestor.
682bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
683bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
684bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
685bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
686bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
687bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
688bf42cfd7SJustin Bogner         // to adjust our location to the new file.
689bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
690bf42cfd7SJustin Bogner         return;
691bf42cfd7SJustin Bogner       }
692bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
693ee02499aSAlex Lorenz     }
694ee02499aSAlex Lorenz 
695bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
696bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
69757d3f145SPete Cooper     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
69857d3f145SPete Cooper       if (!I.hasStartLoc())
699bf42cfd7SJustin Bogner         continue;
70057d3f145SPete Cooper       SourceLocation Loc = I.getStartLoc();
701bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
70257d3f145SPete Cooper         ParentCounter = I.getCounter();
703bf42cfd7SJustin Bogner         break;
704ee02499aSAlex Lorenz       }
705bf42cfd7SJustin Bogner 
706bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
707bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
708bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
709bf42cfd7SJustin Bogner         // we've seen this region.
710bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
71157d3f145SPete Cooper           SourceRegions.emplace_back(I.getCounter(), Loc,
712bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
713bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
714ee02499aSAlex Lorenz       }
71557d3f145SPete Cooper       I.setStartLoc(getPreciseTokenLocEnd(Loc));
716bf42cfd7SJustin Bogner     }
717bf42cfd7SJustin Bogner 
718bf42cfd7SJustin Bogner     if (ParentCounter) {
719bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
720bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
721bf42cfd7SJustin Bogner       // corresponding to the parent.
722bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
723bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
724bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
725*fa8fa044SVedant Kumar         if (StartLocs.insert(FileStart).second) {
726bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
727bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
728*fa8fa044SVedant Kumar           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
729*fa8fa044SVedant Kumar         }
730bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
731bf42cfd7SJustin Bogner       }
732bf42cfd7SJustin Bogner     }
733bf42cfd7SJustin Bogner 
734bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
735bf42cfd7SJustin Bogner   }
736bf42cfd7SJustin Bogner 
737bf42cfd7SJustin Bogner   /// \brief Ensure that \c S is included in the current region.
738bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
739bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
740bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
741bf42cfd7SJustin Bogner 
742bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
743bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
744bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
745747b0e29SVedant Kumar 
746747b0e29SVedant Kumar     completeDeferred(Region.getCounter(), StartLoc);
747bf42cfd7SJustin Bogner   }
748bf42cfd7SJustin Bogner 
749bf42cfd7SJustin Bogner   /// \brief Mark \c S as a terminator, starting a zero region.
750bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
751bf42cfd7SJustin Bogner     extendRegion(S);
752bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
7538046d22aSVedant Kumar     SourceLocation EndLoc = getEnd(S);
754bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
7558046d22aSVedant Kumar       Region.setEndLoc(EndLoc);
756bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
7578046d22aSVedant Kumar     auto &ZeroRegion = getRegion();
7588046d22aSVedant Kumar     ZeroRegion.setDeferred(true);
7598046d22aSVedant Kumar     LastTerminatedRegion = {EndLoc, RegionStack.size()};
760bf42cfd7SJustin Bogner   }
761ee02499aSAlex Lorenz 
762*fa8fa044SVedant Kumar   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
763*fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
764*fa8fa044SVedant Kumar                                            SourceLocation BeforeLoc) {
765*fa8fa044SVedant Kumar     // If the start and end locations of the gap are both within the same macro
766*fa8fa044SVedant Kumar     // file, the range may not be in source order.
767*fa8fa044SVedant Kumar     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
768*fa8fa044SVedant Kumar       return None;
769*fa8fa044SVedant Kumar     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
770*fa8fa044SVedant Kumar       return None;
771*fa8fa044SVedant Kumar     return {{AfterLoc, BeforeLoc}};
772*fa8fa044SVedant Kumar   }
773*fa8fa044SVedant Kumar 
774*fa8fa044SVedant Kumar   /// Find the source range after \p AfterStmt and before \p BeforeStmt.
775*fa8fa044SVedant Kumar   Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
776*fa8fa044SVedant Kumar                                            const Stmt *BeforeStmt) {
777*fa8fa044SVedant Kumar     return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
778*fa8fa044SVedant Kumar                               getStart(BeforeStmt));
779*fa8fa044SVedant Kumar   }
780*fa8fa044SVedant Kumar 
7812e8c8759SVedant Kumar   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
7822e8c8759SVedant Kumar   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
7832e8c8759SVedant Kumar                             Counter Count) {
784*fa8fa044SVedant Kumar     if (StartLoc == EndLoc)
7852e8c8759SVedant Kumar       return;
786*fa8fa044SVedant Kumar     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
7872e8c8759SVedant Kumar     handleFileExit(StartLoc);
7882e8c8759SVedant Kumar     size_t Index = pushRegion(Count, StartLoc, EndLoc);
7892e8c8759SVedant Kumar     getRegion().setGap(true);
7902e8c8759SVedant Kumar     handleFileExit(EndLoc);
7912e8c8759SVedant Kumar     popRegions(Index);
7922e8c8759SVedant Kumar   }
7932e8c8759SVedant Kumar 
794ee02499aSAlex Lorenz   /// \brief Keep counts of breaks and continues inside loops.
795ee02499aSAlex Lorenz   struct BreakContinue {
796ee02499aSAlex Lorenz     Counter BreakCount;
797ee02499aSAlex Lorenz     Counter ContinueCount;
798ee02499aSAlex Lorenz   };
799ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
800ee02499aSAlex Lorenz 
801ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
802ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
803e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
804ee02499aSAlex Lorenz       const LangOptions &LangOpts)
805747b0e29SVedant Kumar       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
806747b0e29SVedant Kumar         DeferredRegion(None) {}
807ee02499aSAlex Lorenz 
808ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
809ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
810ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
811bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
812fc05ee34SIgor Kudrin     SourceRegionFilter Filter = emitExpansionRegions();
813747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
814fc05ee34SIgor Kudrin     emitSourceRegions(Filter);
815ee02499aSAlex Lorenz     gatherSkippedRegions();
816ee02499aSAlex Lorenz 
817efd319a2SVedant Kumar     if (MappingRegions.empty())
818efd319a2SVedant Kumar       return;
819efd319a2SVedant Kumar 
8204da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
8214da909b2SJustin Bogner                                  MappingRegions);
822ee02499aSAlex Lorenz     Writer.write(OS);
823ee02499aSAlex Lorenz   }
824ee02499aSAlex Lorenz 
825ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
826ed1fe5d0SYaron Keren     if (S->getLocStart().isValid())
827bf42cfd7SJustin Bogner       extendRegion(S);
828642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
829642f173aSBenjamin Kramer       if (Child)
830642f173aSBenjamin Kramer         this->Visit(Child);
831bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
832ee02499aSAlex Lorenz   }
833ee02499aSAlex Lorenz 
834341bf429SVedant Kumar   /// Determine whether the final deferred region emitted in \p Body should be
835341bf429SVedant Kumar   /// discarded.
836341bf429SVedant Kumar   static bool discardFinalDeferredRegionInDecl(Stmt *Body) {
837341bf429SVedant Kumar     if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
838341bf429SVedant Kumar       Stmt *LastStmt = CS->body_back();
839341bf429SVedant Kumar       if (auto *IfElse = dyn_cast<IfStmt>(LastStmt)) {
840341bf429SVedant Kumar         if (auto *Else = dyn_cast_or_null<CompoundStmt>(IfElse->getElse()))
841341bf429SVedant Kumar           LastStmt = Else->body_back();
842341bf429SVedant Kumar         else
843341bf429SVedant Kumar           LastStmt = IfElse->getElse();
844341bf429SVedant Kumar       }
845341bf429SVedant Kumar       return dyn_cast_or_null<ReturnStmt>(LastStmt);
846341bf429SVedant Kumar     }
847341bf429SVedant Kumar     return false;
848341bf429SVedant Kumar   }
849341bf429SVedant Kumar 
850ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
851747b0e29SVedant Kumar     assert(!DeferredRegion && "Deferred region never completed");
852747b0e29SVedant Kumar 
853bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
854efd319a2SVedant Kumar 
855efd319a2SVedant Kumar     // Do not propagate region counts into system headers.
856efd319a2SVedant Kumar     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
857efd319a2SVedant Kumar       return;
858efd319a2SVedant Kumar 
859747b0e29SVedant Kumar     Counter ExitCount = propagateCounts(getRegionCounter(Body), Body);
860747b0e29SVedant Kumar     assert(RegionStack.empty() && "Regions entered but never exited");
861747b0e29SVedant Kumar 
862341bf429SVedant Kumar     if (DeferredRegion) {
863341bf429SVedant Kumar       // Complete (or discard) any deferred regions introduced by the last
864341bf429SVedant Kumar       // statement.
865341bf429SVedant Kumar       if (discardFinalDeferredRegionInDecl(Body))
866ef8e05ffSVedant Kumar         DeferredRegion = None;
867341bf429SVedant Kumar       else
868747b0e29SVedant Kumar         popRegions(completeDeferred(ExitCount, getEnd(Body)));
869ee02499aSAlex Lorenz     }
870341bf429SVedant Kumar   }
871ee02499aSAlex Lorenz 
872ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
873bf42cfd7SJustin Bogner     extendRegion(S);
874ee02499aSAlex Lorenz     if (S->getRetValue())
875ee02499aSAlex Lorenz       Visit(S->getRetValue());
876bf42cfd7SJustin Bogner     terminateRegion(S);
877ee02499aSAlex Lorenz   }
878ee02499aSAlex Lorenz 
879f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
880f959febfSJustin Bogner     extendRegion(E);
881f959febfSJustin Bogner     if (E->getSubExpr())
882f959febfSJustin Bogner       Visit(E->getSubExpr());
883f959febfSJustin Bogner     terminateRegion(E);
884f959febfSJustin Bogner   }
885f959febfSJustin Bogner 
886bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
887ee02499aSAlex Lorenz 
888ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
8898046d22aSVedant Kumar     Counter LabelCount = getRegionCounter(S);
890bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
8918046d22aSVedant Kumar     completeTopLevelDeferredRegion(LabelCount, Start);
892bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
893bf42cfd7SJustin Bogner     handleFileExit(Start);
8948046d22aSVedant Kumar     pushRegion(LabelCount, Start);
895ee02499aSAlex Lorenz     Visit(S->getSubStmt());
896ee02499aSAlex Lorenz   }
897ee02499aSAlex Lorenz 
898ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
899ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
900ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
901bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
9027f53fbfcSEli Friedman     // FIXME: a break in a switch should terminate regions for all preceding
9037f53fbfcSEli Friedman     // case statements, not just the most recent one.
904bf42cfd7SJustin Bogner     terminateRegion(S);
905ee02499aSAlex Lorenz   }
906ee02499aSAlex Lorenz 
907ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
908ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
909ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
910bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
911bf42cfd7SJustin Bogner     terminateRegion(S);
912ee02499aSAlex Lorenz   }
913ee02499aSAlex Lorenz 
914181dfe4cSEli Friedman   void VisitCallExpr(const CallExpr *E) {
915181dfe4cSEli Friedman     VisitStmt(E);
916181dfe4cSEli Friedman 
917181dfe4cSEli Friedman     // Terminate the region when we hit a noreturn function.
918181dfe4cSEli Friedman     // (This is helpful dealing with switch statements.)
919181dfe4cSEli Friedman     QualType CalleeType = E->getCallee()->getType();
920181dfe4cSEli Friedman     if (getFunctionExtInfo(*CalleeType).getNoReturn())
921181dfe4cSEli Friedman       terminateRegion(E);
922181dfe4cSEli Friedman   }
923181dfe4cSEli Friedman 
924ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
925bf42cfd7SJustin Bogner     extendRegion(S);
926ee02499aSAlex Lorenz 
927bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
928bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
929bf42cfd7SJustin Bogner 
930bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
931bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
932bf42cfd7SJustin Bogner     extendRegion(S->getBody());
933bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
934ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
935bf42cfd7SJustin Bogner 
936bf42cfd7SJustin Bogner     // Go back to handle the condition.
937bf42cfd7SJustin Bogner     Counter CondCount =
938bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
939bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
940bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
941bf42cfd7SJustin Bogner 
942*fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
943*fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
944*fa8fa044SVedant Kumar     if (Gap)
945*fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
946*fa8fa044SVedant Kumar 
947bf42cfd7SJustin Bogner     Counter OutCount =
948bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
949bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
950bf42cfd7SJustin Bogner       pushRegion(OutCount);
951ee02499aSAlex Lorenz   }
952ee02499aSAlex Lorenz 
953ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
954bf42cfd7SJustin Bogner     extendRegion(S);
955ee02499aSAlex Lorenz 
956bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
957bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
958bf42cfd7SJustin Bogner 
959bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
960bf42cfd7SJustin Bogner     extendRegion(S->getBody());
961bf42cfd7SJustin Bogner     Counter BackedgeCount =
962bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
963ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
964bf42cfd7SJustin Bogner 
965bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
966bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
967bf42cfd7SJustin Bogner 
968bf42cfd7SJustin Bogner     Counter OutCount =
969bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
970bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
971bf42cfd7SJustin Bogner       pushRegion(OutCount);
972ee02499aSAlex Lorenz   }
973ee02499aSAlex Lorenz 
974ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
975bf42cfd7SJustin Bogner     extendRegion(S);
976ee02499aSAlex Lorenz     if (S->getInit())
977ee02499aSAlex Lorenz       Visit(S->getInit());
978ee02499aSAlex Lorenz 
979bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
980bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
981bf42cfd7SJustin Bogner 
982bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
983ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
984bf42cfd7SJustin Bogner     extendRegion(S->getBody());
985bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
986bf42cfd7SJustin Bogner     BreakContinue BC = BreakContinueStack.pop_back_val();
987ee02499aSAlex Lorenz 
988ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
989ee02499aSAlex Lorenz     // the count for all the continue statements.
990bf42cfd7SJustin Bogner     if (const Stmt *Inc = S->getInc())
991bf42cfd7SJustin Bogner       propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
992bf42cfd7SJustin Bogner 
993bf42cfd7SJustin Bogner     // Go back to handle the condition.
994bf42cfd7SJustin Bogner     Counter CondCount =
995bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
996bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
997bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
998bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
999ee02499aSAlex Lorenz     }
1000ee02499aSAlex Lorenz 
1001*fa8fa044SVedant Kumar     // The body count applies to the area immediately after the increment.
1002*fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1003*fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1004*fa8fa044SVedant Kumar     if (Gap)
1005*fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1006*fa8fa044SVedant Kumar 
1007bf42cfd7SJustin Bogner     Counter OutCount =
1008bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1009bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1010bf42cfd7SJustin Bogner       pushRegion(OutCount);
1011ee02499aSAlex Lorenz   }
1012ee02499aSAlex Lorenz 
1013ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1014bf42cfd7SJustin Bogner     extendRegion(S);
1015bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
1016ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
1017bf42cfd7SJustin Bogner 
1018bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1019bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1020bf42cfd7SJustin Bogner 
1021ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1022bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1023bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1024ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1025bf42cfd7SJustin Bogner 
1026*fa8fa044SVedant Kumar     // The body count applies to the area immediately after the range.
1027*fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1028*fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1029*fa8fa044SVedant Kumar     if (Gap)
1030*fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1031*fa8fa044SVedant Kumar 
10321587432dSJustin Bogner     Counter LoopCount =
10331587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
10341587432dSJustin Bogner     Counter OutCount =
10351587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1036bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1037bf42cfd7SJustin Bogner       pushRegion(OutCount);
1038ee02499aSAlex Lorenz   }
1039ee02499aSAlex Lorenz 
1040ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1041bf42cfd7SJustin Bogner     extendRegion(S);
1042ee02499aSAlex Lorenz     Visit(S->getElement());
1043bf42cfd7SJustin Bogner 
1044bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1045bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
1046bf42cfd7SJustin Bogner 
1047ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1048bf42cfd7SJustin Bogner     extendRegion(S->getBody());
1049bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1050ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1051bf42cfd7SJustin Bogner 
1052*fa8fa044SVedant Kumar     // The body count applies to the area immediately after the collection.
1053*fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1054*fa8fa044SVedant Kumar                                   getStart(S->getBody()));
1055*fa8fa044SVedant Kumar     if (Gap)
1056*fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1057*fa8fa044SVedant Kumar 
10581587432dSJustin Bogner     Counter LoopCount =
10591587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
10601587432dSJustin Bogner     Counter OutCount =
10611587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1062bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1063bf42cfd7SJustin Bogner       pushRegion(OutCount);
1064ee02499aSAlex Lorenz   }
1065ee02499aSAlex Lorenz 
1066ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
1067bf42cfd7SJustin Bogner     extendRegion(S);
1068f2a6ec55SVedant Kumar     if (S->getInit())
1069f2a6ec55SVedant Kumar       Visit(S->getInit());
1070ee02499aSAlex Lorenz     Visit(S->getCond());
1071bf42cfd7SJustin Bogner 
1072ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
1073bf42cfd7SJustin Bogner 
1074bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
1075bf42cfd7SJustin Bogner     extendRegion(Body);
1076bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1077bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
10787f53fbfcSEli Friedman         // Make a region for the body of the switch.  If the body starts with
10797f53fbfcSEli Friedman         // a case, that case will reuse this region; otherwise, this covers
10807f53fbfcSEli Friedman         // the unreachable code at the beginning of the switch body.
1081bf42cfd7SJustin Bogner         size_t Index =
10827f53fbfcSEli Friedman             pushRegion(Counter::getZero(), getStart(CS->body_front()));
1083b5841332SRichard Trieu         for (const auto *Child : CS->children())
1084bf42cfd7SJustin Bogner           Visit(Child);
10857f53fbfcSEli Friedman 
10867f53fbfcSEli Friedman         // Set the end for the body of the switch, if it isn't already set.
10877f53fbfcSEli Friedman         for (size_t i = RegionStack.size(); i != Index; --i) {
10887f53fbfcSEli Friedman           if (!RegionStack[i - 1].hasEndLoc())
10897f53fbfcSEli Friedman             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
10907f53fbfcSEli Friedman         }
10917f53fbfcSEli Friedman 
1092bf42cfd7SJustin Bogner         popRegions(Index);
1093ee02499aSAlex Lorenz       }
109487ea3b05SVedant Kumar     } else
1095bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
1096ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
1097bf42cfd7SJustin Bogner 
1098ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
1099ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
1100ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1101bf42cfd7SJustin Bogner 
1102bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
11033836482aSVedant Kumar     SourceLocation ExitLoc = getEnd(S);
110408780529SAlex Lorenz     pushRegion(ExitCount);
110508780529SAlex Lorenz 
110608780529SAlex Lorenz     // Ensure that handleFileExit recognizes when the end location is located
110708780529SAlex Lorenz     // in a different file.
110808780529SAlex Lorenz     MostRecentLocation = getStart(S);
11093836482aSVedant Kumar     handleFileExit(ExitLoc);
1110ee02499aSAlex Lorenz   }
1111ee02499aSAlex Lorenz 
1112bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
1113bf42cfd7SJustin Bogner     extendRegion(S);
1114ee02499aSAlex Lorenz 
1115bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
1116bf42cfd7SJustin Bogner 
1117bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1118bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
1119bf42cfd7SJustin Bogner     // the first case in a switch.
1120bf42cfd7SJustin Bogner     if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
1121bf42cfd7SJustin Bogner       Parent.setCounter(Count);
1122bf42cfd7SJustin Bogner     else
1123bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
1124bf42cfd7SJustin Bogner 
1125376c06c2SSanjay Patel     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1126bf42cfd7SJustin Bogner       Visit(CS->getLHS());
1127bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
1128bf42cfd7SJustin Bogner         Visit(RHS);
1129bf42cfd7SJustin Bogner     }
1130ee02499aSAlex Lorenz     Visit(S->getSubStmt());
1131ee02499aSAlex Lorenz   }
1132ee02499aSAlex Lorenz 
1133ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
1134bf42cfd7SJustin Bogner     extendRegion(S);
11359d2a16b9SVedant Kumar     if (S->getInit())
11369d2a16b9SVedant Kumar       Visit(S->getInit());
11379d2a16b9SVedant Kumar 
1138055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
1139055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
1140055ebc34SJustin Bogner     extendRegion(S->getCond());
1141ee02499aSAlex Lorenz 
1142bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1143bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
1144ee02499aSAlex Lorenz 
114591f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
114691f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
114791f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
114891f2e3c9SJustin Bogner 
11492e8c8759SVedant Kumar     // The 'then' count applies to the area immediately after the condition.
1150*fa8fa044SVedant Kumar     auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1151*fa8fa044SVedant Kumar     if (Gap)
1152*fa8fa044SVedant Kumar       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
11532e8c8759SVedant Kumar 
1154bf42cfd7SJustin Bogner     extendRegion(S->getThen());
1155bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1156bf42cfd7SJustin Bogner 
1157bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1158bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
11592e8c8759SVedant Kumar       // The 'else' count applies to the area immediately after the 'then'.
1160*fa8fa044SVedant Kumar       Gap = findGapAreaBetween(S->getThen(), Else);
1161*fa8fa044SVedant Kumar       if (Gap)
1162*fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
11632e8c8759SVedant Kumar       extendRegion(Else);
1164bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1165bf42cfd7SJustin Bogner     } else
1166bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
1167bf42cfd7SJustin Bogner 
1168bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
1169bf42cfd7SJustin Bogner       pushRegion(OutCount);
1170ee02499aSAlex Lorenz   }
1171ee02499aSAlex Lorenz 
1172ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
1173bf42cfd7SJustin Bogner     extendRegion(S);
1174049908b2SVedant Kumar     // Handle macros that generate the "try" but not the rest.
1175049908b2SVedant Kumar     extendRegion(S->getTryBlock());
1176049908b2SVedant Kumar 
1177049908b2SVedant Kumar     Counter ParentCount = getRegion().getCounter();
1178049908b2SVedant Kumar     propagateCounts(ParentCount, S->getTryBlock());
1179049908b2SVedant Kumar 
1180ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1181ee02499aSAlex Lorenz       Visit(S->getHandler(I));
1182bf42cfd7SJustin Bogner 
1183bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
1184bf42cfd7SJustin Bogner     pushRegion(ExitCount);
1185ee02499aSAlex Lorenz   }
1186ee02499aSAlex Lorenz 
1187ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1188bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1189ee02499aSAlex Lorenz   }
1190ee02499aSAlex Lorenz 
1191ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1192bf42cfd7SJustin Bogner     extendRegion(E);
1193ee02499aSAlex Lorenz 
1194bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
1195bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
1196ee02499aSAlex Lorenz 
1197e3654ce7SJustin Bogner     Visit(E->getCond());
1198e3654ce7SJustin Bogner 
1199e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
12002e8c8759SVedant Kumar       // The 'then' count applies to the area immediately after the condition.
1201*fa8fa044SVedant Kumar       auto Gap =
1202*fa8fa044SVedant Kumar           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1203*fa8fa044SVedant Kumar       if (Gap)
1204*fa8fa044SVedant Kumar         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
12052e8c8759SVedant Kumar 
1206e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
1207bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
1208e3654ce7SJustin Bogner     }
12092e8c8759SVedant Kumar 
1210e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
1211bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
1212bf42cfd7SJustin Bogner                     E->getFalseExpr());
1213ee02499aSAlex Lorenz   }
1214ee02499aSAlex Lorenz 
1215ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
1216e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1217e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1218e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1219bf42cfd7SJustin Bogner 
1220bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1221bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
1222ee02499aSAlex Lorenz   }
1223ee02499aSAlex Lorenz 
1224ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
1225e5f06a81SVedant Kumar     extendRegion(E->getLHS());
1226e5f06a81SVedant Kumar     propagateCounts(getRegion().getCounter(), E->getLHS());
1227e5f06a81SVedant Kumar     handleFileExit(getEnd(E->getLHS()));
1228ee02499aSAlex Lorenz 
1229bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
1230bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
123101a0d062SAlex Lorenz   }
1232c109102eSJustin Bogner 
1233c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
1234c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
1235c109102eSJustin Bogner     // propagate counts into them.
1236c109102eSJustin Bogner   }
1237ee02499aSAlex Lorenz };
1238ee02499aSAlex Lorenz 
12391f39fcf2SXinliang David Li std::string getCoverageSection(const CodeGenModule &CGM) {
12408a767a43SVedant Kumar   return llvm::getInstrProfSectionName(
12418a767a43SVedant Kumar       llvm::IPSK_covmap,
12428a767a43SVedant Kumar       CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1243ee02499aSAlex Lorenz }
1244ee02499aSAlex Lorenz 
124514f8fb68SVedant Kumar std::string normalizeFilename(StringRef Filename) {
124614f8fb68SVedant Kumar   llvm::SmallString<256> Path(Filename);
124714f8fb68SVedant Kumar   llvm::sys::fs::make_absolute(Path);
1248d04929d8SVedant Kumar   llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
124914f8fb68SVedant Kumar   return Path.str().str();
125014f8fb68SVedant Kumar }
125114f8fb68SVedant Kumar 
125214f8fb68SVedant Kumar } // end anonymous namespace
125314f8fb68SVedant Kumar 
1254a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1255a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
1256a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
1257a432d176SJustin Bogner   OS << FunctionName << ":\n";
1258a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
1259a432d176SJustin Bogner   for (const auto &R : Regions) {
1260f2cf38e0SAlex Lorenz     OS.indent(2);
1261f2cf38e0SAlex Lorenz     switch (R.Kind) {
1262f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1263f2cf38e0SAlex Lorenz       break;
1264f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1265f2cf38e0SAlex Lorenz       OS << "Expansion,";
1266f2cf38e0SAlex Lorenz       break;
1267f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1268f2cf38e0SAlex Lorenz       OS << "Skipped,";
1269f2cf38e0SAlex Lorenz       break;
1270a1c4deb7SVedant Kumar     case CounterMappingRegion::GapRegion:
1271a1c4deb7SVedant Kumar       OS << "Gap,";
1272a1c4deb7SVedant Kumar       break;
1273f2cf38e0SAlex Lorenz     }
1274f2cf38e0SAlex Lorenz 
12754da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
12764da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1277f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1278f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
12794da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
12804da909b2SJustin Bogner     OS << "\n";
1281f2cf38e0SAlex Lorenz   }
1282f2cf38e0SAlex Lorenz }
1283f2cf38e0SAlex Lorenz 
1284ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord(
12852129ae53SXinliang David Li     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1286848da137SXinliang David Li     const std::string &CoverageMapping, bool IsUsed) {
1287ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1288ee02499aSAlex Lorenz   if (!FunctionRecordTy) {
1289a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1290a026a437SXinliang David Li     llvm::Type *FunctionRecordTypes[] = {
1291a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1292a026a437SXinliang David Li     };
1293ee02499aSAlex Lorenz     FunctionRecordTy =
12944dc5adc7SJustin Bogner         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
12954dc5adc7SJustin Bogner                               /*isPacked=*/true);
1296ee02499aSAlex Lorenz   }
1297ee02499aSAlex Lorenz 
1298a026a437SXinliang David Li   #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1299ee02499aSAlex Lorenz   llvm::Constant *FunctionRecordVals[] = {
1300a026a437SXinliang David Li       #include "llvm/ProfileData/InstrProfData.inc"
1301a026a437SXinliang David Li   };
1302ee02499aSAlex Lorenz   FunctionRecords.push_back(llvm::ConstantStruct::get(
1303ee02499aSAlex Lorenz       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
1304848da137SXinliang David Li   if (!IsUsed)
13052129ae53SXinliang David Li     FunctionNames.push_back(
13062129ae53SXinliang David Li         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1307ca3326c0SVedant Kumar   CoverageMappings.push_back(CoverageMapping);
1308f2cf38e0SAlex Lorenz 
1309f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1310f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1311f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1312f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1313f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1314f2cf38e0SAlex Lorenz     // expressions.
1315f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1316f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1317f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1318b31ee819SJordan Rose     llvm::SmallVector<std::string, 16> FilenameStrs;
1319f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1320b31ee819SJordan Rose     FilenameStrs.resize(FileEntries.size());
1321f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1322b31ee819SJordan Rose     for (const auto &Entry : FileEntries) {
1323b31ee819SJordan Rose       auto I = Entry.second;
1324b31ee819SJordan Rose       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1325b31ee819SJordan Rose       FilenameRefs[I] = FilenameStrs[I];
1326b31ee819SJordan Rose     }
1327a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1328a432d176SJustin Bogner                                     Expressions, Regions);
1329a432d176SJustin Bogner     if (Reader.read())
1330f2cf38e0SAlex Lorenz       return;
1331a026a437SXinliang David Li     dump(llvm::outs(), NameValue, Expressions, Regions);
1332f2cf38e0SAlex Lorenz   }
1333ee02499aSAlex Lorenz }
1334ee02499aSAlex Lorenz 
1335ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1336ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1337ee02499aSAlex Lorenz     return;
1338ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1339ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1340ee02499aSAlex Lorenz 
1341ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1342ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
13439e324dd1SVedant Kumar   llvm::SmallVector<StringRef, 16> FilenameRefs;
1344ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
13459e324dd1SVedant Kumar   FilenameRefs.resize(FileEntries.size());
1346ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1347ee02499aSAlex Lorenz     auto I = Entry.second;
134814f8fb68SVedant Kumar     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
13499e324dd1SVedant Kumar     FilenameRefs[I] = FilenameStrs[I];
1350ee02499aSAlex Lorenz   }
1351ee02499aSAlex Lorenz 
13529e324dd1SVedant Kumar   std::string FilenamesAndCoverageMappings;
13539e324dd1SVedant Kumar   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
13549e324dd1SVedant Kumar   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
13559e324dd1SVedant Kumar   std::string RawCoverageMappings =
13569e324dd1SVedant Kumar       llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
13579e324dd1SVedant Kumar   OS << RawCoverageMappings;
13589e324dd1SVedant Kumar   size_t CoverageMappingSize = RawCoverageMappings.size();
13599e324dd1SVedant Kumar   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
13609e324dd1SVedant Kumar   // Append extra zeroes if necessary to ensure that the size of the filenames
13619e324dd1SVedant Kumar   // and coverage mappings is a multiple of 8.
13629e324dd1SVedant Kumar   if (size_t Rem = OS.str().size() % 8) {
13639e324dd1SVedant Kumar     CoverageMappingSize += 8 - Rem;
13649e324dd1SVedant Kumar     for (size_t I = 0, S = 8 - Rem; I < S; ++I)
13659e324dd1SVedant Kumar       OS << '\0';
1366ee02499aSAlex Lorenz   }
1367ee02499aSAlex Lorenz   auto *FilenamesAndMappingsVal =
13689e324dd1SVedant Kumar       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1369ee02499aSAlex Lorenz 
1370ee02499aSAlex Lorenz   // Create the deferred function records array
1371ee02499aSAlex Lorenz   auto RecordsTy =
1372ee02499aSAlex Lorenz       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1373ee02499aSAlex Lorenz   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1374ee02499aSAlex Lorenz 
137520b188c0SXinliang David Li   llvm::Type *CovDataHeaderTypes[] = {
137620b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
137720b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
137820b188c0SXinliang David Li   };
137920b188c0SXinliang David Li   auto CovDataHeaderTy =
138020b188c0SXinliang David Li       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
138120b188c0SXinliang David Li   llvm::Constant *CovDataHeaderVals[] = {
138220b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
138320b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc"
138420b188c0SXinliang David Li   };
138520b188c0SXinliang David Li   auto CovDataHeaderVal = llvm::ConstantStruct::get(
138620b188c0SXinliang David Li       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
138720b188c0SXinliang David Li 
1388ee02499aSAlex Lorenz   // Create the coverage data record
138920b188c0SXinliang David Li   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
139020b188c0SXinliang David Li                                 FilenamesAndMappingsVal->getType()};
1391ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
139220b188c0SXinliang David Li   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
139320b188c0SXinliang David Li                                   FilenamesAndMappingsVal};
1394ee02499aSAlex Lorenz   auto CovDataVal =
1395ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
139620b188c0SXinliang David Li   auto CovData = new llvm::GlobalVariable(
139720b188c0SXinliang David Li       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
139820b188c0SXinliang David Li       CovDataVal, llvm::getCoverageMappingVarName());
1399ee02499aSAlex Lorenz 
1400ee02499aSAlex Lorenz   CovData->setSection(getCoverageSection(CGM));
1401ee02499aSAlex Lorenz   CovData->setAlignment(8);
1402ee02499aSAlex Lorenz 
1403ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1404ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
14052129ae53SXinliang David Li   // Create the deferred function records array
14062129ae53SXinliang David Li   if (!FunctionNames.empty()) {
14072129ae53SXinliang David Li     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
14082129ae53SXinliang David Li                                            FunctionNames.size());
14092129ae53SXinliang David Li     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
14102129ae53SXinliang David Li     // This variable will *NOT* be emitted to the object file. It is used
14112129ae53SXinliang David Li     // to pass the list of names referenced to codegen.
14122129ae53SXinliang David Li     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
14132129ae53SXinliang David Li                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
14147077f0afSXinliang David Li                              llvm::getCoverageUnusedNamesVarName());
14152129ae53SXinliang David Li   }
1416ee02499aSAlex Lorenz }
1417ee02499aSAlex Lorenz 
1418ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1419ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1420ee02499aSAlex Lorenz   if (It != FileEntries.end())
1421ee02499aSAlex Lorenz     return It->second;
1422ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1423ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1424ee02499aSAlex Lorenz   return FileID;
1425ee02499aSAlex Lorenz }
1426ee02499aSAlex Lorenz 
1427ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1428ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1429ee02499aSAlex Lorenz   assert(CounterMap);
1430e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1431ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1432ee02499aSAlex Lorenz   Walker.write(OS);
1433ee02499aSAlex Lorenz }
1434ee02499aSAlex Lorenz 
1435ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1436ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1437ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1438ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1439ee02499aSAlex Lorenz   Walker.write(OS);
1440ee02499aSAlex Lorenz }
1441