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"
18ee02499aSAlex Lorenz #include "llvm/ProfileData/CoverageMapping.h"
19f2cf38e0SAlex Lorenz #include "llvm/ProfileData/CoverageMappingReader.h"
200d9593ddSChandler Carruth #include "llvm/ProfileData/CoverageMappingWriter.h"
210d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h"
22ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h"
23ee02499aSAlex Lorenz 
24ee02499aSAlex Lorenz using namespace clang;
25ee02499aSAlex Lorenz using namespace CodeGen;
26ee02499aSAlex Lorenz using namespace llvm::coverage;
27ee02499aSAlex Lorenz 
28ee02499aSAlex Lorenz void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
29ee02499aSAlex Lorenz   SkippedRanges.push_back(Range);
30ee02499aSAlex Lorenz }
31ee02499aSAlex Lorenz 
32ee02499aSAlex Lorenz namespace {
33ee02499aSAlex Lorenz 
34ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter.
3509c7179bSJustin Bogner class SourceMappingRegion {
3609c7179bSJustin Bogner public:
37ee02499aSAlex Lorenz   enum RegionFlags {
38ee02499aSAlex Lorenz     /// \brief This region won't be emitted if it wasn't extended.
39ee02499aSAlex Lorenz     /// This is useful so that we won't emit source ranges for single tokens
40ee02499aSAlex Lorenz     /// that we don't really care that much about, like:
41ee02499aSAlex Lorenz     ///   the '(' token in #define MACRO (
42ee02499aSAlex Lorenz     IgnoreIfNotExtended = 0x0001,
43ee02499aSAlex Lorenz   };
44ee02499aSAlex Lorenz 
4509c7179bSJustin Bogner private:
46ee02499aSAlex Lorenz   FileID File, MacroArgumentFile;
47ee02499aSAlex Lorenz 
48ee02499aSAlex Lorenz   Counter Count;
49ee02499aSAlex Lorenz 
50ee02499aSAlex Lorenz   /// \brief A statement that initiated the count of Zero.
51ee02499aSAlex Lorenz   ///
52ee02499aSAlex Lorenz   /// This initiator statement is useful to prevent merging of unreachable
53ee02499aSAlex Lorenz   /// regions with different statements that caused the counter to become
54ee02499aSAlex Lorenz   /// unreachable.
55ee02499aSAlex Lorenz   const Stmt *UnreachableInitiator;
56ee02499aSAlex Lorenz 
57ee02499aSAlex Lorenz   /// \brief A statement that separates certain mapping regions into groups.
58ee02499aSAlex Lorenz   ///
59ee02499aSAlex Lorenz   /// The group statement is sometimes useful when we are emitting the source
60ee02499aSAlex Lorenz   /// regions not in their correct lexical order, e.g. the regions for the
61ee02499aSAlex Lorenz   /// incrementation expression in the 'for' construct. By marking the regions
62ee02499aSAlex Lorenz   /// in the incrementation expression with the group statement, we avoid the
63ee02499aSAlex Lorenz   /// merging of the regions from the incrementation expression and the loop's
64ee02499aSAlex Lorenz   /// body.
65ee02499aSAlex Lorenz   const Stmt *Group;
66ee02499aSAlex Lorenz 
67ee02499aSAlex Lorenz   /// \brief The region's starting location.
68ee02499aSAlex Lorenz   SourceLocation LocStart;
69ee02499aSAlex Lorenz 
70ee02499aSAlex Lorenz   /// \brief The region's ending location.
71ee02499aSAlex Lorenz   SourceLocation LocEnd, AlternativeLocEnd;
72ee02499aSAlex Lorenz   unsigned Flags;
73ee02499aSAlex Lorenz 
7409c7179bSJustin Bogner public:
75ee02499aSAlex Lorenz   SourceMappingRegion(FileID File, FileID MacroArgumentFile, Counter Count,
76ee02499aSAlex Lorenz                       const Stmt *UnreachableInitiator, const Stmt *Group,
77ee02499aSAlex Lorenz                       SourceLocation LocStart, SourceLocation LocEnd,
78916cca72SJustin Bogner                       unsigned Flags = 0)
79ee02499aSAlex Lorenz       : File(File), MacroArgumentFile(MacroArgumentFile), Count(Count),
80ee02499aSAlex Lorenz         UnreachableInitiator(UnreachableInitiator), Group(Group),
81ee02499aSAlex Lorenz         LocStart(LocStart), LocEnd(LocEnd), AlternativeLocEnd(LocStart),
82916cca72SJustin Bogner         Flags(Flags) {}
83ee02499aSAlex Lorenz 
8409c7179bSJustin Bogner   const FileID &getFile() const { return File; }
8509c7179bSJustin Bogner 
8609c7179bSJustin Bogner   const Counter &getCounter() const { return Count; }
8709c7179bSJustin Bogner 
8809c7179bSJustin Bogner   const SourceLocation &getStartLoc() const { return LocStart; }
8909c7179bSJustin Bogner 
9009c7179bSJustin Bogner   const SourceLocation &getEndLoc(const SourceManager &SM) const {
9109c7179bSJustin Bogner     if (SM.getFileID(LocEnd) != File)
9209c7179bSJustin Bogner       return AlternativeLocEnd;
9309c7179bSJustin Bogner     return LocEnd;
9409c7179bSJustin Bogner   }
9509c7179bSJustin Bogner 
96ee02499aSAlex Lorenz   bool hasFlag(RegionFlags Flag) const { return (Flags & Flag) != 0; }
97ee02499aSAlex Lorenz 
98ee02499aSAlex Lorenz   void setFlag(RegionFlags Flag) { Flags |= Flag; }
99ee02499aSAlex Lorenz 
100ee02499aSAlex Lorenz   void clearFlag(RegionFlags Flag) { Flags &= ~Flag; }
101ee02499aSAlex Lorenz 
102ee02499aSAlex Lorenz   /// \brief Return true if two regions can be merged together.
103ee02499aSAlex Lorenz   bool isMergeable(SourceMappingRegion &R) {
104f59329b0SJustin Bogner     // FIXME: We allow merging regions with a gap in between them. Should we?
105ee02499aSAlex Lorenz     return File == R.File && MacroArgumentFile == R.MacroArgumentFile &&
106ee02499aSAlex Lorenz            Count == R.Count && UnreachableInitiator == R.UnreachableInitiator &&
107916cca72SJustin Bogner            Group == R.Group;
108ee02499aSAlex Lorenz   }
109ee02499aSAlex Lorenz 
110f59329b0SJustin Bogner   /// \brief A comparison that sorts such that mergeable regions are adjacent.
111f59329b0SJustin Bogner   friend bool operator<(const SourceMappingRegion &LHS,
112f59329b0SJustin Bogner                         const SourceMappingRegion &RHS) {
113f59329b0SJustin Bogner     return std::tie(LHS.File, LHS.MacroArgumentFile, LHS.Count,
114f59329b0SJustin Bogner                     LHS.UnreachableInitiator, LHS.Group) <
115f59329b0SJustin Bogner            std::tie(RHS.File, RHS.MacroArgumentFile, RHS.Count,
116f59329b0SJustin Bogner                     RHS.UnreachableInitiator, RHS.Group);
117ee02499aSAlex Lorenz   }
118ee02499aSAlex Lorenz };
119ee02499aSAlex Lorenz 
120ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different
121ee02499aSAlex Lorenz /// coverage mapping region builders.
122ee02499aSAlex Lorenz class CoverageMappingBuilder {
123ee02499aSAlex Lorenz public:
124ee02499aSAlex Lorenz   CoverageMappingModuleGen &CVM;
125ee02499aSAlex Lorenz   SourceManager &SM;
126ee02499aSAlex Lorenz   const LangOptions &LangOpts;
127ee02499aSAlex Lorenz 
128ee02499aSAlex Lorenz private:
129ee02499aSAlex Lorenz   struct FileInfo {
130ee02499aSAlex Lorenz     /// \brief The file id that will be used by the coverage mapping system.
131ee02499aSAlex Lorenz     unsigned CovMappingFileID;
132ee02499aSAlex Lorenz     const FileEntry *Entry;
133ee02499aSAlex Lorenz 
134ee02499aSAlex Lorenz     FileInfo(unsigned CovMappingFileID, const FileEntry *Entry)
135ee02499aSAlex Lorenz         : CovMappingFileID(CovMappingFileID), Entry(Entry) {}
136ee02499aSAlex Lorenz   };
137ee02499aSAlex Lorenz 
138ee02499aSAlex Lorenz   /// \brief This mapping maps clang's FileIDs to file ids used
139ee02499aSAlex Lorenz   /// by the coverage mapping system and clang's file entries.
140ee02499aSAlex Lorenz   llvm::SmallDenseMap<FileID, FileInfo, 8> FileIDMapping;
141ee02499aSAlex Lorenz 
142ee02499aSAlex Lorenz public:
143ee02499aSAlex Lorenz   /// \brief The statement that corresponds to the current source group.
144ee02499aSAlex Lorenz   const Stmt *CurrentSourceGroup;
145ee02499aSAlex Lorenz 
146ee02499aSAlex Lorenz   /// \brief The statement the initiated the current unreachable region.
147ee02499aSAlex Lorenz   const Stmt *CurrentUnreachableRegionInitiator;
148ee02499aSAlex Lorenz 
149ee02499aSAlex Lorenz   /// \brief The coverage mapping regions for this function
150ee02499aSAlex Lorenz   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
151ee02499aSAlex Lorenz   /// \brief The source mapping regions for this function.
152f59329b0SJustin Bogner   std::vector<SourceMappingRegion> SourceRegions;
153ee02499aSAlex Lorenz 
154ee02499aSAlex Lorenz   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
155ee02499aSAlex Lorenz                          const LangOptions &LangOpts)
156ee02499aSAlex Lorenz       : CVM(CVM), SM(SM), LangOpts(LangOpts),
157ee02499aSAlex Lorenz         CurrentSourceGroup(nullptr),
158ee02499aSAlex Lorenz         CurrentUnreachableRegionInitiator(nullptr) {}
159ee02499aSAlex Lorenz 
160ee02499aSAlex Lorenz   /// \brief Return the precise end location for the given token.
161ee02499aSAlex Lorenz   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
162ee02499aSAlex Lorenz     return Lexer::getLocForEndOfToken(SM.getSpellingLoc(Loc), 0, SM, LangOpts);
163ee02499aSAlex Lorenz   }
164ee02499aSAlex Lorenz 
165ee02499aSAlex Lorenz   /// \brief Create the mapping that maps from the function's file ids to
166ee02499aSAlex Lorenz   /// the indices for the translation unit's filenames.
167ee02499aSAlex Lorenz   void createFileIDMapping(SmallVectorImpl<unsigned> &Mapping) {
168ee02499aSAlex Lorenz     Mapping.resize(FileIDMapping.size(), 0);
169ee02499aSAlex Lorenz     for (const auto &I : FileIDMapping)
170ee02499aSAlex Lorenz       Mapping[I.second.CovMappingFileID] = CVM.getFileID(I.second.Entry);
171ee02499aSAlex Lorenz   }
172ee02499aSAlex Lorenz 
173ee02499aSAlex Lorenz   /// \brief Get the coverage mapping file id that corresponds to the given
174ee02499aSAlex Lorenz   /// clang file id. If such file id doesn't exist, it gets added to the
175ee02499aSAlex Lorenz   /// mapping that maps from clang's file ids to coverage mapping file ids.
176*903678caSJustin Bogner   /// Returns None if there was an error getting the coverage mapping file id.
177ee02499aSAlex Lorenz   /// An example of an when this function fails is when the region tries
178ee02499aSAlex Lorenz   /// to get a coverage file id for a location in a built-in macro.
179*903678caSJustin Bogner   Optional<unsigned> getCoverageFileID(SourceLocation LocStart, FileID File,
180*903678caSJustin Bogner                                        FileID SpellingFile) {
181ee02499aSAlex Lorenz     auto Mapping = FileIDMapping.find(File);
182*903678caSJustin Bogner     if (Mapping != FileIDMapping.end())
183*903678caSJustin Bogner       return Mapping->second.CovMappingFileID;
184ee02499aSAlex Lorenz 
185ee02499aSAlex Lorenz     auto Entry = SM.getFileEntryForID(SpellingFile);
186ee02499aSAlex Lorenz     if (!Entry)
187*903678caSJustin Bogner       return None;
188ee02499aSAlex Lorenz 
189*903678caSJustin Bogner     unsigned Result = FileIDMapping.size();
190ee02499aSAlex Lorenz     FileIDMapping.insert(std::make_pair(File, FileInfo(Result, Entry)));
191ee02499aSAlex Lorenz     createFileExpansionRegion(LocStart, File);
192*903678caSJustin Bogner     return Result;
193ee02499aSAlex Lorenz   }
194ee02499aSAlex Lorenz 
195ee02499aSAlex Lorenz   /// \brief Get the coverage mapping file id that corresponds to the given
196ee02499aSAlex Lorenz   /// clang file id.
197*903678caSJustin Bogner   /// Returns None if there was an error getting the coverage mapping file id.
198*903678caSJustin Bogner   Optional<unsigned> getExistingCoverageFileID(FileID File) {
199ee02499aSAlex Lorenz     // Make sure that the file is valid.
200ee02499aSAlex Lorenz     if (File.isInvalid())
201*903678caSJustin Bogner       return None;
202ee02499aSAlex Lorenz     auto Mapping = FileIDMapping.find(File);
203*903678caSJustin Bogner     if (Mapping == FileIDMapping.end())
204*903678caSJustin Bogner       return None;
205*903678caSJustin Bogner     return Mapping->second.CovMappingFileID;
206ee02499aSAlex Lorenz   }
207ee02499aSAlex Lorenz 
208ee02499aSAlex Lorenz   /// \brief Return true if the given clang's file id has a corresponding
209ee02499aSAlex Lorenz   /// coverage file id.
210ee02499aSAlex Lorenz   bool hasExistingCoverageFileID(FileID File) const {
211ee02499aSAlex Lorenz     return FileIDMapping.count(File);
212ee02499aSAlex Lorenz   }
213ee02499aSAlex Lorenz 
214ee02499aSAlex Lorenz   /// \brief Gather all the regions that were skipped by the preprocessor
215ee02499aSAlex Lorenz   /// using the constructs like #if.
216ee02499aSAlex Lorenz   void gatherSkippedRegions() {
217ee02499aSAlex Lorenz     /// An array of the minimum lineStarts and the maximum lineEnds
218ee02499aSAlex Lorenz     /// for mapping regions from the appropriate source files.
219ee02499aSAlex Lorenz     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
220ee02499aSAlex Lorenz     FileLineRanges.resize(
221ee02499aSAlex Lorenz         FileIDMapping.size(),
222ee02499aSAlex Lorenz         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
223ee02499aSAlex Lorenz     for (const auto &R : MappingRegions) {
224ee02499aSAlex Lorenz       FileLineRanges[R.FileID].first =
225ee02499aSAlex Lorenz           std::min(FileLineRanges[R.FileID].first, R.LineStart);
226ee02499aSAlex Lorenz       FileLineRanges[R.FileID].second =
227ee02499aSAlex Lorenz           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
228ee02499aSAlex Lorenz     }
229ee02499aSAlex Lorenz 
230ee02499aSAlex Lorenz     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
231ee02499aSAlex Lorenz     for (const auto &I : SkippedRanges) {
232ee02499aSAlex Lorenz       auto LocStart = I.getBegin();
233ee02499aSAlex Lorenz       auto LocEnd = I.getEnd();
234ee02499aSAlex Lorenz       auto FileStart = SM.getFileID(LocStart);
235ee02499aSAlex Lorenz       if (!hasExistingCoverageFileID(FileStart))
236ee02499aSAlex Lorenz         continue;
237ee02499aSAlex Lorenz       auto ActualFileStart = SM.getDecomposedSpellingLoc(LocStart).first;
238ee02499aSAlex Lorenz       if (ActualFileStart != SM.getDecomposedSpellingLoc(LocEnd).first)
239ee02499aSAlex Lorenz         // Ignore regions that span across multiple files.
240ee02499aSAlex Lorenz         continue;
241ee02499aSAlex Lorenz 
242*903678caSJustin Bogner       auto CovFileID = getCoverageFileID(LocStart, FileStart, ActualFileStart);
243*903678caSJustin Bogner       if (!CovFileID)
244ee02499aSAlex Lorenz         continue;
245ee02499aSAlex Lorenz       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
246ee02499aSAlex Lorenz       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
247ee02499aSAlex Lorenz       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
248ee02499aSAlex Lorenz       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
249*903678caSJustin Bogner       CounterMappingRegion Region(Counter(), *CovFileID, LineStart, ColumnStart,
250ee02499aSAlex Lorenz                                   LineEnd, ColumnEnd, false,
251ee02499aSAlex Lorenz                                   CounterMappingRegion::SkippedRegion);
252ee02499aSAlex Lorenz       // Make sure that we only collect the regions that are inside
253ee02499aSAlex Lorenz       // the souce code of this function.
254*903678caSJustin Bogner       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
255*903678caSJustin Bogner           Region.LineEnd <= FileLineRanges[*CovFileID].second)
256ee02499aSAlex Lorenz         MappingRegions.push_back(Region);
257ee02499aSAlex Lorenz     }
258ee02499aSAlex Lorenz   }
259ee02499aSAlex Lorenz 
260ee02499aSAlex Lorenz   /// \brief Create a mapping region that correponds to an expansion of
261ee02499aSAlex Lorenz   /// a macro or an embedded include.
262ee02499aSAlex Lorenz   void createFileExpansionRegion(SourceLocation Loc, FileID ExpandedFile) {
263ee02499aSAlex Lorenz     SourceLocation LocStart;
264ee02499aSAlex Lorenz     if (Loc.isMacroID())
265ee02499aSAlex Lorenz       LocStart = SM.getImmediateExpansionRange(Loc).first;
266ee02499aSAlex Lorenz     else {
267ee02499aSAlex Lorenz       LocStart = SM.getIncludeLoc(ExpandedFile);
268ee02499aSAlex Lorenz       if (LocStart.isInvalid())
269ee02499aSAlex Lorenz         return; // This file has no expansion region.
270ee02499aSAlex Lorenz     }
271ee02499aSAlex Lorenz 
272ee02499aSAlex Lorenz     auto File = SM.getFileID(LocStart);
273ee02499aSAlex Lorenz     auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first;
274*903678caSJustin Bogner     auto CovFileID = getCoverageFileID(LocStart, File, SpellingFile);
275*903678caSJustin Bogner     auto ExpandedFileID = getExistingCoverageFileID(ExpandedFile);
276*903678caSJustin Bogner     if (!CovFileID || !ExpandedFileID)
277ee02499aSAlex Lorenz       return;
278ee02499aSAlex Lorenz     unsigned LineStart = SM.getSpellingLineNumber(LocStart);
279ee02499aSAlex Lorenz     unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
280ee02499aSAlex Lorenz     unsigned LineEnd = LineStart;
281ee02499aSAlex Lorenz     // Compute the end column manually as Lexer::getLocForEndOfToken doesn't
282ee02499aSAlex Lorenz     // give the correct result in all cases.
283ee02499aSAlex Lorenz     unsigned ColumnEnd =
284ee02499aSAlex Lorenz         ColumnStart +
285ee02499aSAlex Lorenz         Lexer::MeasureTokenLength(SM.getSpellingLoc(LocStart), SM, LangOpts);
286ee02499aSAlex Lorenz 
287ee02499aSAlex Lorenz     MappingRegions.push_back(CounterMappingRegion(
288*903678caSJustin Bogner         Counter(), *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd,
289ee02499aSAlex Lorenz         false, CounterMappingRegion::ExpansionRegion));
290*903678caSJustin Bogner     MappingRegions.back().ExpandedFileID = *ExpandedFileID;
291ee02499aSAlex Lorenz   }
292ee02499aSAlex Lorenz 
293ee02499aSAlex Lorenz   /// \brief Enter a source region group that is identified by the given
294ee02499aSAlex Lorenz   /// statement.
295ee02499aSAlex Lorenz   /// It's not possible to enter a group when there is already
296ee02499aSAlex Lorenz   /// another group present.
297ee02499aSAlex Lorenz   void beginSourceRegionGroup(const Stmt *Group) {
298ee02499aSAlex Lorenz     assert(!CurrentSourceGroup);
299ee02499aSAlex Lorenz     CurrentSourceGroup = Group;
300ee02499aSAlex Lorenz   }
301ee02499aSAlex Lorenz 
302ee02499aSAlex Lorenz   /// \brief Exit the current source region group.
303ee02499aSAlex Lorenz   void endSourceRegionGroup() { CurrentSourceGroup = nullptr; }
304ee02499aSAlex Lorenz 
305ee02499aSAlex Lorenz   /// \brief Associate a counter with a given source code range.
306ee02499aSAlex Lorenz   void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
307ee02499aSAlex Lorenz                           Counter Count, const Stmt *UnreachableInitiator,
308ee02499aSAlex Lorenz                           const Stmt *SourceGroup, unsigned Flags = 0,
309ee02499aSAlex Lorenz                           FileID MacroArgumentFile = FileID()) {
310ee02499aSAlex Lorenz     if (SM.isMacroArgExpansion(LocStart)) {
311ee02499aSAlex Lorenz       // Map the code range with the macro argument's value.
312ee02499aSAlex Lorenz       mapSourceCodeRange(SM.getImmediateSpellingLoc(LocStart),
313ee02499aSAlex Lorenz                          SM.getImmediateSpellingLoc(LocEnd), Count,
314ee02499aSAlex Lorenz                          UnreachableInitiator, SourceGroup, Flags,
315ee02499aSAlex Lorenz                          SM.getFileID(LocStart));
316ee02499aSAlex Lorenz       // Map the code range where the macro argument is referenced.
317ee02499aSAlex Lorenz       SourceLocation RefLocStart(SM.getImmediateExpansionRange(LocStart).first);
318ee02499aSAlex Lorenz       SourceLocation RefLocEnd(RefLocStart);
319ee02499aSAlex Lorenz       if (SM.isMacroArgExpansion(RefLocStart))
320ee02499aSAlex Lorenz         mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator,
321ee02499aSAlex Lorenz                            SourceGroup, 0, SM.getFileID(RefLocStart));
322ee02499aSAlex Lorenz       else
323ee02499aSAlex Lorenz         mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator,
324ee02499aSAlex Lorenz                            SourceGroup);
325ee02499aSAlex Lorenz       return;
326ee02499aSAlex Lorenz     }
327ee02499aSAlex Lorenz     auto File = SM.getFileID(LocStart);
328ee02499aSAlex Lorenz     // Make sure that the file id is valid.
329ee02499aSAlex Lorenz     if (File.isInvalid())
330ee02499aSAlex Lorenz       return;
331f59329b0SJustin Bogner     SourceRegions.emplace_back(File, MacroArgumentFile, Count,
332f59329b0SJustin Bogner                                UnreachableInitiator, SourceGroup, LocStart,
333f59329b0SJustin Bogner                                LocEnd, Flags);
334ee02499aSAlex Lorenz   }
335ee02499aSAlex Lorenz 
336ee02499aSAlex Lorenz   void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
337ee02499aSAlex Lorenz                           Counter Count, unsigned Flags = 0) {
338ee02499aSAlex Lorenz     mapSourceCodeRange(LocStart, LocEnd, Count,
339ee02499aSAlex Lorenz                        CurrentUnreachableRegionInitiator, CurrentSourceGroup,
340ee02499aSAlex Lorenz                        Flags);
341ee02499aSAlex Lorenz   }
342ee02499aSAlex Lorenz 
343ee02499aSAlex Lorenz   /// \brief Generate the coverage counter mapping regions from collected
344ee02499aSAlex Lorenz   /// source regions.
345ee02499aSAlex Lorenz   void emitSourceRegions() {
346f59329b0SJustin Bogner     std::sort(SourceRegions.begin(), SourceRegions.end());
347ee02499aSAlex Lorenz 
348f59329b0SJustin Bogner     for (auto I = SourceRegions.begin(), E = SourceRegions.end(); I != E; ++I) {
349f59329b0SJustin Bogner       // Keep the original start location of this region.
350f59329b0SJustin Bogner       SourceLocation LocStart = I->getStartLoc();
351f59329b0SJustin Bogner       SourceLocation LocEnd = I->getEndLoc(SM);
352f59329b0SJustin Bogner 
353f59329b0SJustin Bogner       bool Ignore = I->hasFlag(SourceMappingRegion::IgnoreIfNotExtended);
354f59329b0SJustin Bogner       // We need to handle mergeable regions together.
355f59329b0SJustin Bogner       for (auto Next = I + 1; Next != E && Next->isMergeable(*I); ++Next) {
356f59329b0SJustin Bogner         ++I;
357f59329b0SJustin Bogner         LocStart = std::min(LocStart, I->getStartLoc());
358f59329b0SJustin Bogner         LocEnd = std::max(LocEnd, I->getEndLoc(SM));
359f59329b0SJustin Bogner         // FIXME: Should we && together the Ignore flag of multiple regions?
360f59329b0SJustin Bogner         Ignore = false;
361f59329b0SJustin Bogner       }
362f59329b0SJustin Bogner       if (Ignore)
363ee02499aSAlex Lorenz         continue;
364ee02499aSAlex Lorenz 
365f59329b0SJustin Bogner       // Find the spilling locations for the mapping region.
366ee02499aSAlex Lorenz       LocEnd = getPreciseTokenLocEnd(LocEnd);
367ee02499aSAlex Lorenz       unsigned LineStart = SM.getSpellingLineNumber(LocStart);
368ee02499aSAlex Lorenz       unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
369ee02499aSAlex Lorenz       unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
370ee02499aSAlex Lorenz       unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
371ee02499aSAlex Lorenz 
37209c7179bSJustin Bogner       auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first;
373*903678caSJustin Bogner       auto CovFileID = getCoverageFileID(LocStart, I->getFile(), SpellingFile);
374*903678caSJustin Bogner       if (!CovFileID)
375ee02499aSAlex Lorenz         continue;
376ee02499aSAlex Lorenz 
377ee02499aSAlex Lorenz       assert(LineStart <= LineEnd);
378ee02499aSAlex Lorenz       MappingRegions.push_back(CounterMappingRegion(
379*903678caSJustin Bogner           I->getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
380f59329b0SJustin Bogner           ColumnEnd, false, CounterMappingRegion::CodeRegion));
381ee02499aSAlex Lorenz     }
382ee02499aSAlex Lorenz   }
383ee02499aSAlex Lorenz };
384ee02499aSAlex Lorenz 
385ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that
386ee02499aSAlex Lorenz /// are not emitted.
387ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
388ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
389ee02499aSAlex Lorenz                               const LangOptions &LangOpts)
390ee02499aSAlex Lorenz       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
391ee02499aSAlex Lorenz 
392ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
393ee02499aSAlex Lorenz     if (!D->hasBody())
394ee02499aSAlex Lorenz       return;
395ee02499aSAlex Lorenz     auto Body = D->getBody();
396ee02499aSAlex Lorenz     mapSourceCodeRange(Body->getLocStart(), Body->getLocEnd(), Counter());
397ee02499aSAlex Lorenz   }
398ee02499aSAlex Lorenz 
399ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
400ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
401ee02499aSAlex Lorenz     emitSourceRegions();
402ee02499aSAlex Lorenz     SmallVector<unsigned, 16> FileIDMapping;
403ee02499aSAlex Lorenz     createFileIDMapping(FileIDMapping);
404ee02499aSAlex Lorenz 
4055fc8fc2dSCraig Topper     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
406ee02499aSAlex Lorenz     Writer.write(OS);
407ee02499aSAlex Lorenz   }
408ee02499aSAlex Lorenz };
409ee02499aSAlex Lorenz 
410ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map
411ee02499aSAlex Lorenz /// from the source code locations to the PGO counters.
412ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder
413ee02499aSAlex Lorenz     : public CoverageMappingBuilder,
414ee02499aSAlex Lorenz       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
415ee02499aSAlex Lorenz   /// \brief The map of statements to count values.
416ee02499aSAlex Lorenz   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
417ee02499aSAlex Lorenz 
418ee02499aSAlex Lorenz   Counter CurrentRegionCount;
419ee02499aSAlex Lorenz 
420ee02499aSAlex Lorenz   CounterExpressionBuilder Builder;
421ee02499aSAlex Lorenz 
422ee02499aSAlex Lorenz   /// \brief Return a counter that represents the
423ee02499aSAlex Lorenz   /// expression that subracts rhs from lhs.
424ee02499aSAlex Lorenz   Counter subtractCounters(Counter LHS, Counter RHS) {
425ee02499aSAlex Lorenz     return Builder.subtract(LHS, RHS);
426ee02499aSAlex Lorenz   }
427ee02499aSAlex Lorenz 
428ee02499aSAlex Lorenz   /// \brief Return a counter that represents the
429ee02499aSAlex Lorenz   /// the exression that adds lhs and rhs.
430ee02499aSAlex Lorenz   Counter addCounters(Counter LHS, Counter RHS) {
431ee02499aSAlex Lorenz     return Builder.add(LHS, RHS);
432ee02499aSAlex Lorenz   }
433ee02499aSAlex Lorenz 
434ee02499aSAlex Lorenz   /// \brief Return the region counter for the given statement.
435ee02499aSAlex Lorenz   /// This should only be called on statements that have a dedicated counter.
436ee02499aSAlex Lorenz   unsigned getRegionCounter(const Stmt *S) { return CounterMap[S]; }
437ee02499aSAlex Lorenz 
438ee02499aSAlex Lorenz   /// \brief Return the region count for the counter at the given index.
439ee02499aSAlex Lorenz   Counter getRegionCount(unsigned CounterId) {
440ee02499aSAlex Lorenz     return Counter::getCounter(CounterId);
441ee02499aSAlex Lorenz   }
442ee02499aSAlex Lorenz 
443ee02499aSAlex Lorenz   /// \brief Return the counter value of the current region.
444ee02499aSAlex Lorenz   Counter getCurrentRegionCount() { return CurrentRegionCount; }
445ee02499aSAlex Lorenz 
446ee02499aSAlex Lorenz   /// \brief Set the counter value for the current region.
447ee02499aSAlex Lorenz   /// This is used to keep track of changes to the most recent counter
448ee02499aSAlex Lorenz   /// from control flow and non-local exits.
449ee02499aSAlex Lorenz   void setCurrentRegionCount(Counter Count) {
450ee02499aSAlex Lorenz     CurrentRegionCount = Count;
451ee02499aSAlex Lorenz     CurrentUnreachableRegionInitiator = nullptr;
452ee02499aSAlex Lorenz   }
453ee02499aSAlex Lorenz 
454ee02499aSAlex Lorenz   /// \brief Indicate that the current region is never reached,
455ee02499aSAlex Lorenz   /// and thus should have a counter value of zero.
456ee02499aSAlex Lorenz   /// This is important so that subsequent regions can correctly track
457ee02499aSAlex Lorenz   /// their parent counts.
458ee02499aSAlex Lorenz   void setCurrentRegionUnreachable(const Stmt *Initiator) {
459ee02499aSAlex Lorenz     CurrentRegionCount = Counter::getZero();
460ee02499aSAlex Lorenz     CurrentUnreachableRegionInitiator = Initiator;
461ee02499aSAlex Lorenz   }
462ee02499aSAlex Lorenz 
463ee02499aSAlex Lorenz   /// \brief A counter for a particular region.
464ee02499aSAlex Lorenz   /// This is the primary interface through
465ee02499aSAlex Lorenz   /// which the coverage mapping builder manages counters and their values.
466ee02499aSAlex Lorenz   class RegionMapper {
467ee02499aSAlex Lorenz     CounterCoverageMappingBuilder &Mapping;
468ee02499aSAlex Lorenz     Counter Count;
469ee02499aSAlex Lorenz     Counter ParentCount;
470ee02499aSAlex Lorenz     Counter RegionCount;
471ee02499aSAlex Lorenz     Counter Adjust;
472ee02499aSAlex Lorenz 
473ee02499aSAlex Lorenz   public:
474ee02499aSAlex Lorenz     RegionMapper(CounterCoverageMappingBuilder *Mapper, const Stmt *S)
475ee02499aSAlex Lorenz         : Mapping(*Mapper),
476ee02499aSAlex Lorenz           Count(Mapper->getRegionCount(Mapper->getRegionCounter(S))),
477ee02499aSAlex Lorenz           ParentCount(Mapper->getCurrentRegionCount()) {}
478ee02499aSAlex Lorenz 
479ee02499aSAlex Lorenz     /// Get the value of the counter. In most cases this is the number of times
480ee02499aSAlex Lorenz     /// the region of the counter was entered, but for switch labels it's the
481ee02499aSAlex Lorenz     /// number of direct jumps to that label.
482ee02499aSAlex Lorenz     Counter getCount() const { return Count; }
483ee02499aSAlex Lorenz 
484ee02499aSAlex Lorenz     /// Get the value of the counter with adjustments applied. Adjustments occur
485ee02499aSAlex Lorenz     /// when control enters or leaves the region abnormally; i.e., if there is a
486ee02499aSAlex Lorenz     /// jump to a label within the region, or if the function can return from
487ee02499aSAlex Lorenz     /// within the region. The adjusted count, then, is the value of the counter
488ee02499aSAlex Lorenz     /// at the end of the region.
489ee02499aSAlex Lorenz     Counter getAdjustedCount() const {
490ee02499aSAlex Lorenz       return Mapping.addCounters(Count, Adjust);
491ee02499aSAlex Lorenz     }
492ee02499aSAlex Lorenz 
493ee02499aSAlex Lorenz     /// Get the value of the counter in this region's parent, i.e., the region
494ee02499aSAlex Lorenz     /// that was active when this region began. This is useful for deriving
495ee02499aSAlex Lorenz     /// counts in implicitly counted regions, like the false case of a condition
496ee02499aSAlex Lorenz     /// or the normal exits of a loop.
497ee02499aSAlex Lorenz     Counter getParentCount() const { return ParentCount; }
498ee02499aSAlex Lorenz 
499ee02499aSAlex Lorenz     /// Activate the counter by emitting an increment and starting to track
500ee02499aSAlex Lorenz     /// adjustments. If AddIncomingFallThrough is true, the current region count
501ee02499aSAlex Lorenz     /// will be added to the counter for the purposes of tracking the region.
502ee02499aSAlex Lorenz     void beginRegion(bool AddIncomingFallThrough = false) {
503ee02499aSAlex Lorenz       RegionCount = Count;
504ee02499aSAlex Lorenz       if (AddIncomingFallThrough)
505ee02499aSAlex Lorenz         RegionCount =
506ee02499aSAlex Lorenz             Mapping.addCounters(RegionCount, Mapping.getCurrentRegionCount());
507ee02499aSAlex Lorenz       Mapping.setCurrentRegionCount(RegionCount);
508ee02499aSAlex Lorenz     }
509ee02499aSAlex Lorenz 
510ee02499aSAlex Lorenz     /// For counters on boolean branches, begins tracking adjustments for the
511ee02499aSAlex Lorenz     /// uncounted path.
512ee02499aSAlex Lorenz     void beginElseRegion() {
513ee02499aSAlex Lorenz       RegionCount = Mapping.subtractCounters(ParentCount, Count);
514ee02499aSAlex Lorenz       Mapping.setCurrentRegionCount(RegionCount);
515ee02499aSAlex Lorenz     }
516ee02499aSAlex Lorenz 
517ee02499aSAlex Lorenz     /// Reset the current region count.
518ee02499aSAlex Lorenz     void setCurrentRegionCount(Counter CurrentCount) {
519ee02499aSAlex Lorenz       RegionCount = CurrentCount;
520ee02499aSAlex Lorenz       Mapping.setCurrentRegionCount(RegionCount);
521ee02499aSAlex Lorenz     }
522ee02499aSAlex Lorenz 
523ee02499aSAlex Lorenz     /// Adjust for non-local control flow after emitting a subexpression or
524ee02499aSAlex Lorenz     /// substatement. This must be called to account for constructs such as
525ee02499aSAlex Lorenz     /// gotos,
526ee02499aSAlex Lorenz     /// labels, and returns, so that we can ensure that our region's count is
527ee02499aSAlex Lorenz     /// correct in the code that follows.
528ee02499aSAlex Lorenz     void adjustForControlFlow() {
529ee02499aSAlex Lorenz       Adjust = Mapping.addCounters(
530ee02499aSAlex Lorenz           Adjust, Mapping.subtractCounters(Mapping.getCurrentRegionCount(),
531ee02499aSAlex Lorenz                                            RegionCount));
532ee02499aSAlex Lorenz       // Reset the region count in case this is called again later.
533ee02499aSAlex Lorenz       RegionCount = Mapping.getCurrentRegionCount();
534ee02499aSAlex Lorenz     }
535ee02499aSAlex Lorenz 
536ee02499aSAlex Lorenz     /// Commit all adjustments to the current region. If the region is a loop,
537ee02499aSAlex Lorenz     /// the LoopAdjust value should be the count of all the breaks and continues
538ee02499aSAlex Lorenz     /// from the loop, to compensate for those counts being deducted from the
539ee02499aSAlex Lorenz     /// adjustments for the body of the loop.
540ee02499aSAlex Lorenz     void applyAdjustmentsToRegion() {
541ee02499aSAlex Lorenz       Mapping.setCurrentRegionCount(Mapping.addCounters(ParentCount, Adjust));
542ee02499aSAlex Lorenz     }
543ee02499aSAlex Lorenz     void applyAdjustmentsToRegion(Counter LoopAdjust) {
544ee02499aSAlex Lorenz       Mapping.setCurrentRegionCount(Mapping.addCounters(
545ee02499aSAlex Lorenz           Mapping.addCounters(ParentCount, Adjust), LoopAdjust));
546ee02499aSAlex Lorenz     }
547ee02499aSAlex Lorenz   };
548ee02499aSAlex Lorenz 
549ee02499aSAlex Lorenz   /// \brief Keep counts of breaks and continues inside loops.
550ee02499aSAlex Lorenz   struct BreakContinue {
551ee02499aSAlex Lorenz     Counter BreakCount;
552ee02499aSAlex Lorenz     Counter ContinueCount;
553ee02499aSAlex Lorenz   };
554ee02499aSAlex Lorenz   SmallVector<BreakContinue, 8> BreakContinueStack;
555ee02499aSAlex Lorenz 
556ee02499aSAlex Lorenz   CounterCoverageMappingBuilder(
557ee02499aSAlex Lorenz       CoverageMappingModuleGen &CVM,
558e5ee6c58SJustin Bogner       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
559ee02499aSAlex Lorenz       const LangOptions &LangOpts)
560e5ee6c58SJustin Bogner       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
561ee02499aSAlex Lorenz 
562ee02499aSAlex Lorenz   /// \brief Write the mapping data to the output stream
563ee02499aSAlex Lorenz   void write(llvm::raw_ostream &OS) {
564ee02499aSAlex Lorenz     emitSourceRegions();
565ee02499aSAlex Lorenz     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
566ee02499aSAlex Lorenz     createFileIDMapping(VirtualFileMapping);
567ee02499aSAlex Lorenz     gatherSkippedRegions();
568ee02499aSAlex Lorenz 
569ee02499aSAlex Lorenz     CoverageMappingWriter Writer(
570ee02499aSAlex Lorenz         VirtualFileMapping, Builder.getExpressions(), MappingRegions);
571ee02499aSAlex Lorenz     Writer.write(OS);
572ee02499aSAlex Lorenz   }
573ee02499aSAlex Lorenz 
574ee02499aSAlex Lorenz   /// \brief Associate the source code range with the current region count.
575ee02499aSAlex Lorenz   void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd,
576ee02499aSAlex Lorenz                           unsigned Flags = 0) {
577ee02499aSAlex Lorenz     CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocEnd,
578ee02499aSAlex Lorenz                                                CurrentRegionCount, Flags);
579ee02499aSAlex Lorenz   }
580ee02499aSAlex Lorenz 
581ee02499aSAlex Lorenz   void mapSourceCodeRange(SourceLocation LocStart) {
582ee02499aSAlex Lorenz     CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocStart,
583ee02499aSAlex Lorenz                                                CurrentRegionCount);
584ee02499aSAlex Lorenz   }
585ee02499aSAlex Lorenz 
586ee02499aSAlex Lorenz   /// \brief Associate the source range of a token with the current region
587ee02499aSAlex Lorenz   /// count.
588ee02499aSAlex Lorenz   /// Ignore the source range for this token if it produces a distinct
589ee02499aSAlex Lorenz   /// mapping region with no other source ranges.
590ee02499aSAlex Lorenz   void mapToken(SourceLocation LocStart) {
591ee02499aSAlex Lorenz     CoverageMappingBuilder::mapSourceCodeRange(
592ee02499aSAlex Lorenz         LocStart, LocStart, CurrentRegionCount,
593ee02499aSAlex Lorenz         SourceMappingRegion::IgnoreIfNotExtended);
594ee02499aSAlex Lorenz   }
595ee02499aSAlex Lorenz 
596ee02499aSAlex Lorenz   void VisitStmt(const Stmt *S) {
597ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
598ee02499aSAlex Lorenz     for (Stmt::const_child_range I = S->children(); I; ++I) {
599ee02499aSAlex Lorenz       if (*I)
600ee02499aSAlex Lorenz         this->Visit(*I);
601ee02499aSAlex Lorenz     }
602ee02499aSAlex Lorenz   }
603ee02499aSAlex Lorenz 
604ee02499aSAlex Lorenz   void VisitDecl(const Decl *D) {
605ee02499aSAlex Lorenz     if (!D->hasBody())
606ee02499aSAlex Lorenz       return;
607ee02499aSAlex Lorenz     // Counter tracks entry to the function body.
608ee02499aSAlex Lorenz     auto Body = D->getBody();
609ee02499aSAlex Lorenz     RegionMapper Cnt(this, Body);
610ee02499aSAlex Lorenz     Cnt.beginRegion();
6114cb85f36SJustin Bogner     Visit(Body);
612ee02499aSAlex Lorenz   }
613ee02499aSAlex Lorenz 
614ee02499aSAlex Lorenz   void VisitDeclStmt(const DeclStmt *S) {
615ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
616ee02499aSAlex Lorenz     for (Stmt::const_child_range I = static_cast<const Stmt *>(S)->children();
617ee02499aSAlex Lorenz          I; ++I) {
618ee02499aSAlex Lorenz       if (*I)
619ee02499aSAlex Lorenz         this->Visit(*I);
620ee02499aSAlex Lorenz     }
621ee02499aSAlex Lorenz   }
622ee02499aSAlex Lorenz 
623ee02499aSAlex Lorenz   void VisitCompoundStmt(const CompoundStmt *S) {
624ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLBracLoc());
6258e015ff4SJustin Bogner     mapSourceCodeRange(S->getRBracLoc());
626ee02499aSAlex Lorenz     for (Stmt::const_child_range I = S->children(); I; ++I) {
627ee02499aSAlex Lorenz       if (*I)
628ee02499aSAlex Lorenz         this->Visit(*I);
629ee02499aSAlex Lorenz     }
630ee02499aSAlex Lorenz   }
631ee02499aSAlex Lorenz 
632ee02499aSAlex Lorenz   void VisitReturnStmt(const ReturnStmt *S) {
633ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
634ee02499aSAlex Lorenz     if (S->getRetValue())
635ee02499aSAlex Lorenz       Visit(S->getRetValue());
636ee02499aSAlex Lorenz     setCurrentRegionUnreachable(S);
637ee02499aSAlex Lorenz   }
638ee02499aSAlex Lorenz 
639ee02499aSAlex Lorenz   void VisitGotoStmt(const GotoStmt *S) {
640ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
641ee02499aSAlex Lorenz     mapToken(S->getLabelLoc());
642ee02499aSAlex Lorenz     setCurrentRegionUnreachable(S);
643ee02499aSAlex Lorenz   }
644ee02499aSAlex Lorenz 
645ee02499aSAlex Lorenz   void VisitLabelStmt(const LabelStmt *S) {
646ee02499aSAlex Lorenz     // Counter tracks the block following the label.
647ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
648ee02499aSAlex Lorenz     Cnt.beginRegion();
649ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
650ee02499aSAlex Lorenz     // Can't map the ':' token as its location isn't known.
651ee02499aSAlex Lorenz     Visit(S->getSubStmt());
652ee02499aSAlex Lorenz   }
653ee02499aSAlex Lorenz 
654ee02499aSAlex Lorenz   void VisitBreakStmt(const BreakStmt *S) {
655ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
656ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
657ee02499aSAlex Lorenz     BreakContinueStack.back().BreakCount = addCounters(
658ee02499aSAlex Lorenz         BreakContinueStack.back().BreakCount, getCurrentRegionCount());
659ee02499aSAlex Lorenz     setCurrentRegionUnreachable(S);
660ee02499aSAlex Lorenz   }
661ee02499aSAlex Lorenz 
662ee02499aSAlex Lorenz   void VisitContinueStmt(const ContinueStmt *S) {
663ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
664ee02499aSAlex Lorenz     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
665ee02499aSAlex Lorenz     BreakContinueStack.back().ContinueCount = addCounters(
666ee02499aSAlex Lorenz         BreakContinueStack.back().ContinueCount, getCurrentRegionCount());
667ee02499aSAlex Lorenz     setCurrentRegionUnreachable(S);
668ee02499aSAlex Lorenz   }
669ee02499aSAlex Lorenz 
670ee02499aSAlex Lorenz   void VisitWhileStmt(const WhileStmt *S) {
671ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
672ee02499aSAlex Lorenz     // Counter tracks the body of the loop.
673ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
674ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
675ee02499aSAlex Lorenz     // Visit the body region first so the break/continue adjustments can be
676ee02499aSAlex Lorenz     // included when visiting the condition.
677ee02499aSAlex Lorenz     Cnt.beginRegion();
6784cb85f36SJustin Bogner     Visit(S->getBody());
679ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
680ee02499aSAlex Lorenz 
681ee02499aSAlex Lorenz     // ...then go back and propagate counts through the condition. The count
682ee02499aSAlex Lorenz     // at the start of the condition is the sum of the incoming edges,
683ee02499aSAlex Lorenz     // the backedge from the end of the loop body, and the edges from
684ee02499aSAlex Lorenz     // continue statements.
685ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
686ee02499aSAlex Lorenz     Cnt.setCurrentRegionCount(
687ee02499aSAlex Lorenz         addCounters(Cnt.getParentCount(),
688ee02499aSAlex Lorenz                     addCounters(Cnt.getAdjustedCount(), BC.ContinueCount)));
689ee02499aSAlex Lorenz     beginSourceRegionGroup(S->getCond());
690ee02499aSAlex Lorenz     Visit(S->getCond());
691ee02499aSAlex Lorenz     endSourceRegionGroup();
692ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
693ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
694ee02499aSAlex Lorenz   }
695ee02499aSAlex Lorenz 
696ee02499aSAlex Lorenz   void VisitDoStmt(const DoStmt *S) {
697ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
698ee02499aSAlex Lorenz     // Counter tracks the body of the loop.
699ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
700ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
701ee02499aSAlex Lorenz     Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
7024cb85f36SJustin Bogner     Visit(S->getBody());
703ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
704ee02499aSAlex Lorenz 
705ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
706ee02499aSAlex Lorenz     // The count at the start of the condition is equal to the count at the
707ee02499aSAlex Lorenz     // end of the body. The adjusted count does not include either the
708ee02499aSAlex Lorenz     // fall-through count coming into the loop or the continue count, so add
709ee02499aSAlex Lorenz     // both of those separately. This is coincidentally the same equation as
710ee02499aSAlex Lorenz     // with while loops but for different reasons.
711ee02499aSAlex Lorenz     Cnt.setCurrentRegionCount(
712ee02499aSAlex Lorenz         addCounters(Cnt.getParentCount(),
713ee02499aSAlex Lorenz                     addCounters(Cnt.getAdjustedCount(), BC.ContinueCount)));
714ee02499aSAlex Lorenz     Visit(S->getCond());
715ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
716ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
717ee02499aSAlex Lorenz   }
718ee02499aSAlex Lorenz 
719ee02499aSAlex Lorenz   void VisitForStmt(const ForStmt *S) {
720ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
721ee02499aSAlex Lorenz     if (S->getInit())
722ee02499aSAlex Lorenz       Visit(S->getInit());
723ee02499aSAlex Lorenz 
724ee02499aSAlex Lorenz     // Counter tracks the body of the loop.
725ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
726ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
727ee02499aSAlex Lorenz     // Visit the body region first. (This is basically the same as a while
728ee02499aSAlex Lorenz     // loop; see further comments in VisitWhileStmt.)
729ee02499aSAlex Lorenz     Cnt.beginRegion();
7304cb85f36SJustin Bogner     Visit(S->getBody());
731ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
732ee02499aSAlex Lorenz 
733ee02499aSAlex Lorenz     // The increment is essentially part of the body but it needs to include
734ee02499aSAlex Lorenz     // the count for all the continue statements.
735ee02499aSAlex Lorenz     if (S->getInc()) {
736ee02499aSAlex Lorenz       Cnt.setCurrentRegionCount(addCounters(
737ee02499aSAlex Lorenz           getCurrentRegionCount(), BreakContinueStack.back().ContinueCount));
738ee02499aSAlex Lorenz       beginSourceRegionGroup(S->getInc());
739ee02499aSAlex Lorenz       Visit(S->getInc());
740ee02499aSAlex Lorenz       endSourceRegionGroup();
741ee02499aSAlex Lorenz       Cnt.adjustForControlFlow();
742ee02499aSAlex Lorenz     }
743ee02499aSAlex Lorenz 
744ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
745ee02499aSAlex Lorenz 
746ee02499aSAlex Lorenz     // ...then go back and propagate counts through the condition.
747ee02499aSAlex Lorenz     if (S->getCond()) {
748ee02499aSAlex Lorenz       Cnt.setCurrentRegionCount(
749ee02499aSAlex Lorenz           addCounters(addCounters(Cnt.getParentCount(), Cnt.getAdjustedCount()),
750ee02499aSAlex Lorenz                       BC.ContinueCount));
751ee02499aSAlex Lorenz       beginSourceRegionGroup(S->getCond());
752ee02499aSAlex Lorenz       Visit(S->getCond());
753ee02499aSAlex Lorenz       endSourceRegionGroup();
754ee02499aSAlex Lorenz       Cnt.adjustForControlFlow();
755ee02499aSAlex Lorenz     }
756ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
757ee02499aSAlex Lorenz   }
758ee02499aSAlex Lorenz 
759ee02499aSAlex Lorenz   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
760ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
761ee02499aSAlex Lorenz     Visit(S->getRangeStmt());
762ee02499aSAlex Lorenz     Visit(S->getBeginEndStmt());
763ee02499aSAlex Lorenz     // Counter tracks the body of the loop.
764ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
765ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
766ee02499aSAlex Lorenz     // Visit the body region first. (This is basically the same as a while
767ee02499aSAlex Lorenz     // loop; see further comments in VisitWhileStmt.)
768ee02499aSAlex Lorenz     Cnt.beginRegion();
7694cb85f36SJustin Bogner     Visit(S->getBody());
770ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
771ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
772ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
773ee02499aSAlex Lorenz   }
774ee02499aSAlex Lorenz 
775ee02499aSAlex Lorenz   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
776ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
777ee02499aSAlex Lorenz     Visit(S->getElement());
778ee02499aSAlex Lorenz     // Counter tracks the body of the loop.
779ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
780ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
781fdd769e8SAlex Lorenz     Cnt.beginRegion();
7824cb85f36SJustin Bogner     Visit(S->getBody());
783ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
784ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
785ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount));
786ee02499aSAlex Lorenz   }
787ee02499aSAlex Lorenz 
788ee02499aSAlex Lorenz   void VisitSwitchStmt(const SwitchStmt *S) {
789ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
790ee02499aSAlex Lorenz     Visit(S->getCond());
791ee02499aSAlex Lorenz     BreakContinueStack.push_back(BreakContinue());
792ee02499aSAlex Lorenz     // Map the '}' for the body to have the same count as the regions after
793ee02499aSAlex Lorenz     // the switch.
794ee02499aSAlex Lorenz     SourceLocation RBracLoc;
795ee02499aSAlex Lorenz     if (const auto *CS = dyn_cast<CompoundStmt>(S->getBody())) {
796ee02499aSAlex Lorenz       mapSourceCodeRange(CS->getLBracLoc());
797ee02499aSAlex Lorenz       setCurrentRegionUnreachable(S);
798ee02499aSAlex Lorenz       for (Stmt::const_child_range I = CS->children(); I; ++I) {
799ee02499aSAlex Lorenz         if (*I)
800ee02499aSAlex Lorenz           this->Visit(*I);
801ee02499aSAlex Lorenz       }
802ee02499aSAlex Lorenz       RBracLoc = CS->getRBracLoc();
803ee02499aSAlex Lorenz     } else {
804ee02499aSAlex Lorenz       setCurrentRegionUnreachable(S);
805ee02499aSAlex Lorenz       Visit(S->getBody());
806ee02499aSAlex Lorenz     }
807ee02499aSAlex Lorenz     // If the switch is inside a loop, add the continue counts.
808ee02499aSAlex Lorenz     BreakContinue BC = BreakContinueStack.pop_back_val();
809ee02499aSAlex Lorenz     if (!BreakContinueStack.empty())
810ee02499aSAlex Lorenz       BreakContinueStack.back().ContinueCount = addCounters(
811ee02499aSAlex Lorenz           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
812ee02499aSAlex Lorenz     // Counter tracks the exit block of the switch.
813ee02499aSAlex Lorenz     RegionMapper ExitCnt(this, S);
814ee02499aSAlex Lorenz     ExitCnt.beginRegion();
815ee02499aSAlex Lorenz     if (RBracLoc.isValid())
816ee02499aSAlex Lorenz       mapSourceCodeRange(RBracLoc);
817ee02499aSAlex Lorenz   }
818ee02499aSAlex Lorenz 
819ee02499aSAlex Lorenz   void VisitCaseStmt(const CaseStmt *S) {
820ee02499aSAlex Lorenz     // Counter for this particular case. This counts only jumps from the
821ee02499aSAlex Lorenz     // switch header and does not include fallthrough from the case before
822ee02499aSAlex Lorenz     // this one.
823ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
824ee02499aSAlex Lorenz     Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
825ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
826ee02499aSAlex Lorenz     mapToken(S->getColonLoc());
827ee02499aSAlex Lorenz     Visit(S->getSubStmt());
828ee02499aSAlex Lorenz   }
829ee02499aSAlex Lorenz 
830ee02499aSAlex Lorenz   void VisitDefaultStmt(const DefaultStmt *S) {
831ee02499aSAlex Lorenz     // Counter for this default case. This does not include fallthrough from
832ee02499aSAlex Lorenz     // the previous case.
833ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
834ee02499aSAlex Lorenz     Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
835ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
836ee02499aSAlex Lorenz     mapToken(S->getColonLoc());
837ee02499aSAlex Lorenz     Visit(S->getSubStmt());
838ee02499aSAlex Lorenz   }
839ee02499aSAlex Lorenz 
840ee02499aSAlex Lorenz   void VisitIfStmt(const IfStmt *S) {
841ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
842ee02499aSAlex Lorenz     Visit(S->getCond());
843ee02499aSAlex Lorenz     mapToken(S->getElseLoc());
844ee02499aSAlex Lorenz 
845ee02499aSAlex Lorenz     // Counter tracks the "then" part of an if statement. The count for
846ee02499aSAlex Lorenz     // the "else" part, if it exists, will be calculated from this counter.
847ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
848ee02499aSAlex Lorenz     Cnt.beginRegion();
8494cb85f36SJustin Bogner     Visit(S->getThen());
850ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
851ee02499aSAlex Lorenz 
852ee02499aSAlex Lorenz     if (S->getElse()) {
853ee02499aSAlex Lorenz       Cnt.beginElseRegion();
8544cb85f36SJustin Bogner       Visit(S->getElse());
855ee02499aSAlex Lorenz       Cnt.adjustForControlFlow();
856ee02499aSAlex Lorenz     }
857ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion();
858ee02499aSAlex Lorenz   }
859ee02499aSAlex Lorenz 
860ee02499aSAlex Lorenz   void VisitCXXTryStmt(const CXXTryStmt *S) {
861ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
862ee02499aSAlex Lorenz     Visit(S->getTryBlock());
863ee02499aSAlex Lorenz     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
864ee02499aSAlex Lorenz       Visit(S->getHandler(I));
865ee02499aSAlex Lorenz     // Counter tracks the continuation block of the try statement.
866ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
867ee02499aSAlex Lorenz     Cnt.beginRegion();
868ee02499aSAlex Lorenz   }
869ee02499aSAlex Lorenz 
870ee02499aSAlex Lorenz   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
871ee02499aSAlex Lorenz     mapSourceCodeRange(S->getLocStart());
872ee02499aSAlex Lorenz     // Counter tracks the catch statement's handler block.
873ee02499aSAlex Lorenz     RegionMapper Cnt(this, S);
874ee02499aSAlex Lorenz     Cnt.beginRegion();
8754cb85f36SJustin Bogner     Visit(S->getHandlerBlock());
876ee02499aSAlex Lorenz   }
877ee02499aSAlex Lorenz 
878ee02499aSAlex Lorenz   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
879ee02499aSAlex Lorenz     Visit(E->getCond());
880ee02499aSAlex Lorenz     mapToken(E->getQuestionLoc());
8818e015ff4SJustin Bogner     mapToken(E->getColonLoc());
882ee02499aSAlex Lorenz 
883ee02499aSAlex Lorenz     // Counter tracks the "true" part of a conditional operator. The
884ee02499aSAlex Lorenz     // count in the "false" part will be calculated from this counter.
885ee02499aSAlex Lorenz     RegionMapper Cnt(this, E);
886ee02499aSAlex Lorenz     Cnt.beginRegion();
887ee02499aSAlex Lorenz     Visit(E->getTrueExpr());
888ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
889ee02499aSAlex Lorenz 
890ee02499aSAlex Lorenz     Cnt.beginElseRegion();
891ee02499aSAlex Lorenz     Visit(E->getFalseExpr());
892ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
893ee02499aSAlex Lorenz 
894ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion();
895ee02499aSAlex Lorenz   }
896ee02499aSAlex Lorenz 
897ee02499aSAlex Lorenz   void VisitBinLAnd(const BinaryOperator *E) {
898ee02499aSAlex Lorenz     Visit(E->getLHS());
899ee02499aSAlex Lorenz     mapToken(E->getOperatorLoc());
900ee02499aSAlex Lorenz     // Counter tracks the right hand side of a logical and operator.
901ee02499aSAlex Lorenz     RegionMapper Cnt(this, E);
902ee02499aSAlex Lorenz     Cnt.beginRegion();
903ee02499aSAlex Lorenz     Visit(E->getRHS());
904ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
905ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion();
906ee02499aSAlex Lorenz   }
907ee02499aSAlex Lorenz 
908ee02499aSAlex Lorenz   void VisitBinLOr(const BinaryOperator *E) {
909ee02499aSAlex Lorenz     Visit(E->getLHS());
910ee02499aSAlex Lorenz     mapToken(E->getOperatorLoc());
911ee02499aSAlex Lorenz     // Counter tracks the right hand side of a logical or operator.
912ee02499aSAlex Lorenz     RegionMapper Cnt(this, E);
913ee02499aSAlex Lorenz     Cnt.beginRegion();
914ee02499aSAlex Lorenz     Visit(E->getRHS());
915ee02499aSAlex Lorenz     Cnt.adjustForControlFlow();
916ee02499aSAlex Lorenz     Cnt.applyAdjustmentsToRegion();
917ee02499aSAlex Lorenz   }
918ee02499aSAlex Lorenz 
919ee02499aSAlex Lorenz   void VisitParenExpr(const ParenExpr *E) {
920ee02499aSAlex Lorenz     mapToken(E->getLParen());
921ee02499aSAlex Lorenz     Visit(E->getSubExpr());
922ee02499aSAlex Lorenz     mapToken(E->getRParen());
923ee02499aSAlex Lorenz   }
924ee02499aSAlex Lorenz 
925ee02499aSAlex Lorenz   void VisitBinaryOperator(const BinaryOperator *E) {
926ee02499aSAlex Lorenz     Visit(E->getLHS());
927ee02499aSAlex Lorenz     mapToken(E->getOperatorLoc());
928ee02499aSAlex Lorenz     Visit(E->getRHS());
929ee02499aSAlex Lorenz   }
930ee02499aSAlex Lorenz 
931ee02499aSAlex Lorenz   void VisitUnaryOperator(const UnaryOperator *E) {
932ee02499aSAlex Lorenz     bool Postfix = E->isPostfix();
933ee02499aSAlex Lorenz     if (!Postfix)
934ee02499aSAlex Lorenz       mapToken(E->getOperatorLoc());
935ee02499aSAlex Lorenz     Visit(E->getSubExpr());
936ee02499aSAlex Lorenz     if (Postfix)
937ee02499aSAlex Lorenz       mapToken(E->getOperatorLoc());
938ee02499aSAlex Lorenz   }
939ee02499aSAlex Lorenz 
940ee02499aSAlex Lorenz   void VisitMemberExpr(const MemberExpr *E) {
941ee02499aSAlex Lorenz     Visit(E->getBase());
942ee02499aSAlex Lorenz     mapToken(E->getMemberLoc());
943ee02499aSAlex Lorenz   }
944ee02499aSAlex Lorenz 
945ee02499aSAlex Lorenz   void VisitCallExpr(const CallExpr *E) {
946ee02499aSAlex Lorenz     Visit(E->getCallee());
947ee02499aSAlex Lorenz     for (const auto &Arg : E->arguments())
948ee02499aSAlex Lorenz       Visit(Arg);
949ee02499aSAlex Lorenz     mapToken(E->getRParenLoc());
950ee02499aSAlex Lorenz   }
951ee02499aSAlex Lorenz 
952ee02499aSAlex Lorenz   void VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
953ee02499aSAlex Lorenz     Visit(E->getLHS());
954ee02499aSAlex Lorenz     Visit(E->getRHS());
955ee02499aSAlex Lorenz     mapToken(E->getRBracketLoc());
956ee02499aSAlex Lorenz   }
957ee02499aSAlex Lorenz 
958ee02499aSAlex Lorenz   void VisitCStyleCastExpr(const CStyleCastExpr *E) {
959ee02499aSAlex Lorenz     mapToken(E->getLParenLoc());
960ee02499aSAlex Lorenz     mapToken(E->getRParenLoc());
961ee02499aSAlex Lorenz     Visit(E->getSubExpr());
962ee02499aSAlex Lorenz   }
963ee02499aSAlex Lorenz 
964ee02499aSAlex Lorenz   // Map literals as tokens so that the macros like #define PI 3.14
965ee02499aSAlex Lorenz   // won't generate coverage mapping regions.
966ee02499aSAlex Lorenz 
967ee02499aSAlex Lorenz   void VisitIntegerLiteral(const IntegerLiteral *E) {
968ee02499aSAlex Lorenz     mapToken(E->getLocStart());
969ee02499aSAlex Lorenz   }
970ee02499aSAlex Lorenz 
971ee02499aSAlex Lorenz   void VisitFloatingLiteral(const FloatingLiteral *E) {
972ee02499aSAlex Lorenz     mapToken(E->getLocStart());
973ee02499aSAlex Lorenz   }
974ee02499aSAlex Lorenz 
975ee02499aSAlex Lorenz   void VisitCharacterLiteral(const CharacterLiteral *E) {
976ee02499aSAlex Lorenz     mapToken(E->getLocStart());
977ee02499aSAlex Lorenz   }
978ee02499aSAlex Lorenz 
979ee02499aSAlex Lorenz   void VisitStringLiteral(const StringLiteral *E) {
980ee02499aSAlex Lorenz     mapToken(E->getLocStart());
981ee02499aSAlex Lorenz   }
982ee02499aSAlex Lorenz 
983ee02499aSAlex Lorenz   void VisitImaginaryLiteral(const ImaginaryLiteral *E) {
984ee02499aSAlex Lorenz     mapToken(E->getLocStart());
985ee02499aSAlex Lorenz   }
98601a0d062SAlex Lorenz 
98701a0d062SAlex Lorenz   void VisitObjCMessageExpr(const ObjCMessageExpr *E) {
98801a0d062SAlex Lorenz     mapToken(E->getLeftLoc());
98901a0d062SAlex Lorenz     for (Stmt::const_child_range I = static_cast<const Stmt*>(E)->children(); I;
99001a0d062SAlex Lorenz          ++I) {
99101a0d062SAlex Lorenz       if (*I)
99201a0d062SAlex Lorenz         this->Visit(*I);
99301a0d062SAlex Lorenz     }
99401a0d062SAlex Lorenz     mapToken(E->getRightLoc());
99501a0d062SAlex Lorenz   }
996ee02499aSAlex Lorenz };
997ee02499aSAlex Lorenz }
998ee02499aSAlex Lorenz 
999ee02499aSAlex Lorenz static bool isMachO(const CodeGenModule &CGM) {
1000ee02499aSAlex Lorenz   return CGM.getTarget().getTriple().isOSBinFormatMachO();
1001ee02499aSAlex Lorenz }
1002ee02499aSAlex Lorenz 
1003ee02499aSAlex Lorenz static StringRef getCoverageSection(const CodeGenModule &CGM) {
1004ee02499aSAlex Lorenz   return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap";
1005ee02499aSAlex Lorenz }
1006ee02499aSAlex Lorenz 
1007f2cf38e0SAlex Lorenz static void dump(llvm::raw_ostream &OS, const CoverageMappingRecord &Function) {
1008f2cf38e0SAlex Lorenz   OS << Function.FunctionName << ":\n";
1009f2cf38e0SAlex Lorenz   CounterMappingContext Ctx(Function.Expressions);
1010f2cf38e0SAlex Lorenz   for (const auto &R : Function.MappingRegions) {
1011f2cf38e0SAlex Lorenz     OS.indent(2);
1012f2cf38e0SAlex Lorenz     switch (R.Kind) {
1013f2cf38e0SAlex Lorenz     case CounterMappingRegion::CodeRegion:
1014f2cf38e0SAlex Lorenz       break;
1015f2cf38e0SAlex Lorenz     case CounterMappingRegion::ExpansionRegion:
1016f2cf38e0SAlex Lorenz       OS << "Expansion,";
1017f2cf38e0SAlex Lorenz       break;
1018f2cf38e0SAlex Lorenz     case CounterMappingRegion::SkippedRegion:
1019f2cf38e0SAlex Lorenz       OS << "Skipped,";
1020f2cf38e0SAlex Lorenz       break;
1021f2cf38e0SAlex Lorenz     }
1022f2cf38e0SAlex Lorenz 
1023f2cf38e0SAlex Lorenz     OS << "File " << R.FileID << ", " << R.LineStart << ":"
1024f2cf38e0SAlex Lorenz            << R.ColumnStart << " -> " << R.LineEnd << ":" << R.ColumnEnd
1025f2cf38e0SAlex Lorenz            << " = ";
1026f69dc349SJustin Bogner     Ctx.dump(R.Count, OS);
1027f2cf38e0SAlex Lorenz     OS << " (HasCodeBefore = " << R.HasCodeBefore;
1028f2cf38e0SAlex Lorenz     if (R.Kind == CounterMappingRegion::ExpansionRegion)
1029f2cf38e0SAlex Lorenz       OS << ", Expanded file = " << R.ExpandedFileID;
1030f2cf38e0SAlex Lorenz 
1031f2cf38e0SAlex Lorenz     OS << ")\n";
1032f2cf38e0SAlex Lorenz   }
1033f2cf38e0SAlex Lorenz }
1034f2cf38e0SAlex Lorenz 
1035ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord(
1036f2cf38e0SAlex Lorenz     llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue,
10371d45c5bcSAlex Lorenz     uint64_t FunctionHash, const std::string &CoverageMapping) {
1038ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1039ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
10401d45c5bcSAlex Lorenz   auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
1041ee02499aSAlex Lorenz   auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
1042ee02499aSAlex Lorenz   if (!FunctionRecordTy) {
10431d45c5bcSAlex Lorenz     llvm::Type *FunctionRecordTypes[] = {Int8PtrTy, Int32Ty, Int32Ty, Int64Ty};
1044ee02499aSAlex Lorenz     FunctionRecordTy =
1045ee02499aSAlex Lorenz         llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes));
1046ee02499aSAlex Lorenz   }
1047ee02499aSAlex Lorenz 
1048ee02499aSAlex Lorenz   llvm::Constant *FunctionRecordVals[] = {
1049ee02499aSAlex Lorenz       llvm::ConstantExpr::getBitCast(FunctionName, Int8PtrTy),
1050f2cf38e0SAlex Lorenz       llvm::ConstantInt::get(Int32Ty, FunctionNameValue.size()),
10511d45c5bcSAlex Lorenz       llvm::ConstantInt::get(Int32Ty, CoverageMapping.size()),
10521d45c5bcSAlex Lorenz       llvm::ConstantInt::get(Int64Ty, FunctionHash)};
1053ee02499aSAlex Lorenz   FunctionRecords.push_back(llvm::ConstantStruct::get(
1054ee02499aSAlex Lorenz       FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
1055ee02499aSAlex Lorenz   CoverageMappings += CoverageMapping;
1056f2cf38e0SAlex Lorenz 
1057f2cf38e0SAlex Lorenz   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1058f2cf38e0SAlex Lorenz     // Dump the coverage mapping data for this function by decoding the
1059f2cf38e0SAlex Lorenz     // encoded data. This allows us to dump the mapping regions which were
1060f2cf38e0SAlex Lorenz     // also processed by the CoverageMappingWriter which performs
1061f2cf38e0SAlex Lorenz     // additional minimization operations such as reducing the number of
1062f2cf38e0SAlex Lorenz     // expressions.
1063f2cf38e0SAlex Lorenz     std::vector<StringRef> Filenames;
1064f2cf38e0SAlex Lorenz     std::vector<CounterExpression> Expressions;
1065f2cf38e0SAlex Lorenz     std::vector<CounterMappingRegion> Regions;
1066f2cf38e0SAlex Lorenz     llvm::SmallVector<StringRef, 16> FilenameRefs;
1067f2cf38e0SAlex Lorenz     FilenameRefs.resize(FileEntries.size());
1068f2cf38e0SAlex Lorenz     for (const auto &Entry : FileEntries)
1069f2cf38e0SAlex Lorenz       FilenameRefs[Entry.second] = Entry.first->getName();
1070f2cf38e0SAlex Lorenz     RawCoverageMappingReader Reader(FunctionNameValue, CoverageMapping,
1071f2cf38e0SAlex Lorenz                                     FilenameRefs,
1072f2cf38e0SAlex Lorenz                                     Filenames, Expressions, Regions);
1073f2cf38e0SAlex Lorenz     CoverageMappingRecord FunctionRecord;
1074f2cf38e0SAlex Lorenz     if (Reader.read(FunctionRecord))
1075f2cf38e0SAlex Lorenz       return;
1076f2cf38e0SAlex Lorenz     dump(llvm::outs(), FunctionRecord);
1077f2cf38e0SAlex Lorenz   }
1078ee02499aSAlex Lorenz }
1079ee02499aSAlex Lorenz 
1080ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() {
1081ee02499aSAlex Lorenz   if (FunctionRecords.empty())
1082ee02499aSAlex Lorenz     return;
1083ee02499aSAlex Lorenz   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1084ee02499aSAlex Lorenz   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1085ee02499aSAlex Lorenz 
1086ee02499aSAlex Lorenz   // Create the filenames and merge them with coverage mappings
1087ee02499aSAlex Lorenz   llvm::SmallVector<std::string, 16> FilenameStrs;
1088ee02499aSAlex Lorenz   llvm::SmallVector<StringRef, 16> FilenameRefs;
1089ee02499aSAlex Lorenz   FilenameStrs.resize(FileEntries.size());
1090ee02499aSAlex Lorenz   FilenameRefs.resize(FileEntries.size());
1091ee02499aSAlex Lorenz   for (const auto &Entry : FileEntries) {
1092ee02499aSAlex Lorenz     llvm::SmallString<256> Path(Entry.first->getName());
1093ee02499aSAlex Lorenz     llvm::sys::fs::make_absolute(Path);
1094ee02499aSAlex Lorenz 
1095ee02499aSAlex Lorenz     auto I = Entry.second;
1096ee02499aSAlex Lorenz     FilenameStrs[I] = std::move(std::string(Path.begin(), Path.end()));
1097ee02499aSAlex Lorenz     FilenameRefs[I] = FilenameStrs[I];
1098ee02499aSAlex Lorenz   }
1099ee02499aSAlex Lorenz 
1100ee02499aSAlex Lorenz   std::string FilenamesAndCoverageMappings;
1101ee02499aSAlex Lorenz   llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1102ee02499aSAlex Lorenz   CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1103ee02499aSAlex Lorenz   OS << CoverageMappings;
1104ee02499aSAlex Lorenz   size_t CoverageMappingSize = CoverageMappings.size();
1105ee02499aSAlex Lorenz   size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1106ee02499aSAlex Lorenz   // Append extra zeroes if necessary to ensure that the size of the filenames
1107ee02499aSAlex Lorenz   // and coverage mappings is a multiple of 8.
1108ee02499aSAlex Lorenz   if (size_t Rem = OS.str().size() % 8) {
1109ee02499aSAlex Lorenz     CoverageMappingSize += 8 - Rem;
1110ee02499aSAlex Lorenz     for (size_t I = 0, S = 8 - Rem; I < S; ++I)
1111ee02499aSAlex Lorenz       OS << '\0';
1112ee02499aSAlex Lorenz   }
1113ee02499aSAlex Lorenz   auto *FilenamesAndMappingsVal =
1114ee02499aSAlex Lorenz       llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
1115ee02499aSAlex Lorenz 
1116ee02499aSAlex Lorenz   // Create the deferred function records array
1117ee02499aSAlex Lorenz   auto RecordsTy =
1118ee02499aSAlex Lorenz       llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1119ee02499aSAlex Lorenz   auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1120ee02499aSAlex Lorenz 
1121ee02499aSAlex Lorenz   // Create the coverage data record
1122ee02499aSAlex Lorenz   llvm::Type *CovDataTypes[] = {Int32Ty,   Int32Ty,
1123ee02499aSAlex Lorenz                                 Int32Ty,   Int32Ty,
1124ee02499aSAlex Lorenz                                 RecordsTy, FilenamesAndMappingsVal->getType()};
1125ee02499aSAlex Lorenz   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1126ee02499aSAlex Lorenz   llvm::Constant *TUDataVals[] = {
1127ee02499aSAlex Lorenz       llvm::ConstantInt::get(Int32Ty, FunctionRecords.size()),
1128ee02499aSAlex Lorenz       llvm::ConstantInt::get(Int32Ty, FilenamesSize),
1129ee02499aSAlex Lorenz       llvm::ConstantInt::get(Int32Ty, CoverageMappingSize),
1130ee02499aSAlex Lorenz       llvm::ConstantInt::get(Int32Ty,
1131ee02499aSAlex Lorenz                              /*Version=*/CoverageMappingVersion1),
1132ee02499aSAlex Lorenz       RecordsVal, FilenamesAndMappingsVal};
1133ee02499aSAlex Lorenz   auto CovDataVal =
1134ee02499aSAlex Lorenz       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1135ee02499aSAlex Lorenz   auto CovData = new llvm::GlobalVariable(CGM.getModule(), CovDataTy, true,
1136ee02499aSAlex Lorenz                                           llvm::GlobalValue::InternalLinkage,
1137ee02499aSAlex Lorenz                                           CovDataVal,
1138ee02499aSAlex Lorenz                                           "__llvm_coverage_mapping");
1139ee02499aSAlex Lorenz 
1140ee02499aSAlex Lorenz   CovData->setSection(getCoverageSection(CGM));
1141ee02499aSAlex Lorenz   CovData->setAlignment(8);
1142ee02499aSAlex Lorenz 
1143ee02499aSAlex Lorenz   // Make sure the data doesn't get deleted.
1144ee02499aSAlex Lorenz   CGM.addUsedGlobal(CovData);
1145ee02499aSAlex Lorenz }
1146ee02499aSAlex Lorenz 
1147ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1148ee02499aSAlex Lorenz   auto It = FileEntries.find(File);
1149ee02499aSAlex Lorenz   if (It != FileEntries.end())
1150ee02499aSAlex Lorenz     return It->second;
1151ee02499aSAlex Lorenz   unsigned FileID = FileEntries.size();
1152ee02499aSAlex Lorenz   FileEntries.insert(std::make_pair(File, FileID));
1153ee02499aSAlex Lorenz   return FileID;
1154ee02499aSAlex Lorenz }
1155ee02499aSAlex Lorenz 
1156ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D,
1157ee02499aSAlex Lorenz                                             llvm::raw_ostream &OS) {
1158ee02499aSAlex Lorenz   assert(CounterMap);
1159e5ee6c58SJustin Bogner   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1160ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1161ee02499aSAlex Lorenz   Walker.write(OS);
1162ee02499aSAlex Lorenz }
1163ee02499aSAlex Lorenz 
1164ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1165ee02499aSAlex Lorenz                                           llvm::raw_ostream &OS) {
1166ee02499aSAlex Lorenz   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1167ee02499aSAlex Lorenz   Walker.VisitDecl(D);
1168ee02499aSAlex Lorenz   Walker.write(OS);
1169ee02499aSAlex Lorenz }
1170