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"
18bf42cfd7SJustin Bogner #include "llvm/ADT/Optional.h"
19ee02499aSAlex Lorenz #include "llvm/ProfileData/CoverageMapping.h"
20f2cf38e0SAlex Lorenz #include "llvm/ProfileData/CoverageMappingReader.h"
210d9593ddSChandler Carruth #include "llvm/ProfileData/CoverageMappingWriter.h"
220d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
23ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
24ee02499aSAlex Lorenz 
25ee02499aSAlex Lorenz using namespace clang;
26ee02499aSAlex Lorenz using namespace CodeGen;
27ee02499aSAlex Lorenz using namespace llvm::coverage;
28ee02499aSAlex Lorenz 
29ee02499aSAlex Lorenz void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
30ee02499aSAlex Lorenz   SkippedRanges.push_back(Range);
31ee02499aSAlex Lorenz }
32ee02499aSAlex Lorenz 
33ee02499aSAlex Lorenz namespace {
34ee02499aSAlex Lorenz 
35ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter.
3609c7179bSJustin Bogner class SourceMappingRegion {
37ee02499aSAlex Lorenz   Counter Count;
38ee02499aSAlex Lorenz 
39ee02499aSAlex Lorenz   /// \brief The region's starting location.
40bf42cfd7SJustin Bogner   Optional<SourceLocation> LocStart;
41ee02499aSAlex Lorenz 
42ee02499aSAlex Lorenz   /// \brief The region's ending location.
43bf42cfd7SJustin Bogner   Optional<SourceLocation> LocEnd;
44ee02499aSAlex Lorenz 
4509c7179bSJustin Bogner public:
46bf42cfd7SJustin Bogner   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
47bf42cfd7SJustin Bogner                       Optional<SourceLocation> LocEnd)
48bf42cfd7SJustin Bogner       : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
49ee02499aSAlex Lorenz 
50bf42cfd7SJustin Bogner   SourceMappingRegion(SourceMappingRegion &&Region)
51bf42cfd7SJustin Bogner       : Count(std::move(Region.Count)), LocStart(std::move(Region.LocStart)),
52bf42cfd7SJustin Bogner         LocEnd(std::move(Region.LocEnd)) {}
53bf42cfd7SJustin Bogner 
54bf42cfd7SJustin Bogner   SourceMappingRegion &operator=(SourceMappingRegion &&RHS) {
55bf42cfd7SJustin Bogner     Count = std::move(RHS.Count);
56bf42cfd7SJustin Bogner     LocStart = std::move(RHS.LocStart);
57bf42cfd7SJustin Bogner     LocEnd = std::move(RHS.LocEnd);
58bf42cfd7SJustin Bogner     return *this;
59bf42cfd7SJustin Bogner   }
6009c7179bSJustin Bogner 
6109c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
6209c7179bSJustin Bogner 
63bf42cfd7SJustin Bogner   void setCounter(Counter C) { Count = C; }
6409c7179bSJustin Bogner 
65bf42cfd7SJustin Bogner   bool hasStartLoc() const { return LocStart.hasValue(); }
66bf42cfd7SJustin Bogner 
67bf42cfd7SJustin Bogner   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
68bf42cfd7SJustin Bogner 
69bf42cfd7SJustin Bogner   const SourceLocation &getStartLoc() const {
70bf42cfd7SJustin Bogner     assert(LocStart && "Region has no start location");
71bf42cfd7SJustin Bogner     return *LocStart;
7209c7179bSJustin Bogner   }
7309c7179bSJustin Bogner 
74bf42cfd7SJustin Bogner   bool hasEndLoc() const { return LocEnd.hasValue(); }
75ee02499aSAlex Lorenz 
76bf42cfd7SJustin Bogner   void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
77ee02499aSAlex Lorenz 
78bf42cfd7SJustin Bogner   const SourceLocation &getEndLoc() const {
79bf42cfd7SJustin Bogner     assert(LocEnd && "Region has no end location");
80bf42cfd7SJustin Bogner     return *LocEnd;
81ee02499aSAlex Lorenz   }
82ee02499aSAlex Lorenz };
83ee02499aSAlex Lorenz 
84ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different
85ee02499aSAlex Lorenz /// coverage mapping region builders.
86ee02499aSAlex Lorenz class CoverageMappingBuilder {
87ee02499aSAlex Lorenz public:
88ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
89ee02499aSAlex Lorenz   SourceManager &SM;
90ee02499aSAlex Lorenz   const LangOptions &LangOpts;
91ee02499aSAlex Lorenz 
92ee02499aSAlex Lorenz private:
93bf42cfd7SJustin Bogner   /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
94bf42cfd7SJustin Bogner   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
95bf42cfd7SJustin Bogner       FileIDMapping;
96ee02499aSAlex Lorenz 
97ee02499aSAlex Lorenz public:
98ee02499aSAlex Lorenz   /// \brief The coverage mapping regions for this function
99ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
100ee02499aSAlex Lorenz   /// \brief The source mapping regions for this function.
101f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
102ee02499aSAlex Lorenz 
103ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
104ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
105bf42cfd7SJustin Bogner       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
106ee02499aSAlex Lorenz 
107ee02499aSAlex Lorenz   /// \brief Return the precise end location for the given token.
108ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
109bf42cfd7SJustin Bogner     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
110bf42cfd7SJustin Bogner     // macro locations, which we just treat as expanded files.
111bf42cfd7SJustin Bogner     unsigned TokLen =
112bf42cfd7SJustin Bogner         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
113bf42cfd7SJustin Bogner     return Loc.getLocWithOffset(TokLen);
114ee02499aSAlex Lorenz   }
115ee02499aSAlex Lorenz 
116bf42cfd7SJustin Bogner   /// \brief Return the start location of an included file or expanded macro.
117bf42cfd7SJustin Bogner   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
118bf42cfd7SJustin Bogner     if (Loc.isMacroID())
119bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
120bf42cfd7SJustin Bogner     return SM.getLocForStartOfFile(SM.getFileID(Loc));
121ee02499aSAlex Lorenz   }
122ee02499aSAlex Lorenz 
123bf42cfd7SJustin Bogner   /// \brief Return the end location of an included file or expanded macro.
124bf42cfd7SJustin Bogner   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
125bf42cfd7SJustin Bogner     if (Loc.isMacroID())
126bf42cfd7SJustin Bogner       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
127f14b2078SJustin Bogner                                   SM.getFileOffset(Loc));
128bf42cfd7SJustin Bogner     return SM.getLocForEndOfFile(SM.getFileID(Loc));
129bf42cfd7SJustin Bogner   }
130ee02499aSAlex Lorenz 
131bf42cfd7SJustin Bogner   /// \brief Find out where the current file is included or macro is expanded.
132bf42cfd7SJustin Bogner   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
133bf42cfd7SJustin Bogner     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
134bf42cfd7SJustin Bogner                            : SM.getIncludeLoc(SM.getFileID(Loc));
135bf42cfd7SJustin Bogner   }
136bf42cfd7SJustin Bogner 
137682bfbf3SJustin Bogner   /// \brief Return true if \c Loc is a location in a built-in macro.
138682bfbf3SJustin Bogner   bool isInBuiltin(SourceLocation Loc) {
139682bfbf3SJustin Bogner     return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0;
140682bfbf3SJustin Bogner   }
141682bfbf3SJustin Bogner 
142682bfbf3SJustin Bogner   /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
143bf42cfd7SJustin Bogner   SourceLocation getStart(const Stmt *S) {
144bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocStart();
145682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
146bf42cfd7SJustin Bogner       Loc = SM.getImmediateExpansionRange(Loc).first;
147bf42cfd7SJustin Bogner     return Loc;
148bf42cfd7SJustin Bogner   }
149bf42cfd7SJustin Bogner 
150682bfbf3SJustin Bogner   /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
151bf42cfd7SJustin Bogner   SourceLocation getEnd(const Stmt *S) {
152bf42cfd7SJustin Bogner     SourceLocation Loc = S->getLocEnd();
153682bfbf3SJustin Bogner     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
154bf42cfd7SJustin Bogner       Loc = SM.getImmediateExpansionRange(Loc).first;
155f14b2078SJustin Bogner     return getPreciseTokenLocEnd(Loc);
156bf42cfd7SJustin Bogner   }
157bf42cfd7SJustin Bogner 
158bf42cfd7SJustin Bogner   /// \brief Find the set of files we have regions for and assign IDs
159bf42cfd7SJustin Bogner   ///
160bf42cfd7SJustin Bogner   /// Fills \c Mapping with the virtual file mapping needed to write out
161bf42cfd7SJustin Bogner   /// coverage and collects the necessary file information to emit source and
162bf42cfd7SJustin Bogner   /// expansion regions.
163bf42cfd7SJustin Bogner   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
164bf42cfd7SJustin Bogner     FileIDMapping.clear();
165bf42cfd7SJustin Bogner 
166bf42cfd7SJustin Bogner     SmallVector<FileID, 8> Visited;
167bf42cfd7SJustin Bogner     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
168bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
169bf42cfd7SJustin Bogner       SourceLocation Loc = Region.getStartLoc();
170bf42cfd7SJustin Bogner       FileID File = SM.getFileID(Loc);
171bf42cfd7SJustin Bogner       if (std::find(Visited.begin(), Visited.end(), File) != Visited.end())
172bf42cfd7SJustin Bogner         continue;
173bf42cfd7SJustin Bogner       Visited.push_back(File);
174bf42cfd7SJustin Bogner 
175bf42cfd7SJustin Bogner       unsigned Depth = 0;
176bf42cfd7SJustin Bogner       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
177bf42cfd7SJustin Bogner            !Parent.isInvalid(); Parent = getIncludeOrExpansionLoc(Parent))
178bf42cfd7SJustin Bogner         ++Depth;
179bf42cfd7SJustin Bogner       FileLocs.push_back(std::make_pair(Loc, Depth));
180bf42cfd7SJustin Bogner     }
181bf42cfd7SJustin Bogner     std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
182bf42cfd7SJustin Bogner 
183bf42cfd7SJustin Bogner     for (const auto &FL : FileLocs) {
184bf42cfd7SJustin Bogner       SourceLocation Loc = FL.first;
185bf42cfd7SJustin Bogner       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
186ee02499aSAlex Lorenz       auto Entry = SM.getFileEntryForID(SpellingFile);
187ee02499aSAlex Lorenz       if (!Entry)
188bf42cfd7SJustin Bogner         continue;
189ee02499aSAlex Lorenz 
190bf42cfd7SJustin Bogner       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
191bf42cfd7SJustin Bogner       Mapping.push_back(CVM.getFileID(Entry));
192bf42cfd7SJustin Bogner     }
193ee02499aSAlex Lorenz   }
194ee02499aSAlex Lorenz 
195bf42cfd7SJustin Bogner   /// \brief Get the coverage mapping file ID for \c Loc.
196bf42cfd7SJustin Bogner   ///
197bf42cfd7SJustin Bogner   /// If such file id doesn't exist, return None.
198bf42cfd7SJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
199bf42cfd7SJustin Bogner     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
200bf42cfd7SJustin Bogner     if (Mapping != FileIDMapping.end())
201bf42cfd7SJustin Bogner       return Mapping->second.first;
202903678caSJustin Bogner     return None;
203ee02499aSAlex Lorenz   }
204ee02499aSAlex Lorenz 
205ee02499aSAlex Lorenz   /// \brief Return true if the given clang's file id has a corresponding
206ee02499aSAlex Lorenz   /// coverage file id.
207ee02499aSAlex Lorenz   bool hasExistingCoverageFileID(FileID File) const {
208ee02499aSAlex Lorenz     return FileIDMapping.count(File);
209ee02499aSAlex Lorenz   }
210ee02499aSAlex Lorenz 
211ee02499aSAlex Lorenz   /// \brief Gather all the regions that were skipped by the preprocessor
212ee02499aSAlex Lorenz   /// using the constructs like #if.
213ee02499aSAlex Lorenz   void gatherSkippedRegions() {
214ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
215ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
216ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
217ee02499aSAlex Lorenz     FileLineRanges.resize(
218ee02499aSAlex Lorenz         FileIDMapping.size(),
219ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
220ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
221ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
222ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
223ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
224ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
225ee02499aSAlex Lorenz     }
226ee02499aSAlex Lorenz 
227ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
228ee02499aSAlex Lorenz     for (const auto &I : SkippedRanges) {
229ee02499aSAlex Lorenz       auto LocStart = I.getBegin();
230ee02499aSAlex Lorenz       auto LocEnd = I.getEnd();
231bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
232bf42cfd7SJustin Bogner              "region spans multiple files");
233ee02499aSAlex Lorenz 
234bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
235903678caSJustin Bogner       if (!CovFileID)
236ee02499aSAlex Lorenz         continue;
237ee02499aSAlex Lorenz       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
238ee02499aSAlex Lorenz       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
239ee02499aSAlex Lorenz       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
240ee02499aSAlex Lorenz       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
241fd34280bSJustin Bogner       auto Region = CounterMappingRegion::makeSkipped(
242fd34280bSJustin Bogner           *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
243ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
244ee02499aSAlex Lorenz       // the souce code of this function.
245903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
246903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
247ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
248ee02499aSAlex Lorenz     }
249ee02499aSAlex Lorenz   }
250ee02499aSAlex Lorenz 
251ee02499aSAlex Lorenz   /// \brief Generate the coverage counter mapping regions from collected
252ee02499aSAlex Lorenz   /// source regions.
253ee02499aSAlex Lorenz   void emitSourceRegions() {
254bf42cfd7SJustin Bogner     for (const auto &Region : SourceRegions) {
255bf42cfd7SJustin Bogner       assert(Region.hasEndLoc() && "incomplete region");
256ee02499aSAlex Lorenz 
257bf42cfd7SJustin Bogner       SourceLocation LocStart = Region.getStartLoc();
258bf42cfd7SJustin Bogner       assert(!SM.getFileID(LocStart).isInvalid() && "region in invalid file");
259f59329b0SJustin Bogner 
260bf42cfd7SJustin Bogner       auto CovFileID = getCoverageFileID(LocStart);
261bf42cfd7SJustin Bogner       // Ignore regions that don't have a file, such as builtin macros.
262bf42cfd7SJustin Bogner       if (!CovFileID)
263ee02499aSAlex Lorenz         continue;
264ee02499aSAlex Lorenz 
265f14b2078SJustin Bogner       SourceLocation LocEnd = Region.getEndLoc();
266bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
267bf42cfd7SJustin Bogner              "region spans multiple files");
268bf42cfd7SJustin Bogner 
269f59329b0SJustin Bogner       // Find the spilling locations for the mapping region.
270ee02499aSAlex Lorenz       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
271ee02499aSAlex Lorenz       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
272ee02499aSAlex Lorenz       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
273ee02499aSAlex Lorenz       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
274ee02499aSAlex Lorenz 
275bf42cfd7SJustin Bogner       assert(LineStart <= LineEnd && "region start and end out of order");
276bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeRegion(
277bf42cfd7SJustin Bogner           Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
278bf42cfd7SJustin Bogner           ColumnEnd));
279bf42cfd7SJustin Bogner     }
280bf42cfd7SJustin Bogner   }
281bf42cfd7SJustin Bogner 
282bf42cfd7SJustin Bogner   /// \brief Generate expansion regions for each virtual file we've seen.
283bf42cfd7SJustin Bogner   void emitExpansionRegions() {
284bf42cfd7SJustin Bogner     for (const auto &FM : FileIDMapping) {
285bf42cfd7SJustin Bogner       SourceLocation ExpandedLoc = FM.second.second;
286bf42cfd7SJustin Bogner       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
287bf42cfd7SJustin Bogner       if (ParentLoc.isInvalid())
288ee02499aSAlex Lorenz         continue;
289ee02499aSAlex Lorenz 
290bf42cfd7SJustin Bogner       auto ParentFileID = getCoverageFileID(ParentLoc);
291bf42cfd7SJustin Bogner       if (!ParentFileID)
292bf42cfd7SJustin Bogner         continue;
293bf42cfd7SJustin Bogner       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
294bf42cfd7SJustin Bogner       assert(ExpandedFileID && "expansion in uncovered file");
295bf42cfd7SJustin Bogner 
296bf42cfd7SJustin Bogner       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
297bf42cfd7SJustin Bogner       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
298bf42cfd7SJustin Bogner              "region spans multiple files");
299bf42cfd7SJustin Bogner 
300bf42cfd7SJustin Bogner       unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
301bf42cfd7SJustin Bogner       unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
302bf42cfd7SJustin Bogner       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
303bf42cfd7SJustin Bogner       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
304bf42cfd7SJustin Bogner 
305bf42cfd7SJustin Bogner       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
306bf42cfd7SJustin Bogner           *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
307fd34280bSJustin Bogner           ColumnEnd));
308ee02499aSAlex Lorenz     }
309ee02499aSAlex Lorenz   }
310ee02499aSAlex Lorenz };
311ee02499aSAlex Lorenz 
312ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that
313ee02499aSAlex Lorenz /// are not emitted.
314ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
315ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
316ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
317ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
318ee02499aSAlex Lorenz 
319ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
320ee02499aSAlex Lorenz     if (!D->hasBody())
321ee02499aSAlex Lorenz       return;
322ee02499aSAlex Lorenz     auto Body = D->getBody();
323bf42cfd7SJustin Bogner     SourceRegions.emplace_back(Counter(), getStart(Body), getEnd(Body));
324ee02499aSAlex Lorenz   }
325ee02499aSAlex Lorenz 
326ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
327ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
328ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
329bf42cfd7SJustin Bogner     gatherFileIDs(FileIDMapping);
330bf42cfd7SJustin Bogner     emitSourceRegions();
331ee02499aSAlex Lorenz 
3325fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
333ee02499aSAlex Lorenz     Writer.write(OS);
334ee02499aSAlex Lorenz   }
335ee02499aSAlex Lorenz };
336ee02499aSAlex Lorenz 
337ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map
338ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
339ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
340ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
341ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
342ee02499aSAlex Lorenz   /// \brief The map of statements to count values.
343ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
344ee02499aSAlex Lorenz 
345bf42cfd7SJustin Bogner   /// \brief A stack of currently live regions.
346bf42cfd7SJustin Bogner   std::vector<SourceMappingRegion> RegionStack;
347ee02499aSAlex Lorenz 
348ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
349ee02499aSAlex Lorenz 
350bf42cfd7SJustin Bogner   /// \brief A location in the most recently visited file or macro.
351bf42cfd7SJustin Bogner   ///
352bf42cfd7SJustin Bogner   /// This is used to adjust the active source regions appropriately when
353bf42cfd7SJustin Bogner   /// expressions cross file or macro boundaries.
354bf42cfd7SJustin Bogner   SourceLocation MostRecentLocation;
355bf42cfd7SJustin Bogner 
356bf42cfd7SJustin Bogner   /// \brief Return a counter for the subtraction of \c RHS from \c LHS
357ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
358ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
359ee02499aSAlex Lorenz   }
360ee02499aSAlex Lorenz 
361bf42cfd7SJustin Bogner   /// \brief Return a counter for the sum of \c LHS and \c RHS.
362ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
363ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
364ee02499aSAlex Lorenz   }
365ee02499aSAlex Lorenz 
366bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3) {
367bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2), C3);
368bf42cfd7SJustin Bogner   }
369bf42cfd7SJustin Bogner 
370bf42cfd7SJustin Bogner   Counter addCounters(Counter C1, Counter C2, Counter C3, Counter C4) {
371bf42cfd7SJustin Bogner     return addCounters(addCounters(C1, C2, C3), C4);
372bf42cfd7SJustin Bogner   }
373bf42cfd7SJustin Bogner 
374ee02499aSAlex Lorenz   /// \brief Return the region counter for the given statement.
375bf42cfd7SJustin Bogner   ///
376ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
377bf42cfd7SJustin Bogner   Counter getRegionCounter(const Stmt *S) {
378bf42cfd7SJustin Bogner     return Counter::getCounter(CounterMap[S]);
379ee02499aSAlex Lorenz   }
380ee02499aSAlex Lorenz 
381bf42cfd7SJustin Bogner   /// \brief Push a region onto the stack.
382bf42cfd7SJustin Bogner   ///
383bf42cfd7SJustin Bogner   /// Returns the index on the stack where the region was pushed. This can be
384bf42cfd7SJustin Bogner   /// used with popRegions to exit a "scope", ending the region that was pushed.
385bf42cfd7SJustin Bogner   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
386bf42cfd7SJustin Bogner                     Optional<SourceLocation> EndLoc = None) {
387bf42cfd7SJustin Bogner     if (StartLoc)
388bf42cfd7SJustin Bogner       MostRecentLocation = *StartLoc;
389bf42cfd7SJustin Bogner     RegionStack.emplace_back(Count, StartLoc, EndLoc);
390ee02499aSAlex Lorenz 
391bf42cfd7SJustin Bogner     return RegionStack.size() - 1;
392ee02499aSAlex Lorenz   }
393ee02499aSAlex Lorenz 
394bf42cfd7SJustin Bogner   /// \brief Pop regions from the stack into the function's list of regions.
395bf42cfd7SJustin Bogner   ///
396bf42cfd7SJustin Bogner   /// Adds all regions from \c ParentIndex to the top of the stack to the
397bf42cfd7SJustin Bogner   /// function's \c SourceRegions.
398bf42cfd7SJustin Bogner   void popRegions(size_t ParentIndex) {
399bf42cfd7SJustin Bogner     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
400bf42cfd7SJustin Bogner     while (RegionStack.size() > ParentIndex) {
401bf42cfd7SJustin Bogner       SourceMappingRegion &Region = RegionStack.back();
402bf42cfd7SJustin Bogner       if (Region.hasStartLoc()) {
403bf42cfd7SJustin Bogner         SourceLocation StartLoc = Region.getStartLoc();
404bf42cfd7SJustin Bogner         SourceLocation EndLoc = Region.hasEndLoc()
405bf42cfd7SJustin Bogner                                     ? Region.getEndLoc()
406bf42cfd7SJustin Bogner                                     : RegionStack[ParentIndex].getEndLoc();
407bf42cfd7SJustin Bogner         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
408bf42cfd7SJustin Bogner           // The region ends in a nested file or macro expansion. Create a
409bf42cfd7SJustin Bogner           // separate region for each expansion.
410bf42cfd7SJustin Bogner           SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
411bf42cfd7SJustin Bogner           assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
412bf42cfd7SJustin Bogner 
413bf42cfd7SJustin Bogner           SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
414bf42cfd7SJustin Bogner 
415f14b2078SJustin Bogner           EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
416*dceaaadfSJustin Bogner           if (EndLoc.isInvalid())
417*dceaaadfSJustin Bogner             llvm::report_fatal_error("File exit not handled before popRegions");
418bf42cfd7SJustin Bogner         }
419bf42cfd7SJustin Bogner         Region.setEndLoc(EndLoc);
420bf42cfd7SJustin Bogner 
421bf42cfd7SJustin Bogner         MostRecentLocation = EndLoc;
422bf42cfd7SJustin Bogner         // If this region happens to span an entire expansion, we need to make
423bf42cfd7SJustin Bogner         // sure we don't overlap the parent region with it.
424bf42cfd7SJustin Bogner         if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
425bf42cfd7SJustin Bogner             EndLoc == getEndOfFileOrMacro(EndLoc))
426bf42cfd7SJustin Bogner           MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
427bf42cfd7SJustin Bogner 
428bf42cfd7SJustin Bogner         assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
429bf42cfd7SJustin Bogner         SourceRegions.push_back(std::move(Region));
430bf42cfd7SJustin Bogner       }
431bf42cfd7SJustin Bogner       RegionStack.pop_back();
432bf42cfd7SJustin Bogner     }
433ee02499aSAlex Lorenz   }
434ee02499aSAlex Lorenz 
435bf42cfd7SJustin Bogner   /// \brief Return the currently active region.
436bf42cfd7SJustin Bogner   SourceMappingRegion &getRegion() {
437bf42cfd7SJustin Bogner     assert(!RegionStack.empty() && "statement has no region");
438bf42cfd7SJustin Bogner     return RegionStack.back();
439ee02499aSAlex Lorenz   }
440ee02499aSAlex Lorenz 
441bf42cfd7SJustin Bogner   /// \brief Propagate counts through the children of \c S.
442bf42cfd7SJustin Bogner   Counter propagateCounts(Counter TopCount, const Stmt *S) {
443bf42cfd7SJustin Bogner     size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
444bf42cfd7SJustin Bogner     Visit(S);
445bf42cfd7SJustin Bogner     Counter ExitCount = getRegion().getCounter();
446bf42cfd7SJustin Bogner     popRegions(Index);
447bf42cfd7SJustin Bogner     return ExitCount;
448ee02499aSAlex Lorenz   }
449ee02499aSAlex Lorenz 
450bf42cfd7SJustin Bogner   /// \brief Adjust the most recently visited location to \c EndLoc.
451bf42cfd7SJustin Bogner   ///
452bf42cfd7SJustin Bogner   /// This should be used after visiting any statements in non-source order.
453bf42cfd7SJustin Bogner   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
454bf42cfd7SJustin Bogner     MostRecentLocation = EndLoc;
45596ae73f7SJustin Bogner     // Avoid adding duplicate regions if we have a completed region on the top
45696ae73f7SJustin Bogner     // of the stack and are adjusting to the end of a virtual file.
45796ae73f7SJustin Bogner     if (getRegion().hasEndLoc() &&
45896ae73f7SJustin Bogner         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation))
459bf42cfd7SJustin Bogner       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
460ee02499aSAlex Lorenz   }
461ee02499aSAlex Lorenz 
462bf42cfd7SJustin Bogner   /// \brief Check whether \c Loc is included or expanded from \c Parent.
463bf42cfd7SJustin Bogner   bool isNestedIn(SourceLocation Loc, FileID Parent) {
464bf42cfd7SJustin Bogner     do {
465bf42cfd7SJustin Bogner       Loc = getIncludeOrExpansionLoc(Loc);
466bf42cfd7SJustin Bogner       if (Loc.isInvalid())
467bf42cfd7SJustin Bogner         return false;
468bf42cfd7SJustin Bogner     } while (!SM.isInFileID(Loc, Parent));
469bf42cfd7SJustin Bogner     return true;
470ee02499aSAlex Lorenz   }
471ee02499aSAlex Lorenz 
472bf42cfd7SJustin Bogner   /// \brief Adjust regions and state when \c NewLoc exits a file.
473bf42cfd7SJustin Bogner   ///
474bf42cfd7SJustin Bogner   /// If moving from our most recently tracked location to \c NewLoc exits any
475bf42cfd7SJustin Bogner   /// files, this adjusts our current region stack and creates the file regions
476bf42cfd7SJustin Bogner   /// for the exited file.
477bf42cfd7SJustin Bogner   void handleFileExit(SourceLocation NewLoc) {
478e44dd6dbSJustin Bogner     if (NewLoc.isInvalid() ||
479e44dd6dbSJustin Bogner         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
480bf42cfd7SJustin Bogner       return;
481bf42cfd7SJustin Bogner 
482bf42cfd7SJustin Bogner     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
483bf42cfd7SJustin Bogner     // find the common ancestor.
484bf42cfd7SJustin Bogner     SourceLocation LCA = NewLoc;
485bf42cfd7SJustin Bogner     FileID ParentFile = SM.getFileID(LCA);
486bf42cfd7SJustin Bogner     while (!isNestedIn(MostRecentLocation, ParentFile)) {
487bf42cfd7SJustin Bogner       LCA = getIncludeOrExpansionLoc(LCA);
488bf42cfd7SJustin Bogner       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
489bf42cfd7SJustin Bogner         // Since there isn't a common ancestor, no file was exited. We just need
490bf42cfd7SJustin Bogner         // to adjust our location to the new file.
491bf42cfd7SJustin Bogner         MostRecentLocation = NewLoc;
492bf42cfd7SJustin Bogner         return;
493bf42cfd7SJustin Bogner       }
494bf42cfd7SJustin Bogner       ParentFile = SM.getFileID(LCA);
495ee02499aSAlex Lorenz     }
496ee02499aSAlex Lorenz 
497bf42cfd7SJustin Bogner     llvm::SmallSet<SourceLocation, 8> StartLocs;
498bf42cfd7SJustin Bogner     Optional<Counter> ParentCounter;
499bf42cfd7SJustin Bogner     for (auto I = RegionStack.rbegin(), E = RegionStack.rend(); I != E; ++I) {
500bf42cfd7SJustin Bogner       if (!I->hasStartLoc())
501bf42cfd7SJustin Bogner         continue;
502bf42cfd7SJustin Bogner       SourceLocation Loc = I->getStartLoc();
503bf42cfd7SJustin Bogner       if (!isNestedIn(Loc, ParentFile)) {
504bf42cfd7SJustin Bogner         ParentCounter = I->getCounter();
505bf42cfd7SJustin Bogner         break;
506ee02499aSAlex Lorenz       }
507bf42cfd7SJustin Bogner 
508bf42cfd7SJustin Bogner       while (!SM.isInFileID(Loc, ParentFile)) {
509bf42cfd7SJustin Bogner         // The most nested region for each start location is the one with the
510bf42cfd7SJustin Bogner         // correct count. We avoid creating redundant regions by stopping once
511bf42cfd7SJustin Bogner         // we've seen this region.
512bf42cfd7SJustin Bogner         if (StartLocs.insert(Loc).second)
513bf42cfd7SJustin Bogner           SourceRegions.emplace_back(I->getCounter(), Loc,
514bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
515bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
516ee02499aSAlex Lorenz       }
517bf42cfd7SJustin Bogner       I->setStartLoc(getPreciseTokenLocEnd(Loc));
518bf42cfd7SJustin Bogner     }
519bf42cfd7SJustin Bogner 
520bf42cfd7SJustin Bogner     if (ParentCounter) {
521bf42cfd7SJustin Bogner       // If the file is contained completely by another region and doesn't
522bf42cfd7SJustin Bogner       // immediately start its own region, the whole file gets a region
523bf42cfd7SJustin Bogner       // corresponding to the parent.
524bf42cfd7SJustin Bogner       SourceLocation Loc = MostRecentLocation;
525bf42cfd7SJustin Bogner       while (isNestedIn(Loc, ParentFile)) {
526bf42cfd7SJustin Bogner         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
527bf42cfd7SJustin Bogner         if (StartLocs.insert(FileStart).second)
528bf42cfd7SJustin Bogner           SourceRegions.emplace_back(*ParentCounter, FileStart,
529bf42cfd7SJustin Bogner                                      getEndOfFileOrMacro(Loc));
530bf42cfd7SJustin Bogner         Loc = getIncludeOrExpansionLoc(Loc);
531bf42cfd7SJustin Bogner       }
532bf42cfd7SJustin Bogner     }
533bf42cfd7SJustin Bogner 
534bf42cfd7SJustin Bogner     MostRecentLocation = NewLoc;
535bf42cfd7SJustin Bogner   }
536bf42cfd7SJustin Bogner 
537bf42cfd7SJustin Bogner   /// \brief Ensure that \c S is included in the current region.
538bf42cfd7SJustin Bogner   void extendRegion(const Stmt *S) {
539bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
540bf42cfd7SJustin Bogner     SourceLocation StartLoc = getStart(S);
541bf42cfd7SJustin Bogner 
542bf42cfd7SJustin Bogner     handleFileExit(StartLoc);
543bf42cfd7SJustin Bogner     if (!Region.hasStartLoc())
544bf42cfd7SJustin Bogner       Region.setStartLoc(StartLoc);
545bf42cfd7SJustin Bogner   }
546bf42cfd7SJustin Bogner 
547bf42cfd7SJustin Bogner   /// \brief Mark \c S as a terminator, starting a zero region.
548bf42cfd7SJustin Bogner   void terminateRegion(const Stmt *S) {
549bf42cfd7SJustin Bogner     extendRegion(S);
550bf42cfd7SJustin Bogner     SourceMappingRegion &Region = getRegion();
551bf42cfd7SJustin Bogner     if (!Region.hasEndLoc())
552bf42cfd7SJustin Bogner       Region.setEndLoc(getEnd(S));
553bf42cfd7SJustin Bogner     pushRegion(Counter::getZero());
554bf42cfd7SJustin Bogner   }
555ee02499aSAlex Lorenz 
556ee02499aSAlex Lorenz   /// \brief Keep counts of breaks and continues inside loops.
557ee02499aSAlex Lorenz   struct BreakContinue {
558ee02499aSAlex Lorenz     Counter BreakCount;
559ee02499aSAlex Lorenz     Counter ContinueCount;
560ee02499aSAlex Lorenz   };
561ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
562ee02499aSAlex Lorenz 
563ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
564ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
565e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
566ee02499aSAlex Lorenz       const LangOptions &LangOpts)
567e5ee6c58SJustin Bogner       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
568ee02499aSAlex Lorenz 
569ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
570ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
571ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
572bf42cfd7SJustin Bogner     gatherFileIDs(VirtualFileMapping);
573bf42cfd7SJustin Bogner     emitSourceRegions();
574bf42cfd7SJustin Bogner     emitExpansionRegions();
575ee02499aSAlex Lorenz     gatherSkippedRegions();
576ee02499aSAlex Lorenz 
5774da909b2SJustin Bogner     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
5784da909b2SJustin Bogner                                  MappingRegions);
579ee02499aSAlex Lorenz     Writer.write(OS);
580ee02499aSAlex Lorenz   }
581ee02499aSAlex Lorenz 
582ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
583bf42cfd7SJustin Bogner     if (!S->getLocStart().isInvalid())
584bf42cfd7SJustin Bogner       extendRegion(S);
585642f173aSBenjamin Kramer     for (const Stmt *Child : S->children())
586642f173aSBenjamin Kramer       if (Child)
587642f173aSBenjamin Kramer         this->Visit(Child);
588bf42cfd7SJustin Bogner     handleFileExit(getEnd(S));
589ee02499aSAlex Lorenz   }
590ee02499aSAlex Lorenz 
591ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
592bf42cfd7SJustin Bogner     Stmt *Body = D->getBody();
593bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(Body), Body);
594ee02499aSAlex Lorenz   }
595ee02499aSAlex Lorenz 
596ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
597bf42cfd7SJustin Bogner     extendRegion(S);
598ee02499aSAlex Lorenz     if (S->getRetValue())
599ee02499aSAlex Lorenz       Visit(S->getRetValue());
600bf42cfd7SJustin Bogner     terminateRegion(S);
601ee02499aSAlex Lorenz   }
602ee02499aSAlex Lorenz 
603f959febfSJustin Bogner   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
604f959febfSJustin Bogner     extendRegion(E);
605f959febfSJustin Bogner     if (E->getSubExpr())
606f959febfSJustin Bogner       Visit(E->getSubExpr());
607f959febfSJustin Bogner     terminateRegion(E);
608f959febfSJustin Bogner   }
609f959febfSJustin Bogner 
610bf42cfd7SJustin Bogner   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
611ee02499aSAlex Lorenz 
612ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
613bf42cfd7SJustin Bogner     SourceLocation Start = getStart(S);
614bf42cfd7SJustin Bogner     // We can't extendRegion here or we risk overlapping with our new region.
615bf42cfd7SJustin Bogner     handleFileExit(Start);
616bf42cfd7SJustin Bogner     pushRegion(getRegionCounter(S), Start);
617ee02499aSAlex Lorenz     Visit(S->getSubStmt());
618ee02499aSAlex Lorenz   }
619ee02499aSAlex Lorenz 
620ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
621ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
622ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
623bf42cfd7SJustin Bogner         BreakContinueStack.back().BreakCount, getRegion().getCounter());
624bf42cfd7SJustin Bogner     terminateRegion(S);
625ee02499aSAlex Lorenz   }
626ee02499aSAlex Lorenz 
627ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
628ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
629ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
630bf42cfd7SJustin Bogner         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
631bf42cfd7SJustin Bogner     terminateRegion(S);
632ee02499aSAlex Lorenz   }
633ee02499aSAlex Lorenz 
634ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
635bf42cfd7SJustin Bogner     extendRegion(S);
636ee02499aSAlex Lorenz 
637bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
638bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
639bf42cfd7SJustin Bogner 
640bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
641bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
642bf42cfd7SJustin Bogner     extendRegion(S->getBody());
643bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
644ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
645bf42cfd7SJustin Bogner 
646bf42cfd7SJustin Bogner     // Go back to handle the condition.
647bf42cfd7SJustin Bogner     Counter CondCount =
648bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
649bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
650bf42cfd7SJustin Bogner     adjustForOutOfOrderTraversal(getEnd(S));
651bf42cfd7SJustin Bogner 
652bf42cfd7SJustin Bogner     Counter OutCount =
653bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
654bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
655bf42cfd7SJustin Bogner       pushRegion(OutCount);
656ee02499aSAlex Lorenz   }
657ee02499aSAlex Lorenz 
658ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
659bf42cfd7SJustin Bogner     extendRegion(S);
660ee02499aSAlex Lorenz 
661bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
662bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
663bf42cfd7SJustin Bogner 
664bf42cfd7SJustin Bogner     BreakContinueStack.push_back(BreakContinue());
665bf42cfd7SJustin Bogner     extendRegion(S->getBody());
666bf42cfd7SJustin Bogner     Counter BackedgeCount =
667bf42cfd7SJustin Bogner         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
668ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
669bf42cfd7SJustin Bogner 
670bf42cfd7SJustin Bogner     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
671bf42cfd7SJustin Bogner     propagateCounts(CondCount, S->getCond());
672bf42cfd7SJustin Bogner 
673bf42cfd7SJustin Bogner     Counter OutCount =
674bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
675bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
676bf42cfd7SJustin Bogner       pushRegion(OutCount);
677ee02499aSAlex Lorenz   }
678ee02499aSAlex Lorenz 
679ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
680bf42cfd7SJustin Bogner     extendRegion(S);
681ee02499aSAlex Lorenz     if (S->getInit())
682ee02499aSAlex Lorenz       Visit(S->getInit());
683ee02499aSAlex Lorenz 
684bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
685bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
686bf42cfd7SJustin Bogner 
687bf42cfd7SJustin Bogner     // Handle the body first so that we can get the backedge count.
688ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
689bf42cfd7SJustin Bogner     extendRegion(S->getBody());
690bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
691bf42cfd7SJustin Bogner     BreakContinue BC = BreakContinueStack.pop_back_val();
692ee02499aSAlex Lorenz 
693ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
694ee02499aSAlex Lorenz     // the count for all the continue statements.
695bf42cfd7SJustin Bogner     if (const Stmt *Inc = S->getInc())
696bf42cfd7SJustin Bogner       propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
697bf42cfd7SJustin Bogner 
698bf42cfd7SJustin Bogner     // Go back to handle the condition.
699bf42cfd7SJustin Bogner     Counter CondCount =
700bf42cfd7SJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
701bf42cfd7SJustin Bogner     if (const Expr *Cond = S->getCond()) {
702bf42cfd7SJustin Bogner       propagateCounts(CondCount, Cond);
703bf42cfd7SJustin Bogner       adjustForOutOfOrderTraversal(getEnd(S));
704ee02499aSAlex Lorenz     }
705ee02499aSAlex Lorenz 
706bf42cfd7SJustin Bogner     Counter OutCount =
707bf42cfd7SJustin Bogner         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
708bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
709bf42cfd7SJustin Bogner       pushRegion(OutCount);
710ee02499aSAlex Lorenz   }
711ee02499aSAlex Lorenz 
712ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
713bf42cfd7SJustin Bogner     extendRegion(S);
714bf42cfd7SJustin Bogner     Visit(S->getLoopVarStmt());
715ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
716bf42cfd7SJustin Bogner 
717bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
718bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
719bf42cfd7SJustin Bogner 
720ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
721bf42cfd7SJustin Bogner     extendRegion(S->getBody());
722bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
723ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
724bf42cfd7SJustin Bogner 
7251587432dSJustin Bogner     Counter LoopCount =
7261587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
7271587432dSJustin Bogner     Counter OutCount =
7281587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
729bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
730bf42cfd7SJustin Bogner       pushRegion(OutCount);
731ee02499aSAlex Lorenz   }
732ee02499aSAlex Lorenz 
733ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
734bf42cfd7SJustin Bogner     extendRegion(S);
735ee02499aSAlex Lorenz     Visit(S->getElement());
736bf42cfd7SJustin Bogner 
737bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
738bf42cfd7SJustin Bogner     Counter BodyCount = getRegionCounter(S);
739bf42cfd7SJustin Bogner 
740ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
741bf42cfd7SJustin Bogner     extendRegion(S->getBody());
742bf42cfd7SJustin Bogner     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
743ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
744bf42cfd7SJustin Bogner 
7451587432dSJustin Bogner     Counter LoopCount =
7461587432dSJustin Bogner         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
7471587432dSJustin Bogner     Counter OutCount =
7481587432dSJustin Bogner         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
749bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
750bf42cfd7SJustin Bogner       pushRegion(OutCount);
751ee02499aSAlex Lorenz   }
752ee02499aSAlex Lorenz 
753ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
754bf42cfd7SJustin Bogner     extendRegion(S);
755ee02499aSAlex Lorenz     Visit(S->getCond());
756bf42cfd7SJustin Bogner 
757ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
758bf42cfd7SJustin Bogner 
759bf42cfd7SJustin Bogner     const Stmt *Body = S->getBody();
760bf42cfd7SJustin Bogner     extendRegion(Body);
761bf42cfd7SJustin Bogner     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
762bf42cfd7SJustin Bogner       if (!CS->body_empty()) {
763bf42cfd7SJustin Bogner         // The body of the switch needs a zero region so that fallthrough counts
764bf42cfd7SJustin Bogner         // behave correctly, but it would be misleading to include the braces of
765bf42cfd7SJustin Bogner         // the compound statement in the zeroed area, so we need to handle this
766bf42cfd7SJustin Bogner         // specially.
767bf42cfd7SJustin Bogner         size_t Index =
768bf42cfd7SJustin Bogner             pushRegion(Counter::getZero(), getStart(CS->body_front()),
769bf42cfd7SJustin Bogner                        getEnd(CS->body_back()));
770b5841332SRichard Trieu         for (const auto *Child : CS->children())
771bf42cfd7SJustin Bogner           Visit(Child);
772bf42cfd7SJustin Bogner         popRegions(Index);
773ee02499aSAlex Lorenz       }
774bf42cfd7SJustin Bogner     } else
775bf42cfd7SJustin Bogner       propagateCounts(Counter::getZero(), Body);
776ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
777bf42cfd7SJustin Bogner 
778ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
779ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
780ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
781bf42cfd7SJustin Bogner 
782bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
783bf42cfd7SJustin Bogner     pushRegion(ExitCount);
784ee02499aSAlex Lorenz   }
785ee02499aSAlex Lorenz 
786bf42cfd7SJustin Bogner   void VisitSwitchCase(const SwitchCase *S) {
787bf42cfd7SJustin Bogner     extendRegion(S);
788ee02499aSAlex Lorenz 
789bf42cfd7SJustin Bogner     SourceMappingRegion &Parent = getRegion();
790bf42cfd7SJustin Bogner 
791bf42cfd7SJustin Bogner     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
792bf42cfd7SJustin Bogner     // Reuse the existing region if it starts at our label. This is typical of
793bf42cfd7SJustin Bogner     // the first case in a switch.
794bf42cfd7SJustin Bogner     if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
795bf42cfd7SJustin Bogner       Parent.setCounter(Count);
796bf42cfd7SJustin Bogner     else
797bf42cfd7SJustin Bogner       pushRegion(Count, getStart(S));
798bf42cfd7SJustin Bogner 
799bf42cfd7SJustin Bogner     if (const CaseStmt *CS = dyn_cast<CaseStmt>(S)) {
800bf42cfd7SJustin Bogner       Visit(CS->getLHS());
801bf42cfd7SJustin Bogner       if (const Expr *RHS = CS->getRHS())
802bf42cfd7SJustin Bogner         Visit(RHS);
803bf42cfd7SJustin Bogner     }
804ee02499aSAlex Lorenz     Visit(S->getSubStmt());
805ee02499aSAlex Lorenz   }
806ee02499aSAlex Lorenz 
807ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
808bf42cfd7SJustin Bogner     extendRegion(S);
809055ebc34SJustin Bogner     // Extend into the condition before we propagate through it below - this is
810055ebc34SJustin Bogner     // needed to handle macros that generate the "if" but not the condition.
811055ebc34SJustin Bogner     extendRegion(S->getCond());
812ee02499aSAlex Lorenz 
813bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
814bf42cfd7SJustin Bogner     Counter ThenCount = getRegionCounter(S);
815ee02499aSAlex Lorenz 
81691f2e3c9SJustin Bogner     // Emitting a counter for the condition makes it easier to interpret the
81791f2e3c9SJustin Bogner     // counter for the body when looking at the coverage.
81891f2e3c9SJustin Bogner     propagateCounts(ParentCount, S->getCond());
81991f2e3c9SJustin Bogner 
820bf42cfd7SJustin Bogner     extendRegion(S->getThen());
821bf42cfd7SJustin Bogner     Counter OutCount = propagateCounts(ThenCount, S->getThen());
822bf42cfd7SJustin Bogner 
823bf42cfd7SJustin Bogner     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
824bf42cfd7SJustin Bogner     if (const Stmt *Else = S->getElse()) {
825bf42cfd7SJustin Bogner       extendRegion(S->getElse());
826bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
827bf42cfd7SJustin Bogner     } else
828bf42cfd7SJustin Bogner       OutCount = addCounters(OutCount, ElseCount);
829bf42cfd7SJustin Bogner 
830bf42cfd7SJustin Bogner     if (OutCount != ParentCount)
831bf42cfd7SJustin Bogner       pushRegion(OutCount);
832ee02499aSAlex Lorenz   }
833ee02499aSAlex Lorenz 
834ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
835bf42cfd7SJustin Bogner     extendRegion(S);
836ee02499aSAlex Lorenz     Visit(S->getTryBlock());
837ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
838ee02499aSAlex Lorenz       Visit(S->getHandler(I));
839bf42cfd7SJustin Bogner 
840bf42cfd7SJustin Bogner     Counter ExitCount = getRegionCounter(S);
841bf42cfd7SJustin Bogner     pushRegion(ExitCount);
842ee02499aSAlex Lorenz   }
843ee02499aSAlex Lorenz 
844ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
845bf42cfd7SJustin Bogner     extendRegion(S);
846bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
847ee02499aSAlex Lorenz   }
848ee02499aSAlex Lorenz 
849ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
850bf42cfd7SJustin Bogner     extendRegion(E);
851ee02499aSAlex Lorenz 
852bf42cfd7SJustin Bogner     Counter ParentCount = getRegion().getCounter();
853bf42cfd7SJustin Bogner     Counter TrueCount = getRegionCounter(E);
854ee02499aSAlex Lorenz 
855e3654ce7SJustin Bogner     Visit(E->getCond());
856e3654ce7SJustin Bogner 
857e3654ce7SJustin Bogner     if (!isa<BinaryConditionalOperator>(E)) {
858e3654ce7SJustin Bogner       extendRegion(E->getTrueExpr());
859bf42cfd7SJustin Bogner       propagateCounts(TrueCount, E->getTrueExpr());
860e3654ce7SJustin Bogner     }
861e3654ce7SJustin Bogner     extendRegion(E->getFalseExpr());
862bf42cfd7SJustin Bogner     propagateCounts(subtractCounters(ParentCount, TrueCount),
863bf42cfd7SJustin Bogner                     E->getFalseExpr());
864ee02499aSAlex Lorenz   }
865ee02499aSAlex Lorenz 
866ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
867bf42cfd7SJustin Bogner     extendRegion(E);
868ee02499aSAlex Lorenz     Visit(E->getLHS());
869bf42cfd7SJustin Bogner 
870bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
871bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
872ee02499aSAlex Lorenz   }
873ee02499aSAlex Lorenz 
874ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
875bf42cfd7SJustin Bogner     extendRegion(E);
876ee02499aSAlex Lorenz     Visit(E->getLHS());
877ee02499aSAlex Lorenz 
878bf42cfd7SJustin Bogner     extendRegion(E->getRHS());
879bf42cfd7SJustin Bogner     propagateCounts(getRegionCounter(E), E->getRHS());
88001a0d062SAlex Lorenz   }
881c109102eSJustin Bogner 
882c109102eSJustin Bogner   void VisitLambdaExpr(const LambdaExpr *LE) {
883c109102eSJustin Bogner     // Lambdas are treated as their own functions for now, so we shouldn't
884c109102eSJustin Bogner     // propagate counts into them.
885c109102eSJustin Bogner   }
886ee02499aSAlex Lorenz };
887ab9db510SAlexander Kornienko }
888ee02499aSAlex Lorenz 
889ee02499aSAlex Lorenz static bool isMachO(const CodeGenModule &CGM) {
890ee02499aSAlex Lorenz   return CGM.getTarget().getTriple().isOSBinFormatMachO();
891ee02499aSAlex Lorenz }
892ee02499aSAlex Lorenz 
893ee02499aSAlex Lorenz static StringRef getCoverageSection(const CodeGenModule &CGM) {
894ee02499aSAlex Lorenz   return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap";
895ee02499aSAlex Lorenz }
896ee02499aSAlex Lorenz 
897a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
898a432d176SJustin Bogner                  ArrayRef<CounterExpression> Expressions,
899a432d176SJustin Bogner                  ArrayRef<CounterMappingRegion> Regions) {
900a432d176SJustin Bogner   OS << FunctionName << ":\n";
901a432d176SJustin Bogner   CounterMappingContext Ctx(Expressions);
902a432d176SJustin Bogner   for (const auto &R : Regions) {
903f2cf38e0SAlex Lorenz     OS.indent(2);
904f2cf38e0SAlex Lorenz     switch (R.Kind) {
905f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
906f2cf38e0SAlex Lorenz       break;
907f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
908f2cf38e0SAlex Lorenz       OS << "Expansion,";
909f2cf38e0SAlex Lorenz       break;
910f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
911f2cf38e0SAlex Lorenz       OS << "Skipped,";
912f2cf38e0SAlex Lorenz       break;
913f2cf38e0SAlex Lorenz     }
914f2cf38e0SAlex Lorenz 
9154da909b2SJustin Bogner     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
9164da909b2SJustin Bogner        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
917f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
918f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
9194da909b2SJustin Bogner       OS << " (Expanded file = " << R.ExpandedFileID << ")";
9204da909b2SJustin Bogner     OS << "\n";
921f2cf38e0SAlex Lorenz   }
922f2cf38e0SAlex Lorenz }
923f2cf38e0SAlex Lorenz 
924ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord(
925f2cf38e0SAlex Lorenz     llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue,
9261d45c5bcSAlex Lorenz     uint64_t FunctionHash, const std::string &CoverageMapping) {
927ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
928ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
9291d45c5bcSAlex Lorenz   auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
930ee02499aSAlex Lorenz   auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
931ee02499aSAlex Lorenz   if (!FunctionRecordTy) {
9321d45c5bcSAlex Lorenz     llvm::Type *FunctionRecordTypes[] = {Int8PtrTy, Int32Ty, Int32Ty, Int64Ty};
933ee02499aSAlex Lorenz     FunctionRecordTy =
9344dc5adc7SJustin Bogner         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
9354dc5adc7SJustin Bogner                               /*isPacked=*/true);
936ee02499aSAlex Lorenz   }
937ee02499aSAlex Lorenz 
938ee02499aSAlex Lorenz   llvm::Constant *FunctionRecordVals[] = {
939ee02499aSAlex Lorenz       llvm::ConstantExpr::getBitCast(FunctionName, Int8PtrTy),
940f2cf38e0SAlex Lorenz       llvm::ConstantInt::get(Int32Ty, FunctionNameValue.size()),
9411d45c5bcSAlex Lorenz       llvm::ConstantInt::get(Int32Ty, CoverageMapping.size()),
9421d45c5bcSAlex Lorenz       llvm::ConstantInt::get(Int64Ty, FunctionHash)};
943ee02499aSAlex Lorenz   FunctionRecords.push_back(llvm::ConstantStruct::get(
944ee02499aSAlex Lorenz       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
945ee02499aSAlex Lorenz   CoverageMappings += CoverageMapping;
946f2cf38e0SAlex Lorenz 
947f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
948f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
949f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
950f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
951f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
952f2cf38e0SAlex Lorenz     // expressions.
953f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
954f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
955f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
956f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
957f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
958f2cf38e0SAlex Lorenz     for (const auto &Entry : FileEntries)
959f2cf38e0SAlex Lorenz       FilenameRefs[Entry.second] = Entry.first->getName();
960a432d176SJustin Bogner     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
961a432d176SJustin Bogner                                     Expressions, Regions);
962a432d176SJustin Bogner     if (Reader.read())
963f2cf38e0SAlex Lorenz       return;
964a432d176SJustin Bogner     dump(llvm::outs(), FunctionNameValue, Expressions, Regions);
965f2cf38e0SAlex Lorenz   }
966ee02499aSAlex Lorenz }
967ee02499aSAlex Lorenz 
968ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
969ee02499aSAlex Lorenz   if (FunctionRecords.empty())
970ee02499aSAlex Lorenz     return;
971ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
972ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
973ee02499aSAlex Lorenz 
974ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
975ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
976ee02499aSAlex Lorenz   llvm::SmallVector<StringRef, 16> FilenameRefs;
977ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
978ee02499aSAlex Lorenz   FilenameRefs.resize(FileEntries.size());
979ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
980ee02499aSAlex Lorenz     llvm::SmallString<256> Path(Entry.first->getName());
981ee02499aSAlex Lorenz     llvm::sys::fs::make_absolute(Path);
982ee02499aSAlex Lorenz 
983ee02499aSAlex Lorenz     auto I = Entry.second;
984d1ffdda4SRichard Trieu     FilenameStrs[I] = std::string(Path.begin(), Path.end());
985ee02499aSAlex Lorenz     FilenameRefs[I] = FilenameStrs[I];
986ee02499aSAlex Lorenz   }
987ee02499aSAlex Lorenz 
988ee02499aSAlex Lorenz   std::string FilenamesAndCoverageMappings;
989ee02499aSAlex Lorenz   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
990ee02499aSAlex Lorenz   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
991ee02499aSAlex Lorenz   OS << CoverageMappings;
992ee02499aSAlex Lorenz   size_t CoverageMappingSize = CoverageMappings.size();
993ee02499aSAlex Lorenz   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
994ee02499aSAlex Lorenz   // Append extra zeroes if necessary to ensure that the size of the filenames
995ee02499aSAlex Lorenz   // and coverage mappings is a multiple of 8.
996ee02499aSAlex Lorenz   if (size_t Rem = OS.str().size() % 8) {
997ee02499aSAlex Lorenz     CoverageMappingSize += 8 - Rem;
998ee02499aSAlex Lorenz     for (size_t I = 0, S = 8 - Rem; I < S; ++I)
999ee02499aSAlex Lorenz       OS << '\0';
1000ee02499aSAlex Lorenz   }
1001ee02499aSAlex Lorenz   auto *FilenamesAndMappingsVal =
1002ee02499aSAlex Lorenz       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1003ee02499aSAlex Lorenz 
1004ee02499aSAlex Lorenz   // Create the deferred function records array
1005ee02499aSAlex Lorenz   auto RecordsTy =
1006ee02499aSAlex Lorenz       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1007ee02499aSAlex Lorenz   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1008ee02499aSAlex Lorenz 
1009ee02499aSAlex Lorenz   // Create the coverage data record
1010ee02499aSAlex Lorenz   llvm::Type *CovDataTypes[] = {Int32Ty,   Int32Ty,
1011ee02499aSAlex Lorenz                                 Int32Ty,   Int32Ty,
1012ee02499aSAlex Lorenz                                 RecordsTy, FilenamesAndMappingsVal->getType()};
1013ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1014ee02499aSAlex Lorenz   llvm::Constant *TUDataVals[] = {
1015ee02499aSAlex Lorenz       llvm::ConstantInt::get(Int32Ty, FunctionRecords.size()),
1016ee02499aSAlex Lorenz       llvm::ConstantInt::get(Int32Ty, FilenamesSize),
1017ee02499aSAlex Lorenz       llvm::ConstantInt::get(Int32Ty, CoverageMappingSize),
1018ee02499aSAlex Lorenz       llvm::ConstantInt::get(Int32Ty,
1019ee02499aSAlex Lorenz                              /*Version=*/CoverageMappingVersion1),
1020ee02499aSAlex Lorenz       RecordsVal, FilenamesAndMappingsVal};
1021ee02499aSAlex Lorenz   auto CovDataVal =
1022ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1023ee02499aSAlex Lorenz   auto CovData = new llvm::GlobalVariable(CGM.getModule(), CovDataTy, true,
1024ee02499aSAlex Lorenz                                           llvm::GlobalValue::InternalLinkage,
1025ee02499aSAlex Lorenz                                           CovDataVal,
1026ee02499aSAlex Lorenz                                           "__llvm_coverage_mapping");
1027ee02499aSAlex Lorenz 
1028ee02499aSAlex Lorenz   CovData->setSection(getCoverageSection(CGM));
1029ee02499aSAlex Lorenz   CovData->setAlignment(8);
1030ee02499aSAlex Lorenz 
1031ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1032ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
1033ee02499aSAlex Lorenz }
1034ee02499aSAlex Lorenz 
1035ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1036ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1037ee02499aSAlex Lorenz   if (It != FileEntries.end())
1038ee02499aSAlex Lorenz     return It->second;
1039ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1040ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1041ee02499aSAlex Lorenz   return FileID;
1042ee02499aSAlex Lorenz }
1043ee02499aSAlex Lorenz 
1044ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1045ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1046ee02499aSAlex Lorenz   assert(CounterMap);
1047e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1048ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1049ee02499aSAlex Lorenz   Walker.write(OS);
1050ee02499aSAlex Lorenz }
1051ee02499aSAlex Lorenz 
1052ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1053ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1054ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1055ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1056ee02499aSAlex Lorenz   Walker.write(OS);
1057ee02499aSAlex Lorenz }
1058