blob: 389d29e467b7003ffff96d764f2d99f0cdf4fb10 [file] [log] [blame]
Alex Lorenzee024992014-08-04 18:41:51 +00001//===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Instrumentation-based code coverage mapping generator
11//
12//===----------------------------------------------------------------------===//
13
14#include "CoverageMappingGen.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Lex/Lexer.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000018#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000019#include "llvm/ADT/StringExtras.h"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000020#include "llvm/ADT/Optional.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000021#include "llvm/ProfileData/Coverage/CoverageMapping.h"
22#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000025#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000026#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000027
28using namespace clang;
29using namespace CodeGen;
30using namespace llvm::coverage;
31
Vedant Kumar3919a502017-09-11 20:47:42 +000032void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Alex Lorenzee024992014-08-04 18:41:51 +000033 SkippedRanges.push_back(Range);
34}
35
36namespace {
37
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038/// A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000039class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000040 Counter Count;
41
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000043 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000046 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000047
Vedant Kumar747b0e22017-09-08 18:44:56 +000048 /// Whether this region should be emitted after its parent is emitted.
49 bool DeferRegion;
50
Vedant Kumara1c4deb2017-09-18 23:37:30 +000051 /// Whether this region is a gap region. The count from a gap region is set
52 /// as the line execution count if there are no other regions on the line.
53 bool GapRegion;
54
Justin Bogner09c71792014-10-01 03:33:49 +000055public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000056 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara1c4deb2017-09-18 23:37:30 +000057 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
58 bool GapRegion = false)
Vedant Kumar747b0e22017-09-08 18:44:56 +000059 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
Vedant Kumara1c4deb2017-09-18 23:37:30 +000060 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000061
Justin Bogner09c71792014-10-01 03:33:49 +000062 const Counter &getCounter() const { return Count; }
63
Justin Bognerbf42cfd2015-02-18 21:24:51 +000064 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000065
Justin Bognerbf42cfd2015-02-18 21:24:51 +000066 bool hasStartLoc() const { return LocStart.hasValue(); }
67
68 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
69
Stephen Kelly3cffc4c2018-08-09 20:05:18 +000070 SourceLocation getStartLoc() const LLVM_READONLY { return getBeginLoc(); }
71 SourceLocation getBeginLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000072 assert(LocStart && "Region has no start location");
73 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000074 }
75
Justin Bognerbf42cfd2015-02-18 21:24:51 +000076 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000077
Vedant Kumara14a1f92018-01-17 18:53:51 +000078 void setEndLoc(SourceLocation Loc) {
79 assert(Loc.isValid() && "Setting an invalid end location");
80 LocEnd = Loc;
81 }
Alex Lorenzee024992014-08-04 18:41:51 +000082
Craig Topper462c77b2015-09-26 05:10:14 +000083 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000084 assert(LocEnd && "Region has no end location");
85 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000086 }
Vedant Kumar747b0e22017-09-08 18:44:56 +000087
88 bool isDeferred() const { return DeferRegion; }
89
90 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Vedant Kumara1c4deb2017-09-18 23:37:30 +000091
92 bool isGap() const { return GapRegion; }
93
94 void setGap(bool Gap) { GapRegion = Gap; }
Alex Lorenzee024992014-08-04 18:41:51 +000095};
96
Vedant Kumard7369642017-07-27 02:20:25 +000097/// Spelling locations for the start and end of a source region.
98struct SpellingRegion {
99 /// The line where the region starts.
100 unsigned LineStart;
101
102 /// The column where the region starts.
103 unsigned ColumnStart;
104
105 /// The line where the region ends.
106 unsigned LineEnd;
107
108 /// The column where the region ends.
109 unsigned ColumnEnd;
110
111 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
112 SourceLocation LocEnd) {
113 LineStart = SM.getSpellingLineNumber(LocStart);
114 ColumnStart = SM.getSpellingColumnNumber(LocStart);
115 LineEnd = SM.getSpellingLineNumber(LocEnd);
116 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
117 }
118
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000119 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
120 : SpellingRegion(SM, R.getStartLoc(), R.getEndLoc()) {}
121
Vedant Kumard7369642017-07-27 02:20:25 +0000122 /// Check if the start and end locations appear in source order, i.e
123 /// top->bottom, left->right.
124 bool isInSourceOrder() const {
125 return (LineStart < LineEnd) ||
126 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
127 }
128};
129
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000130/// Provides the common functionality for the different
Alex Lorenzee024992014-08-04 18:41:51 +0000131/// coverage mapping region builders.
132class CoverageMappingBuilder {
133public:
134 CoverageMappingModuleGen &CVM;
135 SourceManager &SM;
136 const LangOptions &LangOpts;
137
138private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000139 /// Map of clang's FileIDs to IDs used for coverage mapping.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000140 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
141 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000142
143public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000144 /// The coverage mapping regions for this function
Alex Lorenzee024992014-08-04 18:41:51 +0000145 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000146 /// The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000147 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000148
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000149 /// A set of regions which can be used as a filter.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000150 ///
151 /// It is produced by emitExpansionRegions() and is used in
152 /// emitSourceRegions() to suppress producing code regions if
153 /// the same area is covered by expansion regions.
154 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
155 SourceRegionFilter;
156
Alex Lorenzee024992014-08-04 18:41:51 +0000157 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
158 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000159 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000161 /// Return the precise end location for the given token.
Alex Lorenzee024992014-08-04 18:41:51 +0000162 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000163 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
164 // macro locations, which we just treat as expanded files.
165 unsigned TokLen =
166 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
167 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000168 }
169
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000170 /// Return the start location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000171 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
172 if (Loc.isMacroID())
173 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
174 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000175 }
176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000177 /// Return the end location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000178 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
179 if (Loc.isMacroID())
180 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000181 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000182 return SM.getLocForEndOfFile(SM.getFileID(Loc));
183 }
184
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000185 /// Find out where the current file is included or macro is expanded.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000186 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
Richard Smithb5f81712018-04-30 05:25:48 +0000187 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000188 : SM.getIncludeLoc(SM.getFileID(Loc));
189 }
190
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000191 /// Return true if \c Loc is a location in a built-in macro.
Justin Bogner682bfbf2015-05-14 22:14:10 +0000192 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000193 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000194 }
195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000196 /// Check whether \c Loc is included or expanded from \c Parent.
Igor Kudrind9e1a612016-06-07 10:07:51 +0000197 bool isNestedIn(SourceLocation Loc, FileID Parent) {
198 do {
199 Loc = getIncludeOrExpansionLoc(Loc);
200 if (Loc.isInvalid())
201 return false;
202 } while (!SM.isInFileID(Loc, Parent));
203 return true;
204 }
205
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000206 /// Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000207 SourceLocation getStart(const Stmt *S) {
208 SourceLocation Loc = S->getLocStart();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000209 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000210 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000211 return Loc;
212 }
213
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000214 /// Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000215 SourceLocation getEnd(const Stmt *S) {
216 SourceLocation Loc = S->getLocEnd();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000217 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000218 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerf14b2072015-03-25 04:13:49 +0000219 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000220 }
221
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000222 /// Find the set of files we have regions for and assign IDs
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000223 ///
224 /// Fills \c Mapping with the virtual file mapping needed to write out
225 /// coverage and collects the necessary file information to emit source and
226 /// expansion regions.
227 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
228 FileIDMapping.clear();
229
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000230 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000231 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
232 for (const auto &Region : SourceRegions) {
233 SourceLocation Loc = Region.getStartLoc();
234 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000235 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000236 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000237
Vedant Kumar93205af2016-07-11 22:57:46 +0000238 // Do not map FileID's associated with system headers.
239 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
240 continue;
241
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000242 unsigned Depth = 0;
243 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000244 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000245 ++Depth;
246 FileLocs.push_back(std::make_pair(Loc, Depth));
247 }
248 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
249
250 for (const auto &FL : FileLocs) {
251 SourceLocation Loc = FL.first;
252 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
253 auto Entry = SM.getFileEntryForID(SpellingFile);
254 if (!Entry)
255 continue;
256
257 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
258 Mapping.push_back(CVM.getFileID(Entry));
259 }
260 }
261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262 /// Get the coverage mapping file ID for \c Loc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000263 ///
264 /// If such file id doesn't exist, return None.
265 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
266 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000267 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000268 return Mapping->second.first;
269 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000270 }
271
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000272 /// Gather all the regions that were skipped by the preprocessor
Alex Lorenzee024992014-08-04 18:41:51 +0000273 /// using the constructs like #if.
274 void gatherSkippedRegions() {
275 /// An array of the minimum lineStarts and the maximum lineEnds
276 /// for mapping regions from the appropriate source files.
277 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
278 FileLineRanges.resize(
279 FileIDMapping.size(),
280 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
281 for (const auto &R : MappingRegions) {
282 FileLineRanges[R.FileID].first =
283 std::min(FileLineRanges[R.FileID].first, R.LineStart);
284 FileLineRanges[R.FileID].second =
285 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
286 }
287
288 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
289 for (const auto &I : SkippedRanges) {
290 auto LocStart = I.getBegin();
291 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000292 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
293 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000294
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000295 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000296 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000297 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000298 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000299 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000300 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000301 // Make sure that we only collect the regions that are inside
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000302 // the source code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000303 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
304 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000305 MappingRegions.push_back(Region);
306 }
307 }
308
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000309 /// Generate the coverage counter mapping regions from collected
Alex Lorenzee024992014-08-04 18:41:51 +0000310 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000311 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000312 for (const auto &Region : SourceRegions) {
313 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000314
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000315 SourceLocation LocStart = Region.getStartLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000316 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000317
Vedant Kumar93205af2016-07-11 22:57:46 +0000318 // Ignore regions from system headers.
319 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
320 continue;
321
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000322 auto CovFileID = getCoverageFileID(LocStart);
323 // Ignore regions that don't have a file, such as builtin macros.
324 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000325 continue;
326
Justin Bognerf14b2072015-03-25 04:13:49 +0000327 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000328 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
329 "region spans multiple files");
330
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000331 // Don't add code regions for the area covered by expansion regions.
332 // This not only suppresses redundant regions, but sometimes prevents
333 // creating regions with wrong counters if, for example, a statement's
334 // body ends at the end of a nested macro.
335 if (Filter.count(std::make_pair(LocStart, LocEnd)))
336 continue;
337
Vedant Kumard7369642017-07-27 02:20:25 +0000338 // Find the spelling locations for the mapping region.
339 SpellingRegion SR{SM, LocStart, LocEnd};
340 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000341
342 if (Region.isGap()) {
343 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
344 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
345 SR.LineEnd, SR.ColumnEnd));
346 } else {
347 MappingRegions.push_back(CounterMappingRegion::makeRegion(
348 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
349 SR.LineEnd, SR.ColumnEnd));
350 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000351 }
352 }
353
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000354 /// Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000355 SourceRegionFilter emitExpansionRegions() {
356 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000357 for (const auto &FM : FileIDMapping) {
358 SourceLocation ExpandedLoc = FM.second.second;
359 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
360 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000361 continue;
362
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000363 auto ParentFileID = getCoverageFileID(ParentLoc);
364 if (!ParentFileID)
365 continue;
366 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
367 assert(ExpandedFileID && "expansion in uncovered file");
368
369 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
370 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
371 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000372 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000373
Vedant Kumard7369642017-07-27 02:20:25 +0000374 SpellingRegion SR{SM, ParentLoc, LocEnd};
375 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000376 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000377 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
378 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000379 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000380 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000381 }
382};
383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000384/// Creates unreachable coverage regions for the functions that
Alex Lorenzee024992014-08-04 18:41:51 +0000385/// are not emitted.
386struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
387 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
388 const LangOptions &LangOpts)
389 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
390
391 void VisitDecl(const Decl *D) {
392 if (!D->hasBody())
393 return;
394 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000395 SourceLocation Start = getStart(Body);
396 SourceLocation End = getEnd(Body);
397 if (!SM.isWrittenInSameFile(Start, End)) {
398 // Walk up to find the common ancestor.
399 // Correct the locations accordingly.
400 FileID StartFileID = SM.getFileID(Start);
401 FileID EndFileID = SM.getFileID(End);
402 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
403 Start = getIncludeOrExpansionLoc(Start);
404 assert(Start.isValid() &&
405 "Declaration start location not nested within a known region");
406 StartFileID = SM.getFileID(Start);
407 }
408 while (StartFileID != EndFileID) {
409 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
410 assert(End.isValid() &&
411 "Declaration end location not nested within a known region");
412 EndFileID = SM.getFileID(End);
413 }
414 }
415 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000416 }
417
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000418 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000419 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000420 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000421 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000422 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000423
Vedant Kumarefd319a2016-07-26 00:24:59 +0000424 if (MappingRegions.empty())
425 return;
426
Craig Topper5fc8fc22014-08-27 06:28:36 +0000427 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000428 Writer.write(OS);
429 }
430};
431
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432/// A StmtVisitor that creates coverage mapping regions which map
Alex Lorenzee024992014-08-04 18:41:51 +0000433/// from the source code locations to the PGO counters.
434struct CounterCoverageMappingBuilder
435 : public CoverageMappingBuilder,
436 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// The map of statements to count values.
Alex Lorenzee024992014-08-04 18:41:51 +0000438 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
439
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000440 /// A stack of currently live regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000441 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000442
Vedant Kumar747b0e22017-09-08 18:44:56 +0000443 /// The currently deferred region: its end location and count can be set once
444 /// its parent has been popped from the region stack.
445 Optional<SourceMappingRegion> DeferredRegion;
446
Alex Lorenzee024992014-08-04 18:41:51 +0000447 CounterExpressionBuilder Builder;
448
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// A location in the most recently visited file or macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000450 ///
451 /// This is used to adjust the active source regions appropriately when
452 /// expressions cross file or macro boundaries.
453 SourceLocation MostRecentLocation;
454
Vedant Kumar8046d222017-11-09 02:33:39 +0000455 /// Location of the last terminated region.
456 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
457
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000458 /// Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000459 Counter subtractCounters(Counter LHS, Counter RHS) {
460 return Builder.subtract(LHS, RHS);
461 }
462
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000463 /// Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000464 Counter addCounters(Counter LHS, Counter RHS) {
465 return Builder.add(LHS, RHS);
466 }
467
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000468 Counter addCounters(Counter C1, Counter C2, Counter C3) {
469 return addCounters(addCounters(C1, C2), C3);
470 }
471
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000472 /// Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000473 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000474 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000475 Counter getRegionCounter(const Stmt *S) {
476 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000477 }
478
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000479 /// Push a region onto the stack.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000480 ///
481 /// Returns the index on the stack where the region was pushed. This can be
482 /// used with popRegions to exit a "scope", ending the region that was pushed.
483 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
484 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000485 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000486 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000487 completeDeferred(Count, MostRecentLocation);
488 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000489 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000490
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000491 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000492 }
493
Vedant Kumar747b0e22017-09-08 18:44:56 +0000494 /// Complete any pending deferred region by setting its end location and
495 /// count, and then pushing it onto the region stack.
496 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
497 size_t Index = RegionStack.size();
498 if (!DeferredRegion)
499 return Index;
500
501 // Consume the pending region.
502 SourceMappingRegion DR = DeferredRegion.getValue();
503 DeferredRegion = None;
504
505 // If the region ends in an expansion, find the expansion site.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000506 FileID StartFile = SM.getFileID(DR.getStartLoc());
507 if (SM.getFileID(DeferredEndLoc) != StartFile) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000508 if (isNestedIn(DeferredEndLoc, StartFile)) {
509 do {
510 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
511 } while (StartFile != SM.getFileID(DeferredEndLoc));
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000512 } else {
513 return Index;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000514 }
515 }
516
517 // The parent of this deferred region ends where the containing decl ends,
518 // so the region isn't useful.
519 if (DR.getStartLoc() == DeferredEndLoc)
520 return Index;
521
522 // If we're visiting statements in non-source order (e.g switch cases or
523 // a loop condition) we can't construct a sensible deferred region.
524 if (!SpellingRegion(SM, DR.getStartLoc(), DeferredEndLoc).isInSourceOrder())
525 return Index;
526
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000527 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000528 DR.setCounter(Count);
529 DR.setEndLoc(DeferredEndLoc);
530 handleFileExit(DeferredEndLoc);
531 RegionStack.push_back(DR);
532 return Index;
533 }
534
Vedant Kumar8046d222017-11-09 02:33:39 +0000535 /// Complete a deferred region created after a terminated region at the
536 /// top-level.
537 void completeTopLevelDeferredRegion(Counter Count,
538 SourceLocation DeferredEndLoc) {
539 if (DeferredRegion || !LastTerminatedRegion)
540 return;
541
542 if (LastTerminatedRegion->second != RegionStack.size())
543 return;
544
545 SourceLocation Start = LastTerminatedRegion->first;
546 if (SM.getFileID(Start) != SM.getMainFileID())
547 return;
548
549 SourceMappingRegion DR = RegionStack.back();
550 DR.setStartLoc(Start);
551 DR.setDeferred(false);
552 DeferredRegion = DR;
553 completeDeferred(Count, DeferredEndLoc);
554 }
555
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000556 /// Pop regions from the stack into the function's list of regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000557 ///
558 /// Adds all regions from \c ParentIndex to the top of the stack to the
559 /// function's \c SourceRegions.
560 void popRegions(size_t ParentIndex) {
561 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000562 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000563 while (RegionStack.size() > ParentIndex) {
564 SourceMappingRegion &Region = RegionStack.back();
565 if (Region.hasStartLoc()) {
566 SourceLocation StartLoc = Region.getStartLoc();
567 SourceLocation EndLoc = Region.hasEndLoc()
568 ? Region.getEndLoc()
569 : RegionStack[ParentIndex].getEndLoc();
570 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
571 // The region ends in a nested file or macro expansion. Create a
572 // separate region for each expansion.
573 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
574 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
575
Igor Kudrin8545dae2016-08-29 11:48:50 +0000576 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
577 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000578
Justin Bognerf14b2072015-03-25 04:13:49 +0000579 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerdceaaad2015-07-17 23:31:21 +0000580 if (EndLoc.isInvalid())
581 llvm::report_fatal_error("File exit not handled before popRegions");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000582 }
583 Region.setEndLoc(EndLoc);
584
585 MostRecentLocation = EndLoc;
586 // If this region happens to span an entire expansion, we need to make
587 // sure we don't overlap the parent region with it.
588 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
589 EndLoc == getEndOfFileOrMacro(EndLoc))
590 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
591
592 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000593 assert(SpellingRegion(SM, Region).isInSourceOrder());
Craig Topperf36a5c42015-09-26 05:10:16 +0000594 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000595
596 if (ParentOfDeferredRegion) {
597 ParentOfDeferredRegion = false;
598
599 // If there's an existing deferred region, keep the old one, because
600 // it means there are two consecutive returns (or a similar pattern).
601 if (!DeferredRegion.hasValue() &&
602 // File IDs aren't gathered within macro expansions, so it isn't
603 // useful to try and create a deferred region inside of one.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000604 !EndLoc.isMacroID())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000605 DeferredRegion =
606 SourceMappingRegion(Counter::getZero(), EndLoc, None);
607 }
608 } else if (Region.isDeferred()) {
609 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
610 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000611 }
612 RegionStack.pop_back();
Vedant Kumar8046d222017-11-09 02:33:39 +0000613
614 // If the zero region pushed after the last terminated region no longer
615 // exists, clear its cached information.
616 if (LastTerminatedRegion &&
617 RegionStack.size() < LastTerminatedRegion->second)
618 LastTerminatedRegion = None;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000619 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000620 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000621 }
622
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000623 /// Return the currently active region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000624 SourceMappingRegion &getRegion() {
625 assert(!RegionStack.empty() && "statement has no region");
626 return RegionStack.back();
627 }
Alex Lorenzee024992014-08-04 18:41:51 +0000628
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000629 /// Propagate counts through the children of \c S.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000630 Counter propagateCounts(Counter TopCount, const Stmt *S) {
Vedant Kumar78386962017-07-27 02:20:20 +0000631 SourceLocation StartLoc = getStart(S);
632 SourceLocation EndLoc = getEnd(S);
633 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000634 Visit(S);
635 Counter ExitCount = getRegion().getCounter();
636 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000637
638 // The statement may be spanned by an expansion. Make sure we handle a file
639 // exit out of this expansion before moving to the next statement.
Vedant Kumar78386962017-07-27 02:20:20 +0000640 if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart()))
641 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000642
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000643 return ExitCount;
644 }
Alex Lorenzee024992014-08-04 18:41:51 +0000645
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000646 /// Check whether a region with bounds \c StartLoc and \c EndLoc
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000647 /// is already added to \c SourceRegions.
648 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
649 return SourceRegions.rend() !=
650 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
651 [&](const SourceMappingRegion &Region) {
652 return Region.getStartLoc() == StartLoc &&
653 Region.getEndLoc() == EndLoc;
654 });
655 }
656
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000657 /// Adjust the most recently visited location to \c EndLoc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000658 ///
659 /// This should be used after visiting any statements in non-source order.
660 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
661 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000662 // The code region for a whole macro is created in handleFileExit() when
663 // it detects exiting of the virtual file of that macro. If we visited
664 // statements in non-source order, we might already have such a region
665 // added, for example, if a body of a loop is divided among multiple
666 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000667 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000668 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
669 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
670 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000671 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
672 }
Alex Lorenzee024992014-08-04 18:41:51 +0000673
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000674 /// Adjust regions and state when \c NewLoc exits a file.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000675 ///
676 /// If moving from our most recently tracked location to \c NewLoc exits any
677 /// files, this adjusts our current region stack and creates the file regions
678 /// for the exited file.
679 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000680 if (NewLoc.isInvalid() ||
681 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000682 return;
683
684 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
685 // find the common ancestor.
686 SourceLocation LCA = NewLoc;
687 FileID ParentFile = SM.getFileID(LCA);
688 while (!isNestedIn(MostRecentLocation, ParentFile)) {
689 LCA = getIncludeOrExpansionLoc(LCA);
690 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
691 // Since there isn't a common ancestor, no file was exited. We just need
692 // to adjust our location to the new file.
693 MostRecentLocation = NewLoc;
694 return;
695 }
696 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000697 }
698
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000699 llvm::SmallSet<SourceLocation, 8> StartLocs;
700 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000701 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
702 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000703 continue;
Pete Cooper57d3f142015-07-30 17:22:52 +0000704 SourceLocation Loc = I.getStartLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000705 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000706 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000707 break;
708 }
Alex Lorenzee024992014-08-04 18:41:51 +0000709
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000710 while (!SM.isInFileID(Loc, ParentFile)) {
711 // The most nested region for each start location is the one with the
712 // correct count. We avoid creating redundant regions by stopping once
713 // we've seen this region.
714 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000715 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000716 getEndOfFileOrMacro(Loc));
717 Loc = getIncludeOrExpansionLoc(Loc);
718 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000719 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000720 }
721
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000722 if (ParentCounter) {
723 // If the file is contained completely by another region and doesn't
724 // immediately start its own region, the whole file gets a region
725 // corresponding to the parent.
726 SourceLocation Loc = MostRecentLocation;
727 while (isNestedIn(Loc, ParentFile)) {
728 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000729 if (StartLocs.insert(FileStart).second) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000730 SourceRegions.emplace_back(*ParentCounter, FileStart,
731 getEndOfFileOrMacro(Loc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000732 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
733 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000734 Loc = getIncludeOrExpansionLoc(Loc);
735 }
Alex Lorenzee024992014-08-04 18:41:51 +0000736 }
737
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000738 MostRecentLocation = NewLoc;
739 }
Alex Lorenzee024992014-08-04 18:41:51 +0000740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000741 /// Ensure that \c S is included in the current region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000742 void extendRegion(const Stmt *S) {
743 SourceMappingRegion &Region = getRegion();
744 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000745
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000746 handleFileExit(StartLoc);
747 if (!Region.hasStartLoc())
748 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000749
750 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000751 }
752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000753 /// Mark \c S as a terminator, starting a zero region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000754 void terminateRegion(const Stmt *S) {
755 extendRegion(S);
756 SourceMappingRegion &Region = getRegion();
Vedant Kumar8046d222017-11-09 02:33:39 +0000757 SourceLocation EndLoc = getEnd(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000758 if (!Region.hasEndLoc())
Vedant Kumar8046d222017-11-09 02:33:39 +0000759 Region.setEndLoc(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000760 pushRegion(Counter::getZero());
Vedant Kumar8046d222017-11-09 02:33:39 +0000761 auto &ZeroRegion = getRegion();
762 ZeroRegion.setDeferred(true);
763 LastTerminatedRegion = {EndLoc, RegionStack.size()};
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000764 }
Alex Lorenzee024992014-08-04 18:41:51 +0000765
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000766 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
767 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
768 SourceLocation BeforeLoc) {
769 // If the start and end locations of the gap are both within the same macro
770 // file, the range may not be in source order.
771 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
772 return None;
773 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
774 return None;
775 return {{AfterLoc, BeforeLoc}};
776 }
777
778 /// Find the source range after \p AfterStmt and before \p BeforeStmt.
779 Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
780 const Stmt *BeforeStmt) {
781 return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
782 getStart(BeforeStmt));
783 }
784
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000785 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
786 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
787 Counter Count) {
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000788 if (StartLoc == EndLoc)
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000789 return;
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000790 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000791 handleFileExit(StartLoc);
792 size_t Index = pushRegion(Count, StartLoc, EndLoc);
793 getRegion().setGap(true);
794 handleFileExit(EndLoc);
795 popRegions(Index);
796 }
797
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000798 /// Keep counts of breaks and continues inside loops.
Alex Lorenzee024992014-08-04 18:41:51 +0000799 struct BreakContinue {
800 Counter BreakCount;
801 Counter ContinueCount;
802 };
803 SmallVector<BreakContinue, 8> BreakContinueStack;
804
805 CounterCoverageMappingBuilder(
806 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000807 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000808 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000809 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
810 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000812 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000813 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000814 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000815 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000816 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000817 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000818 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000819 gatherSkippedRegions();
820
Vedant Kumarefd319a2016-07-26 00:24:59 +0000821 if (MappingRegions.empty())
822 return;
823
Justin Bogner4da909b2015-02-03 21:35:49 +0000824 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
825 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000826 Writer.write(OS);
827 }
828
Alex Lorenzee024992014-08-04 18:41:51 +0000829 void VisitStmt(const Stmt *S) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000830 if (S->getLocStart().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000831 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000832 for (const Stmt *Child : S->children())
833 if (Child)
834 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000835 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000836 }
837
Alex Lorenzee024992014-08-04 18:41:51 +0000838 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000839 assert(!DeferredRegion && "Deferred region never completed");
840
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000841 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000842
843 // Do not propagate region counts into system headers.
844 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
845 return;
846
Vedant Kumar61763b62018-05-30 23:35:44 +0000847 propagateCounts(getRegionCounter(Body), Body);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000848 assert(RegionStack.empty() && "Regions entered but never exited");
849
Vedant Kumar61763b62018-05-30 23:35:44 +0000850 // Discard the last uncompleted deferred region in a decl, if one exists.
851 // This prevents lines at the end of a function containing only whitespace
852 // or closing braces from being marked as uncovered.
853 DeferredRegion = None;
Alex Lorenzee024992014-08-04 18:41:51 +0000854 }
855
856 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000857 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000858 if (S->getRetValue())
859 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000860 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000861 }
862
Justin Bognerf959feb2015-04-28 06:31:55 +0000863 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
864 extendRegion(E);
865 if (E->getSubExpr())
866 Visit(E->getSubExpr());
867 terminateRegion(E);
868 }
869
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000870 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000871
872 void VisitLabelStmt(const LabelStmt *S) {
Vedant Kumar8046d222017-11-09 02:33:39 +0000873 Counter LabelCount = getRegionCounter(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000874 SourceLocation Start = getStart(S);
Vedant Kumar8046d222017-11-09 02:33:39 +0000875 completeTopLevelDeferredRegion(LabelCount, Start);
Vedant Kumard781d972018-06-01 00:37:13 +0000876 completeDeferred(LabelCount, Start);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000877 // We can't extendRegion here or we risk overlapping with our new region.
878 handleFileExit(Start);
Vedant Kumar8046d222017-11-09 02:33:39 +0000879 pushRegion(LabelCount, Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000880 Visit(S->getSubStmt());
881 }
882
883 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000884 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
885 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000886 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000887 // FIXME: a break in a switch should terminate regions for all preceding
888 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000889 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000890 }
891
892 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000893 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
894 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000895 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
896 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000897 }
898
Eli Friedman181dfe42017-08-08 20:10:14 +0000899 void VisitCallExpr(const CallExpr *E) {
900 VisitStmt(E);
901
902 // Terminate the region when we hit a noreturn function.
903 // (This is helpful dealing with switch statements.)
904 QualType CalleeType = E->getCallee()->getType();
905 if (getFunctionExtInfo(*CalleeType).getNoReturn())
906 terminateRegion(E);
907 }
908
Alex Lorenzee024992014-08-04 18:41:51 +0000909 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000910 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000911
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000912 Counter ParentCount = getRegion().getCounter();
913 Counter BodyCount = getRegionCounter(S);
914
915 // Handle the body first so that we can get the backedge count.
916 BreakContinueStack.push_back(BreakContinue());
917 extendRegion(S->getBody());
918 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000919 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000920
921 // Go back to handle the condition.
922 Counter CondCount =
923 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
924 propagateCounts(CondCount, S->getCond());
925 adjustForOutOfOrderTraversal(getEnd(S));
926
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000927 // The body count applies to the area immediately after the increment.
928 auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
929 if (Gap)
930 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
931
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000932 Counter OutCount =
933 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
934 if (OutCount != ParentCount)
935 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000936 }
937
938 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000939 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000940
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000941 Counter ParentCount = getRegion().getCounter();
942 Counter BodyCount = getRegionCounter(S);
943
944 BreakContinueStack.push_back(BreakContinue());
945 extendRegion(S->getBody());
946 Counter BackedgeCount =
947 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000948 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000949
950 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
951 propagateCounts(CondCount, S->getCond());
952
953 Counter OutCount =
954 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
955 if (OutCount != ParentCount)
956 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000957 }
958
959 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000960 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000961 if (S->getInit())
962 Visit(S->getInit());
963
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000964 Counter ParentCount = getRegion().getCounter();
965 Counter BodyCount = getRegionCounter(S);
966
Vedant Kumar3e2ae492018-02-16 07:59:43 +0000967 // The loop increment may contain a break or continue.
968 if (S->getInc())
969 BreakContinueStack.emplace_back();
970
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000971 // Handle the body first so that we can get the backedge count.
Vedant Kumar3e2ae492018-02-16 07:59:43 +0000972 BreakContinueStack.emplace_back();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000973 extendRegion(S->getBody());
974 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Vedant Kumar3e2ae492018-02-16 07:59:43 +0000975 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000976
977 // The increment is essentially part of the body but it needs to include
978 // the count for all the continue statements.
Vedant Kumar3e2ae492018-02-16 07:59:43 +0000979 BreakContinue IncrementBC;
980 if (const Stmt *Inc = S->getInc()) {
981 propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
982 IncrementBC = BreakContinueStack.pop_back_val();
983 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000984
985 // Go back to handle the condition.
Vedant Kumar3e2ae492018-02-16 07:59:43 +0000986 Counter CondCount = addCounters(
987 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
988 IncrementBC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000989 if (const Expr *Cond = S->getCond()) {
990 propagateCounts(CondCount, Cond);
991 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000992 }
993
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000994 // The body count applies to the area immediately after the increment.
995 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
996 getStart(S->getBody()));
997 if (Gap)
998 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
999
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001000 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1001 subtractCounters(CondCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001002 if (OutCount != ParentCount)
1003 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001004 }
1005
1006 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001007 extendRegion(S);
1008 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +00001009 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001010
1011 Counter ParentCount = getRegion().getCounter();
1012 Counter BodyCount = getRegionCounter(S);
1013
Alex Lorenzee024992014-08-04 18:41:51 +00001014 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001015 extendRegion(S->getBody());
1016 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001017 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001018
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001019 // The body count applies to the area immediately after the range.
1020 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1021 getStart(S->getBody()));
1022 if (Gap)
1023 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1024
Justin Bogner15874322015-04-30 21:31:02 +00001025 Counter LoopCount =
1026 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1027 Counter OutCount =
1028 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001029 if (OutCount != ParentCount)
1030 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001031 }
1032
1033 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001034 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001035 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001036
1037 Counter ParentCount = getRegion().getCounter();
1038 Counter BodyCount = getRegionCounter(S);
1039
Alex Lorenzee024992014-08-04 18:41:51 +00001040 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001041 extendRegion(S->getBody());
1042 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001043 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001044
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001045 // The body count applies to the area immediately after the collection.
1046 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1047 getStart(S->getBody()));
1048 if (Gap)
1049 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1050
Justin Bogner15874322015-04-30 21:31:02 +00001051 Counter LoopCount =
1052 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1053 Counter OutCount =
1054 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001055 if (OutCount != ParentCount)
1056 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001057 }
1058
1059 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001060 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +00001061 if (S->getInit())
1062 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +00001063 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001064
Alex Lorenzee024992014-08-04 18:41:51 +00001065 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001066
1067 const Stmt *Body = S->getBody();
1068 extendRegion(Body);
1069 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1070 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001071 // Make a region for the body of the switch. If the body starts with
1072 // a case, that case will reuse this region; otherwise, this covers
1073 // the unreachable code at the beginning of the switch body.
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001074 size_t Index =
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001075 pushRegion(Counter::getZero(), getStart(CS->body_front()));
Richard Trieub5841332015-04-15 01:21:42 +00001076 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001077 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001078
1079 // Set the end for the body of the switch, if it isn't already set.
1080 for (size_t i = RegionStack.size(); i != Index; --i) {
1081 if (!RegionStack[i - 1].hasEndLoc())
1082 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1083 }
1084
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001085 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001086 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001087 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001088 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001089 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001090
Alex Lorenzee024992014-08-04 18:41:51 +00001091 if (!BreakContinueStack.empty())
1092 BreakContinueStack.back().ContinueCount = addCounters(
1093 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001094
1095 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001096 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001097 pushRegion(ExitCount);
1098
1099 // Ensure that handleFileExit recognizes when the end location is located
1100 // in a different file.
1101 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001102 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001103 }
1104
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001105 void VisitSwitchCase(const SwitchCase *S) {
1106 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001107
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001108 SourceMappingRegion &Parent = getRegion();
1109
1110 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1111 // Reuse the existing region if it starts at our label. This is typical of
1112 // the first case in a switch.
1113 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
1114 Parent.setCounter(Count);
1115 else
1116 pushRegion(Count, getStart(S));
1117
Sanjay Patel376c06c2015-12-24 21:11:29 +00001118 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001119 Visit(CS->getLHS());
1120 if (const Expr *RHS = CS->getRHS())
1121 Visit(RHS);
1122 }
Alex Lorenzee024992014-08-04 18:41:51 +00001123 Visit(S->getSubStmt());
1124 }
1125
1126 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001127 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001128 if (S->getInit())
1129 Visit(S->getInit());
1130
Justin Bogner055ebc32015-06-16 06:24:15 +00001131 // Extend into the condition before we propagate through it below - this is
1132 // needed to handle macros that generate the "if" but not the condition.
1133 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001134
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001135 Counter ParentCount = getRegion().getCounter();
1136 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001137
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001138 // Emitting a counter for the condition makes it easier to interpret the
1139 // counter for the body when looking at the coverage.
1140 propagateCounts(ParentCount, S->getCond());
1141
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001142 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001143 auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1144 if (Gap)
1145 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001146
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001147 extendRegion(S->getThen());
1148 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1149
1150 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1151 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001152 // The 'else' count applies to the area immediately after the 'then'.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001153 Gap = findGapAreaBetween(S->getThen(), Else);
1154 if (Gap)
1155 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001156 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001157 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1158 } else
1159 OutCount = addCounters(OutCount, ElseCount);
1160
1161 if (OutCount != ParentCount)
1162 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001163 }
1164
1165 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001166 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001167 // Handle macros that generate the "try" but not the rest.
1168 extendRegion(S->getTryBlock());
1169
1170 Counter ParentCount = getRegion().getCounter();
1171 propagateCounts(ParentCount, S->getTryBlock());
1172
Alex Lorenzee024992014-08-04 18:41:51 +00001173 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1174 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001175
1176 Counter ExitCount = getRegionCounter(S);
1177 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001178 }
1179
1180 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001181 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001182 }
1183
1184 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001185 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001186
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001187 Counter ParentCount = getRegion().getCounter();
1188 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001189
Justin Bognere3654ce2015-04-24 23:37:57 +00001190 Visit(E->getCond());
1191
1192 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001193 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001194 auto Gap =
1195 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1196 if (Gap)
1197 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001198
Justin Bognere3654ce2015-04-24 23:37:57 +00001199 extendRegion(E->getTrueExpr());
1200 propagateCounts(TrueCount, E->getTrueExpr());
1201 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001202
Justin Bognere3654ce2015-04-24 23:37:57 +00001203 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001204 propagateCounts(subtractCounters(ParentCount, TrueCount),
1205 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001206 }
1207
1208 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001209 extendRegion(E->getLHS());
1210 propagateCounts(getRegion().getCounter(), E->getLHS());
1211 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001212
1213 extendRegion(E->getRHS());
1214 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001215 }
1216
1217 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001218 extendRegion(E->getLHS());
1219 propagateCounts(getRegion().getCounter(), E->getLHS());
1220 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001221
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001222 extendRegion(E->getRHS());
1223 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001224 }
Justin Bognerc1091022015-02-24 04:13:56 +00001225
1226 void VisitLambdaExpr(const LambdaExpr *LE) {
1227 // Lambdas are treated as their own functions for now, so we shouldn't
1228 // propagate counts into them.
1229 }
Alex Lorenzee024992014-08-04 18:41:51 +00001230};
Alex Lorenzee024992014-08-04 18:41:51 +00001231
Xinliang David Li1f39fcf2017-04-14 04:14:29 +00001232std::string getCoverageSection(const CodeGenModule &CGM) {
Vedant Kumar8a767a42017-04-15 00:10:05 +00001233 return llvm::getInstrProfSectionName(
1234 llvm::IPSK_covmap,
1235 CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
Alex Lorenzee024992014-08-04 18:41:51 +00001236}
1237
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001238std::string normalizeFilename(StringRef Filename) {
1239 llvm::SmallString<256> Path(Filename);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001240 llvm::sys::fs::make_absolute(Path);
Vedant Kumard04929d2016-07-18 22:32:02 +00001241 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001242 return Path.str().str();
1243}
1244
1245} // end anonymous namespace
1246
Justin Bognera432d172015-02-03 00:20:24 +00001247static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1248 ArrayRef<CounterExpression> Expressions,
1249 ArrayRef<CounterMappingRegion> Regions) {
1250 OS << FunctionName << ":\n";
1251 CounterMappingContext Ctx(Expressions);
1252 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001253 OS.indent(2);
1254 switch (R.Kind) {
1255 case CounterMappingRegion::CodeRegion:
1256 break;
1257 case CounterMappingRegion::ExpansionRegion:
1258 OS << "Expansion,";
1259 break;
1260 case CounterMappingRegion::SkippedRegion:
1261 OS << "Skipped,";
1262 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001263 case CounterMappingRegion::GapRegion:
1264 OS << "Gap,";
1265 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001266 }
1267
Justin Bogner4da909b2015-02-03 21:35:49 +00001268 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1269 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001270 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001271 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001272 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1273 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001274 }
1275}
1276
Alex Lorenzee024992014-08-04 18:41:51 +00001277void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001278 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001279 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001280 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +00001281 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +00001282#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +00001283 llvm::Type *FunctionRecordTypes[] = {
1284 #include "llvm/ProfileData/InstrProfData.inc"
1285 };
Alex Lorenzee024992014-08-04 18:41:51 +00001286 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +00001287 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1288 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +00001289 }
1290
Xinliang David Lia026a432015-11-05 05:46:39 +00001291 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +00001292 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +00001293 #include "llvm/ProfileData/InstrProfData.inc"
1294 };
Alex Lorenzee024992014-08-04 18:41:51 +00001295 FunctionRecords.push_back(llvm::ConstantStruct::get(
1296 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +00001297 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001298 FunctionNames.push_back(
1299 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +00001300 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001301
1302 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1303 // Dump the coverage mapping data for this function by decoding the
1304 // encoded data. This allows us to dump the mapping regions which were
1305 // also processed by the CoverageMappingWriter which performs
1306 // additional minimization operations such as reducing the number of
1307 // expressions.
1308 std::vector<StringRef> Filenames;
1309 std::vector<CounterExpression> Expressions;
1310 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001311 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001312 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001313 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001314 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001315 for (const auto &Entry : FileEntries) {
1316 auto I = Entry.second;
1317 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1318 FilenameRefs[I] = FilenameStrs[I];
1319 }
Justin Bognera432d172015-02-03 00:20:24 +00001320 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1321 Expressions, Regions);
1322 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001323 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001324 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001325 }
Alex Lorenzee024992014-08-04 18:41:51 +00001326}
1327
1328void CoverageMappingModuleGen::emit() {
1329 if (FunctionRecords.empty())
1330 return;
1331 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1332 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1333
1334 // Create the filenames and merge them with coverage mappings
1335 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001336 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001337 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001338 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001339 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001340 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001341 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001342 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001343 }
1344
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001345 std::string FilenamesAndCoverageMappings;
1346 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1347 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1348 std::string RawCoverageMappings =
1349 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
1350 OS << RawCoverageMappings;
1351 size_t CoverageMappingSize = RawCoverageMappings.size();
1352 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1353 // Append extra zeroes if necessary to ensure that the size of the filenames
1354 // and coverage mappings is a multiple of 8.
1355 if (size_t Rem = OS.str().size() % 8) {
1356 CoverageMappingSize += 8 - Rem;
Peter Collingbourne070777d2018-05-17 22:11:43 +00001357 OS.write_zeros(8 - Rem);
Alex Lorenzee024992014-08-04 18:41:51 +00001358 }
1359 auto *FilenamesAndMappingsVal =
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001360 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
Alex Lorenzee024992014-08-04 18:41:51 +00001361
1362 // Create the deferred function records array
1363 auto RecordsTy =
1364 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1365 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1366
Xinliang David Li20b188c2016-01-03 19:25:54 +00001367 llvm::Type *CovDataHeaderTypes[] = {
1368#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1369#include "llvm/ProfileData/InstrProfData.inc"
1370 };
1371 auto CovDataHeaderTy =
1372 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1373 llvm::Constant *CovDataHeaderVals[] = {
1374#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1375#include "llvm/ProfileData/InstrProfData.inc"
1376 };
1377 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1378 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1379
Alex Lorenzee024992014-08-04 18:41:51 +00001380 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001381 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1382 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001383 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001384 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1385 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001386 auto CovDataVal =
1387 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001388 auto CovData = new llvm::GlobalVariable(
1389 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1390 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001391
1392 CovData->setSection(getCoverageSection(CGM));
1393 CovData->setAlignment(8);
1394
1395 // Make sure the data doesn't get deleted.
1396 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001397 // Create the deferred function records array
1398 if (!FunctionNames.empty()) {
1399 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1400 FunctionNames.size());
1401 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1402 // This variable will *NOT* be emitted to the object file. It is used
1403 // to pass the list of names referenced to codegen.
1404 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1405 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001406 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001407 }
Alex Lorenzee024992014-08-04 18:41:51 +00001408}
1409
1410unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1411 auto It = FileEntries.find(File);
1412 if (It != FileEntries.end())
1413 return It->second;
1414 unsigned FileID = FileEntries.size();
1415 FileEntries.insert(std::make_pair(File, FileID));
1416 return FileID;
1417}
1418
1419void CoverageMappingGen::emitCounterMapping(const Decl *D,
1420 llvm::raw_ostream &OS) {
1421 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001422 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001423 Walker.VisitDecl(D);
1424 Walker.write(OS);
1425}
1426
1427void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1428 llvm::raw_ostream &OS) {
1429 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1430 Walker.VisitDecl(D);
1431 Walker.write(OS);
1432}