blob: acf0b5a753367afa549d40a5d2509d69dcbecf27 [file] [log] [blame]
Alex Lorenzee024992014-08-04 18:41:51 +00001//===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alex Lorenzee024992014-08-04 18:41:51 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Instrumentation-based code coverage mapping generator
10//
11//===----------------------------------------------------------------------===//
12
13#include "CoverageMappingGen.h"
14#include "CodeGenFunction.h"
15#include "clang/AST/StmtVisitor.h"
Vedant Kumar99317122019-10-21 11:48:38 -070016#include "clang/Basic/Diagnostic.h"
17#include "clang/Frontend/FrontendDiagnostic.h"
Alex Lorenzee024992014-08-04 18:41:51 +000018#include "clang/Lex/Lexer.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000019#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000020#include "llvm/ADT/StringExtras.h"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000021#include "llvm/ADT/Optional.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000022#include "llvm/ProfileData/Coverage/CoverageMapping.h"
23#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
24#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000026#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000027#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000028
Vedant Kumar99317122019-10-21 11:48:38 -070029// This selects the coverage mapping format defined when `InstrProfData.inc`
30// is textually included.
31#define COVMAP_V3
32
Alex Lorenzee024992014-08-04 18:41:51 +000033using namespace clang;
34using namespace CodeGen;
35using namespace llvm::coverage;
36
Vedant Kumar3919a502017-09-11 20:47:42 +000037void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Alex Lorenzee024992014-08-04 18:41:51 +000038 SkippedRanges.push_back(Range);
39}
40
41namespace {
42
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000043/// A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000044class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000045 Counter Count;
46
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000047 /// The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000048 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050 /// The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000051 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000052
Vedant Kumar747b0e22017-09-08 18:44:56 +000053 /// Whether this region should be emitted after its parent is emitted.
54 bool DeferRegion;
55
Vedant Kumara1c4deb2017-09-18 23:37:30 +000056 /// Whether this region is a gap region. The count from a gap region is set
57 /// as the line execution count if there are no other regions on the line.
58 bool GapRegion;
59
Justin Bogner09c71792014-10-01 03:33:49 +000060public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000061 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara1c4deb2017-09-18 23:37:30 +000062 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
63 bool GapRegion = false)
Vedant Kumar747b0e22017-09-08 18:44:56 +000064 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
Vedant Kumara1c4deb2017-09-18 23:37:30 +000065 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000066
Justin Bogner09c71792014-10-01 03:33:49 +000067 const Counter &getCounter() const { return Count; }
68
Justin Bognerbf42cfd2015-02-18 21:24:51 +000069 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000070
Justin Bognerbf42cfd2015-02-18 21:24:51 +000071 bool hasStartLoc() const { return LocStart.hasValue(); }
72
73 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
74
Stephen Kelly3cffc4c2018-08-09 20:05:18 +000075 SourceLocation getBeginLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000076 assert(LocStart && "Region has no start location");
77 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000078 }
79
Justin Bognerbf42cfd2015-02-18 21:24:51 +000080 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000081
Vedant Kumara14a1f92018-01-17 18:53:51 +000082 void setEndLoc(SourceLocation Loc) {
83 assert(Loc.isValid() && "Setting an invalid end location");
84 LocEnd = Loc;
85 }
Alex Lorenzee024992014-08-04 18:41:51 +000086
Craig Topper462c77b2015-09-26 05:10:14 +000087 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000088 assert(LocEnd && "Region has no end location");
89 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000090 }
Vedant Kumar747b0e22017-09-08 18:44:56 +000091
92 bool isDeferred() const { return DeferRegion; }
93
94 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Vedant Kumara1c4deb2017-09-18 23:37:30 +000095
96 bool isGap() const { return GapRegion; }
97
98 void setGap(bool Gap) { GapRegion = Gap; }
Alex Lorenzee024992014-08-04 18:41:51 +000099};
100
Vedant Kumard7369642017-07-27 02:20:25 +0000101/// Spelling locations for the start and end of a source region.
102struct SpellingRegion {
103 /// The line where the region starts.
104 unsigned LineStart;
105
106 /// The column where the region starts.
107 unsigned ColumnStart;
108
109 /// The line where the region ends.
110 unsigned LineEnd;
111
112 /// The column where the region ends.
113 unsigned ColumnEnd;
114
115 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
116 SourceLocation LocEnd) {
117 LineStart = SM.getSpellingLineNumber(LocStart);
118 ColumnStart = SM.getSpellingColumnNumber(LocStart);
119 LineEnd = SM.getSpellingLineNumber(LocEnd);
120 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
121 }
122
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000123 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
Stephen Kellya6e43582018-08-09 21:05:56 +0000124 : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000125
Vedant Kumard7369642017-07-27 02:20:25 +0000126 /// Check if the start and end locations appear in source order, i.e
127 /// top->bottom, left->right.
128 bool isInSourceOrder() const {
129 return (LineStart < LineEnd) ||
130 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
131 }
132};
133
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000134/// Provides the common functionality for the different
Alex Lorenzee024992014-08-04 18:41:51 +0000135/// coverage mapping region builders.
136class CoverageMappingBuilder {
137public:
138 CoverageMappingModuleGen &CVM;
139 SourceManager &SM;
140 const LangOptions &LangOpts;
141
142private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000143 /// Map of clang's FileIDs to IDs used for coverage mapping.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000144 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
145 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000146
147public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000148 /// The coverage mapping regions for this function
Alex Lorenzee024992014-08-04 18:41:51 +0000149 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000150 /// The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000151 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000152
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000153 /// A set of regions which can be used as a filter.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000154 ///
155 /// It is produced by emitExpansionRegions() and is used in
156 /// emitSourceRegions() to suppress producing code regions if
157 /// the same area is covered by expansion regions.
158 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
159 SourceRegionFilter;
160
Alex Lorenzee024992014-08-04 18:41:51 +0000161 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
162 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000163 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000165 /// Return the precise end location for the given token.
Alex Lorenzee024992014-08-04 18:41:51 +0000166 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000167 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
168 // macro locations, which we just treat as expanded files.
169 unsigned TokLen =
170 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
171 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000172 }
173
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000174 /// Return the start location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000175 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
176 if (Loc.isMacroID())
177 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
178 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000179 }
180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000181 /// Return the end location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000182 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
183 if (Loc.isMacroID())
184 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000185 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000186 return SM.getLocForEndOfFile(SM.getFileID(Loc));
187 }
188
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000189 /// Find out where the current file is included or macro is expanded.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000190 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
Richard Smithb5f81712018-04-30 05:25:48 +0000191 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000192 : SM.getIncludeLoc(SM.getFileID(Loc));
193 }
194
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000195 /// Return true if \c Loc is a location in a built-in macro.
Justin Bogner682bfbf2015-05-14 22:14:10 +0000196 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000197 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000198 }
199
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000200 /// Check whether \c Loc is included or expanded from \c Parent.
Igor Kudrind9e1a612016-06-07 10:07:51 +0000201 bool isNestedIn(SourceLocation Loc, FileID Parent) {
202 do {
203 Loc = getIncludeOrExpansionLoc(Loc);
204 if (Loc.isInvalid())
205 return false;
206 } while (!SM.isInFileID(Loc, Parent));
207 return true;
208 }
209
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000210 /// Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000211 SourceLocation getStart(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000212 SourceLocation Loc = S->getBeginLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000213 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000214 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000215 return Loc;
216 }
217
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000218 /// Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000219 SourceLocation getEnd(const Stmt *S) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000220 SourceLocation Loc = S->getEndLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000221 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000222 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerf14b2072015-03-25 04:13:49 +0000223 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000224 }
225
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000226 /// Find the set of files we have regions for and assign IDs
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000227 ///
228 /// Fills \c Mapping with the virtual file mapping needed to write out
229 /// coverage and collects the necessary file information to emit source and
230 /// expansion regions.
231 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
232 FileIDMapping.clear();
233
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000234 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000235 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
236 for (const auto &Region : SourceRegions) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000237 SourceLocation Loc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000238 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000239 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000240 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000241
Vedant Kumar93205af2016-07-11 22:57:46 +0000242 // Do not map FileID's associated with system headers.
243 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
244 continue;
245
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000246 unsigned Depth = 0;
247 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000248 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000249 ++Depth;
250 FileLocs.push_back(std::make_pair(Loc, Depth));
251 }
Fangrui Song899d1392019-04-24 14:43:05 +0000252 llvm::stable_sort(FileLocs, llvm::less_second());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000253
254 for (const auto &FL : FileLocs) {
255 SourceLocation Loc = FL.first;
256 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
257 auto Entry = SM.getFileEntryForID(SpellingFile);
258 if (!Entry)
259 continue;
260
261 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
262 Mapping.push_back(CVM.getFileID(Entry));
263 }
264 }
265
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000266 /// Get the coverage mapping file ID for \c Loc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000267 ///
268 /// If such file id doesn't exist, return None.
269 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
270 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000271 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000272 return Mapping->second.first;
273 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000274 }
275
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000276 /// Gather all the regions that were skipped by the preprocessor
Alex Lorenzee024992014-08-04 18:41:51 +0000277 /// using the constructs like #if.
278 void gatherSkippedRegions() {
279 /// An array of the minimum lineStarts and the maximum lineEnds
280 /// for mapping regions from the appropriate source files.
281 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
282 FileLineRanges.resize(
283 FileIDMapping.size(),
284 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
285 for (const auto &R : MappingRegions) {
286 FileLineRanges[R.FileID].first =
287 std::min(FileLineRanges[R.FileID].first, R.LineStart);
288 FileLineRanges[R.FileID].second =
289 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
290 }
291
292 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
293 for (const auto &I : SkippedRanges) {
294 auto LocStart = I.getBegin();
295 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000296 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
297 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000298
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000299 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000300 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000301 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000302 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000303 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000304 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000305 // Make sure that we only collect the regions that are inside
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000306 // the source code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000307 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
308 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000309 MappingRegions.push_back(Region);
310 }
311 }
312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000313 /// Generate the coverage counter mapping regions from collected
Alex Lorenzee024992014-08-04 18:41:51 +0000314 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000315 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000316 for (const auto &Region : SourceRegions) {
317 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000318
Stephen Kellya6e43582018-08-09 21:05:56 +0000319 SourceLocation LocStart = Region.getBeginLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000320 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000321
Vedant Kumar93205af2016-07-11 22:57:46 +0000322 // Ignore regions from system headers.
323 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
324 continue;
325
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000326 auto CovFileID = getCoverageFileID(LocStart);
327 // Ignore regions that don't have a file, such as builtin macros.
328 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000329 continue;
330
Justin Bognerf14b2072015-03-25 04:13:49 +0000331 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000332 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
333 "region spans multiple files");
334
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000335 // Don't add code regions for the area covered by expansion regions.
336 // This not only suppresses redundant regions, but sometimes prevents
337 // creating regions with wrong counters if, for example, a statement's
338 // body ends at the end of a nested macro.
339 if (Filter.count(std::make_pair(LocStart, LocEnd)))
340 continue;
341
Vedant Kumard7369642017-07-27 02:20:25 +0000342 // Find the spelling locations for the mapping region.
343 SpellingRegion SR{SM, LocStart, LocEnd};
344 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000345
346 if (Region.isGap()) {
347 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
348 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
349 SR.LineEnd, SR.ColumnEnd));
350 } else {
351 MappingRegions.push_back(CounterMappingRegion::makeRegion(
352 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
353 SR.LineEnd, SR.ColumnEnd));
354 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000355 }
356 }
357
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000358 /// Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000359 SourceRegionFilter emitExpansionRegions() {
360 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000361 for (const auto &FM : FileIDMapping) {
362 SourceLocation ExpandedLoc = FM.second.second;
363 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
364 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000365 continue;
366
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000367 auto ParentFileID = getCoverageFileID(ParentLoc);
368 if (!ParentFileID)
369 continue;
370 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
371 assert(ExpandedFileID && "expansion in uncovered file");
372
373 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
374 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
375 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000376 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000377
Vedant Kumard7369642017-07-27 02:20:25 +0000378 SpellingRegion SR{SM, ParentLoc, LocEnd};
379 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000380 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000381 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
382 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000383 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000384 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000385 }
386};
387
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000388/// Creates unreachable coverage regions for the functions that
Alex Lorenzee024992014-08-04 18:41:51 +0000389/// are not emitted.
390struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
391 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
392 const LangOptions &LangOpts)
393 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
394
395 void VisitDecl(const Decl *D) {
396 if (!D->hasBody())
397 return;
398 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000399 SourceLocation Start = getStart(Body);
400 SourceLocation End = getEnd(Body);
401 if (!SM.isWrittenInSameFile(Start, End)) {
402 // Walk up to find the common ancestor.
403 // Correct the locations accordingly.
404 FileID StartFileID = SM.getFileID(Start);
405 FileID EndFileID = SM.getFileID(End);
406 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
407 Start = getIncludeOrExpansionLoc(Start);
408 assert(Start.isValid() &&
409 "Declaration start location not nested within a known region");
410 StartFileID = SM.getFileID(Start);
411 }
412 while (StartFileID != EndFileID) {
413 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
414 assert(End.isValid() &&
415 "Declaration end location not nested within a known region");
416 EndFileID = SM.getFileID(End);
417 }
418 }
419 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000420 }
421
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000422 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000423 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000424 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000425 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000426 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000427
Vedant Kumarefd319a2016-07-26 00:24:59 +0000428 if (MappingRegions.empty())
429 return;
430
Craig Topper5fc8fc22014-08-27 06:28:36 +0000431 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000432 Writer.write(OS);
433 }
434};
435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436/// A StmtVisitor that creates coverage mapping regions which map
Alex Lorenzee024992014-08-04 18:41:51 +0000437/// from the source code locations to the PGO counters.
438struct CounterCoverageMappingBuilder
439 : public CoverageMappingBuilder,
440 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// The map of statements to count values.
Alex Lorenzee024992014-08-04 18:41:51 +0000442 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
443
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000444 /// A stack of currently live regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000445 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000446
Vedant Kumar747b0e22017-09-08 18:44:56 +0000447 /// The currently deferred region: its end location and count can be set once
448 /// its parent has been popped from the region stack.
449 Optional<SourceMappingRegion> DeferredRegion;
450
Alex Lorenzee024992014-08-04 18:41:51 +0000451 CounterExpressionBuilder Builder;
452
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000453 /// A location in the most recently visited file or macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000454 ///
455 /// This is used to adjust the active source regions appropriately when
456 /// expressions cross file or macro boundaries.
457 SourceLocation MostRecentLocation;
458
Vedant Kumar8046d222017-11-09 02:33:39 +0000459 /// Location of the last terminated region.
460 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
461
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462 /// Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000463 Counter subtractCounters(Counter LHS, Counter RHS) {
464 return Builder.subtract(LHS, RHS);
465 }
466
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000467 /// Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000468 Counter addCounters(Counter LHS, Counter RHS) {
469 return Builder.add(LHS, RHS);
470 }
471
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000472 Counter addCounters(Counter C1, Counter C2, Counter C3) {
473 return addCounters(addCounters(C1, C2), C3);
474 }
475
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000476 /// Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000477 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000478 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000479 Counter getRegionCounter(const Stmt *S) {
480 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000481 }
482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000483 /// Push a region onto the stack.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000484 ///
485 /// Returns the index on the stack where the region was pushed. This can be
486 /// used with popRegions to exit a "scope", ending the region that was pushed.
487 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
488 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000489 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000490 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000491 completeDeferred(Count, MostRecentLocation);
492 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000493 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000494
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000495 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000496 }
497
Vedant Kumar747b0e22017-09-08 18:44:56 +0000498 /// Complete any pending deferred region by setting its end location and
499 /// count, and then pushing it onto the region stack.
500 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
501 size_t Index = RegionStack.size();
502 if (!DeferredRegion)
503 return Index;
504
505 // Consume the pending region.
506 SourceMappingRegion DR = DeferredRegion.getValue();
507 DeferredRegion = None;
508
509 // If the region ends in an expansion, find the expansion site.
Stephen Kellya6e43582018-08-09 21:05:56 +0000510 FileID StartFile = SM.getFileID(DR.getBeginLoc());
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000511 if (SM.getFileID(DeferredEndLoc) != StartFile) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000512 if (isNestedIn(DeferredEndLoc, StartFile)) {
513 do {
514 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
515 } while (StartFile != SM.getFileID(DeferredEndLoc));
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000516 } else {
517 return Index;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000518 }
519 }
520
521 // The parent of this deferred region ends where the containing decl ends,
522 // so the region isn't useful.
Stephen Kellya6e43582018-08-09 21:05:56 +0000523 if (DR.getBeginLoc() == DeferredEndLoc)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000524 return Index;
525
526 // If we're visiting statements in non-source order (e.g switch cases or
527 // a loop condition) we can't construct a sensible deferred region.
Stephen Kellya6e43582018-08-09 21:05:56 +0000528 if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000529 return Index;
530
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000531 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000532 DR.setCounter(Count);
533 DR.setEndLoc(DeferredEndLoc);
534 handleFileExit(DeferredEndLoc);
535 RegionStack.push_back(DR);
536 return Index;
537 }
538
Vedant Kumar8046d222017-11-09 02:33:39 +0000539 /// Complete a deferred region created after a terminated region at the
540 /// top-level.
541 void completeTopLevelDeferredRegion(Counter Count,
542 SourceLocation DeferredEndLoc) {
543 if (DeferredRegion || !LastTerminatedRegion)
544 return;
545
546 if (LastTerminatedRegion->second != RegionStack.size())
547 return;
548
549 SourceLocation Start = LastTerminatedRegion->first;
550 if (SM.getFileID(Start) != SM.getMainFileID())
551 return;
552
553 SourceMappingRegion DR = RegionStack.back();
554 DR.setStartLoc(Start);
555 DR.setDeferred(false);
556 DeferredRegion = DR;
557 completeDeferred(Count, DeferredEndLoc);
558 }
559
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000560 size_t locationDepth(SourceLocation Loc) {
561 size_t Depth = 0;
562 while (Loc.isValid()) {
563 Loc = getIncludeOrExpansionLoc(Loc);
564 Depth++;
565 }
566 return Depth;
567 }
568
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000569 /// Pop regions from the stack into the function's list of regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000570 ///
571 /// Adds all regions from \c ParentIndex to the top of the stack to the
572 /// function's \c SourceRegions.
573 void popRegions(size_t ParentIndex) {
574 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000575 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000576 while (RegionStack.size() > ParentIndex) {
577 SourceMappingRegion &Region = RegionStack.back();
578 if (Region.hasStartLoc()) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000579 SourceLocation StartLoc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000580 SourceLocation EndLoc = Region.hasEndLoc()
581 ? Region.getEndLoc()
582 : RegionStack[ParentIndex].getEndLoc();
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000583 size_t StartDepth = locationDepth(StartLoc);
584 size_t EndDepth = locationDepth(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000585 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000586 bool UnnestStart = StartDepth >= EndDepth;
587 bool UnnestEnd = EndDepth >= StartDepth;
588 if (UnnestEnd) {
589 // The region ends in a nested file or macro expansion. Create a
590 // separate region for each expansion.
591 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
592 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000593
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000594 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
595 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000596
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000597 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
598 if (EndLoc.isInvalid())
599 llvm::report_fatal_error("File exit not handled before popRegions");
600 EndDepth--;
601 }
602 if (UnnestStart) {
603 // The region begins in a nested file or macro expansion. Create a
604 // separate region for each expansion.
605 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
606 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
607
608 if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
609 SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
610
611 StartLoc = getIncludeOrExpansionLoc(StartLoc);
612 if (StartLoc.isInvalid())
613 llvm::report_fatal_error("File exit not handled before popRegions");
614 StartDepth--;
615 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000616 }
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000617 Region.setStartLoc(StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000618 Region.setEndLoc(EndLoc);
619
620 MostRecentLocation = EndLoc;
621 // If this region happens to span an entire expansion, we need to make
622 // sure we don't overlap the parent region with it.
623 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
624 EndLoc == getEndOfFileOrMacro(EndLoc))
625 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
626
Stephen Kellya6e43582018-08-09 21:05:56 +0000627 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000628 assert(SpellingRegion(SM, Region).isInSourceOrder());
Craig Topperf36a5c42015-09-26 05:10:16 +0000629 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000630
631 if (ParentOfDeferredRegion) {
632 ParentOfDeferredRegion = false;
633
634 // If there's an existing deferred region, keep the old one, because
635 // it means there are two consecutive returns (or a similar pattern).
636 if (!DeferredRegion.hasValue() &&
637 // File IDs aren't gathered within macro expansions, so it isn't
638 // useful to try and create a deferred region inside of one.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000639 !EndLoc.isMacroID())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000640 DeferredRegion =
641 SourceMappingRegion(Counter::getZero(), EndLoc, None);
642 }
643 } else if (Region.isDeferred()) {
644 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
645 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000646 }
647 RegionStack.pop_back();
Vedant Kumar8046d222017-11-09 02:33:39 +0000648
649 // If the zero region pushed after the last terminated region no longer
650 // exists, clear its cached information.
651 if (LastTerminatedRegion &&
652 RegionStack.size() < LastTerminatedRegion->second)
653 LastTerminatedRegion = None;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000654 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000655 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000656 }
657
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000658 /// Return the currently active region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000659 SourceMappingRegion &getRegion() {
660 assert(!RegionStack.empty() && "statement has no region");
661 return RegionStack.back();
662 }
Alex Lorenzee024992014-08-04 18:41:51 +0000663
Vedant Kumar7225a262018-11-28 20:48:07 +0000664 /// Propagate counts through the children of \p S if \p VisitChildren is true.
665 /// Otherwise, only emit a count for \p S itself.
666 Counter propagateCounts(Counter TopCount, const Stmt *S,
667 bool VisitChildren = true) {
Vedant Kumar78386962017-07-27 02:20:20 +0000668 SourceLocation StartLoc = getStart(S);
669 SourceLocation EndLoc = getEnd(S);
670 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Vedant Kumar7225a262018-11-28 20:48:07 +0000671 if (VisitChildren)
672 Visit(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000673 Counter ExitCount = getRegion().getCounter();
674 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000675
676 // The statement may be spanned by an expansion. Make sure we handle a file
677 // exit out of this expansion before moving to the next statement.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000678 if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
Vedant Kumar78386962017-07-27 02:20:20 +0000679 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000680
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000681 return ExitCount;
682 }
Alex Lorenzee024992014-08-04 18:41:51 +0000683
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000684 /// Check whether a region with bounds \c StartLoc and \c EndLoc
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000685 /// is already added to \c SourceRegions.
686 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
687 return SourceRegions.rend() !=
688 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
689 [&](const SourceMappingRegion &Region) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000690 return Region.getBeginLoc() == StartLoc &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000691 Region.getEndLoc() == EndLoc;
692 });
693 }
694
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000695 /// Adjust the most recently visited location to \c EndLoc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000696 ///
697 /// This should be used after visiting any statements in non-source order.
698 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
699 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000700 // The code region for a whole macro is created in handleFileExit() when
701 // it detects exiting of the virtual file of that macro. If we visited
702 // statements in non-source order, we might already have such a region
703 // added, for example, if a body of a loop is divided among multiple
704 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000705 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000706 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
707 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
708 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000709 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
710 }
Alex Lorenzee024992014-08-04 18:41:51 +0000711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000712 /// Adjust regions and state when \c NewLoc exits a file.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000713 ///
714 /// If moving from our most recently tracked location to \c NewLoc exits any
715 /// files, this adjusts our current region stack and creates the file regions
716 /// for the exited file.
717 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000718 if (NewLoc.isInvalid() ||
719 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000720 return;
721
722 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
723 // find the common ancestor.
724 SourceLocation LCA = NewLoc;
725 FileID ParentFile = SM.getFileID(LCA);
726 while (!isNestedIn(MostRecentLocation, ParentFile)) {
727 LCA = getIncludeOrExpansionLoc(LCA);
728 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
729 // Since there isn't a common ancestor, no file was exited. We just need
730 // to adjust our location to the new file.
731 MostRecentLocation = NewLoc;
732 return;
733 }
734 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000735 }
736
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000737 llvm::SmallSet<SourceLocation, 8> StartLocs;
738 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000739 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
740 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000741 continue;
Stephen Kellya6e43582018-08-09 21:05:56 +0000742 SourceLocation Loc = I.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000743 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000744 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000745 break;
746 }
Alex Lorenzee024992014-08-04 18:41:51 +0000747
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000748 while (!SM.isInFileID(Loc, ParentFile)) {
749 // The most nested region for each start location is the one with the
750 // correct count. We avoid creating redundant regions by stopping once
751 // we've seen this region.
752 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000753 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000754 getEndOfFileOrMacro(Loc));
755 Loc = getIncludeOrExpansionLoc(Loc);
756 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000757 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000758 }
759
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000760 if (ParentCounter) {
761 // If the file is contained completely by another region and doesn't
762 // immediately start its own region, the whole file gets a region
763 // corresponding to the parent.
764 SourceLocation Loc = MostRecentLocation;
765 while (isNestedIn(Loc, ParentFile)) {
766 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000767 if (StartLocs.insert(FileStart).second) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000768 SourceRegions.emplace_back(*ParentCounter, FileStart,
769 getEndOfFileOrMacro(Loc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000770 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
771 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000772 Loc = getIncludeOrExpansionLoc(Loc);
773 }
Alex Lorenzee024992014-08-04 18:41:51 +0000774 }
775
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000776 MostRecentLocation = NewLoc;
777 }
Alex Lorenzee024992014-08-04 18:41:51 +0000778
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000779 /// Ensure that \c S is included in the current region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000780 void extendRegion(const Stmt *S) {
781 SourceMappingRegion &Region = getRegion();
782 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000783
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000784 handleFileExit(StartLoc);
785 if (!Region.hasStartLoc())
786 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000787
788 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000789 }
790
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000791 /// Mark \c S as a terminator, starting a zero region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000792 void terminateRegion(const Stmt *S) {
793 extendRegion(S);
794 SourceMappingRegion &Region = getRegion();
Vedant Kumar8046d222017-11-09 02:33:39 +0000795 SourceLocation EndLoc = getEnd(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000796 if (!Region.hasEndLoc())
Vedant Kumar8046d222017-11-09 02:33:39 +0000797 Region.setEndLoc(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000798 pushRegion(Counter::getZero());
Vedant Kumar8046d222017-11-09 02:33:39 +0000799 auto &ZeroRegion = getRegion();
800 ZeroRegion.setDeferred(true);
801 LastTerminatedRegion = {EndLoc, RegionStack.size()};
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000802 }
Alex Lorenzee024992014-08-04 18:41:51 +0000803
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000804 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
805 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
806 SourceLocation BeforeLoc) {
807 // If the start and end locations of the gap are both within the same macro
808 // file, the range may not be in source order.
809 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
810 return None;
811 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
812 return None;
813 return {{AfterLoc, BeforeLoc}};
814 }
815
816 /// Find the source range after \p AfterStmt and before \p BeforeStmt.
817 Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
818 const Stmt *BeforeStmt) {
819 return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
820 getStart(BeforeStmt));
821 }
822
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000823 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
824 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
825 Counter Count) {
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000826 if (StartLoc == EndLoc)
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000827 return;
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000828 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000829 handleFileExit(StartLoc);
830 size_t Index = pushRegion(Count, StartLoc, EndLoc);
831 getRegion().setGap(true);
832 handleFileExit(EndLoc);
833 popRegions(Index);
834 }
835
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000836 /// Keep counts of breaks and continues inside loops.
Alex Lorenzee024992014-08-04 18:41:51 +0000837 struct BreakContinue {
838 Counter BreakCount;
839 Counter ContinueCount;
840 };
841 SmallVector<BreakContinue, 8> BreakContinueStack;
842
843 CounterCoverageMappingBuilder(
844 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000845 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000846 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000847 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
848 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000849
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000850 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000851 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000852 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000853 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000854 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000855 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000856 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000857 gatherSkippedRegions();
858
Vedant Kumarefd319a2016-07-26 00:24:59 +0000859 if (MappingRegions.empty())
860 return;
861
Justin Bogner4da909b2015-02-03 21:35:49 +0000862 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
863 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000864 Writer.write(OS);
865 }
866
Alex Lorenzee024992014-08-04 18:41:51 +0000867 void VisitStmt(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000868 if (S->getBeginLoc().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000869 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000870 for (const Stmt *Child : S->children())
871 if (Child)
872 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000873 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000874 }
875
Alex Lorenzee024992014-08-04 18:41:51 +0000876 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000877 assert(!DeferredRegion && "Deferred region never completed");
878
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000879 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000880
881 // Do not propagate region counts into system headers.
882 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
883 return;
884
Vedant Kumar7225a262018-11-28 20:48:07 +0000885 // Do not visit the artificial children nodes of defaulted methods. The
886 // lexer may not be able to report back precise token end locations for
887 // these children nodes (llvm.org/PR39822), and moreover users will not be
888 // able to see coverage for them.
889 bool Defaulted = false;
890 if (auto *Method = dyn_cast<CXXMethodDecl>(D))
891 Defaulted = Method->isDefaulted();
892
893 propagateCounts(getRegionCounter(Body), Body,
894 /*VisitChildren=*/!Defaulted);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000895 assert(RegionStack.empty() && "Regions entered but never exited");
896
Vedant Kumar61763b62018-05-30 23:35:44 +0000897 // Discard the last uncompleted deferred region in a decl, if one exists.
898 // This prevents lines at the end of a function containing only whitespace
899 // or closing braces from being marked as uncovered.
900 DeferredRegion = None;
Alex Lorenzee024992014-08-04 18:41:51 +0000901 }
902
903 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000904 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000905 if (S->getRetValue())
906 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000907 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000908 }
909
Justin Bognerf959feb2015-04-28 06:31:55 +0000910 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
911 extendRegion(E);
912 if (E->getSubExpr())
913 Visit(E->getSubExpr());
914 terminateRegion(E);
915 }
916
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000917 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000918
919 void VisitLabelStmt(const LabelStmt *S) {
Vedant Kumar8046d222017-11-09 02:33:39 +0000920 Counter LabelCount = getRegionCounter(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000921 SourceLocation Start = getStart(S);
Vedant Kumar8046d222017-11-09 02:33:39 +0000922 completeTopLevelDeferredRegion(LabelCount, Start);
Vedant Kumard781d972018-06-01 00:37:13 +0000923 completeDeferred(LabelCount, Start);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000924 // We can't extendRegion here or we risk overlapping with our new region.
925 handleFileExit(Start);
Vedant Kumar8046d222017-11-09 02:33:39 +0000926 pushRegion(LabelCount, Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000927 Visit(S->getSubStmt());
928 }
929
930 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000931 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
932 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000933 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000934 // FIXME: a break in a switch should terminate regions for all preceding
935 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000936 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000937 }
938
939 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000940 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
941 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000942 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
943 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000944 }
945
Eli Friedman181dfe42017-08-08 20:10:14 +0000946 void VisitCallExpr(const CallExpr *E) {
947 VisitStmt(E);
948
949 // Terminate the region when we hit a noreturn function.
950 // (This is helpful dealing with switch statements.)
951 QualType CalleeType = E->getCallee()->getType();
952 if (getFunctionExtInfo(*CalleeType).getNoReturn())
953 terminateRegion(E);
954 }
955
Alex Lorenzee024992014-08-04 18:41:51 +0000956 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000957 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000958
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000959 Counter ParentCount = getRegion().getCounter();
960 Counter BodyCount = getRegionCounter(S);
961
962 // Handle the body first so that we can get the backedge count.
963 BreakContinueStack.push_back(BreakContinue());
964 extendRegion(S->getBody());
965 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000966 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000967
968 // Go back to handle the condition.
969 Counter CondCount =
970 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
971 propagateCounts(CondCount, S->getCond());
972 adjustForOutOfOrderTraversal(getEnd(S));
973
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000974 // The body count applies to the area immediately after the increment.
975 auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
976 if (Gap)
977 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
978
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000979 Counter OutCount =
980 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
981 if (OutCount != ParentCount)
982 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000983 }
984
985 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000986 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000987
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000988 Counter ParentCount = getRegion().getCounter();
989 Counter BodyCount = getRegionCounter(S);
990
991 BreakContinueStack.push_back(BreakContinue());
992 extendRegion(S->getBody());
993 Counter BackedgeCount =
994 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000995 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000996
997 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
998 propagateCounts(CondCount, S->getCond());
999
1000 Counter OutCount =
1001 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1002 if (OutCount != ParentCount)
1003 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001004 }
1005
1006 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001007 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001008 if (S->getInit())
1009 Visit(S->getInit());
1010
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001011 Counter ParentCount = getRegion().getCounter();
1012 Counter BodyCount = getRegionCounter(S);
1013
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001014 // The loop increment may contain a break or continue.
1015 if (S->getInc())
1016 BreakContinueStack.emplace_back();
1017
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001018 // Handle the body first so that we can get the backedge count.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001019 BreakContinueStack.emplace_back();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001020 extendRegion(S->getBody());
1021 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001022 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +00001023
1024 // The increment is essentially part of the body but it needs to include
1025 // the count for all the continue statements.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001026 BreakContinue IncrementBC;
1027 if (const Stmt *Inc = S->getInc()) {
1028 propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1029 IncrementBC = BreakContinueStack.pop_back_val();
1030 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001031
1032 // Go back to handle the condition.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001033 Counter CondCount = addCounters(
1034 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1035 IncrementBC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001036 if (const Expr *Cond = S->getCond()) {
1037 propagateCounts(CondCount, Cond);
1038 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +00001039 }
1040
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001041 // The body count applies to the area immediately after the increment.
1042 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1043 getStart(S->getBody()));
1044 if (Gap)
1045 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1046
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001047 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1048 subtractCounters(CondCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001049 if (OutCount != ParentCount)
1050 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001051 }
1052
1053 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001054 extendRegion(S);
Richard Smith8baa5002018-09-28 18:44:09 +00001055 if (S->getInit())
1056 Visit(S->getInit());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001057 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +00001058 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001059
1060 Counter ParentCount = getRegion().getCounter();
1061 Counter BodyCount = getRegionCounter(S);
1062
Alex Lorenzee024992014-08-04 18:41:51 +00001063 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001064 extendRegion(S->getBody());
1065 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001066 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001067
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001068 // The body count applies to the area immediately after the range.
1069 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1070 getStart(S->getBody()));
1071 if (Gap)
1072 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1073
Justin Bogner15874322015-04-30 21:31:02 +00001074 Counter LoopCount =
1075 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1076 Counter OutCount =
1077 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001078 if (OutCount != ParentCount)
1079 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001080 }
1081
1082 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001083 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001084 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001085
1086 Counter ParentCount = getRegion().getCounter();
1087 Counter BodyCount = getRegionCounter(S);
1088
Alex Lorenzee024992014-08-04 18:41:51 +00001089 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001090 extendRegion(S->getBody());
1091 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001092 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001093
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001094 // The body count applies to the area immediately after the collection.
1095 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1096 getStart(S->getBody()));
1097 if (Gap)
1098 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1099
Justin Bogner15874322015-04-30 21:31:02 +00001100 Counter LoopCount =
1101 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1102 Counter OutCount =
1103 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001104 if (OutCount != ParentCount)
1105 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001106 }
1107
1108 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001109 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +00001110 if (S->getInit())
1111 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +00001112 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001113
Alex Lorenzee024992014-08-04 18:41:51 +00001114 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001115
1116 const Stmt *Body = S->getBody();
1117 extendRegion(Body);
1118 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1119 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001120 // Make a region for the body of the switch. If the body starts with
1121 // a case, that case will reuse this region; otherwise, this covers
1122 // the unreachable code at the beginning of the switch body.
Vedant Kumar859bf4d2019-11-21 14:17:04 -08001123 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1124 getRegion().setGap(true);
Richard Trieub5841332015-04-15 01:21:42 +00001125 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001126 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001127
1128 // Set the end for the body of the switch, if it isn't already set.
1129 for (size_t i = RegionStack.size(); i != Index; --i) {
1130 if (!RegionStack[i - 1].hasEndLoc())
1131 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1132 }
1133
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001134 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001135 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001136 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001137 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001138 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001139
Alex Lorenzee024992014-08-04 18:41:51 +00001140 if (!BreakContinueStack.empty())
1141 BreakContinueStack.back().ContinueCount = addCounters(
1142 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001143
1144 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001145 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001146 pushRegion(ExitCount);
1147
1148 // Ensure that handleFileExit recognizes when the end location is located
1149 // in a different file.
1150 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001151 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001152 }
1153
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001154 void VisitSwitchCase(const SwitchCase *S) {
1155 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001156
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001157 SourceMappingRegion &Parent = getRegion();
1158
1159 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1160 // Reuse the existing region if it starts at our label. This is typical of
1161 // the first case in a switch.
Stephen Kellya6e43582018-08-09 21:05:56 +00001162 if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001163 Parent.setCounter(Count);
1164 else
1165 pushRegion(Count, getStart(S));
1166
Sanjay Patel376c06c2015-12-24 21:11:29 +00001167 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001168 Visit(CS->getLHS());
1169 if (const Expr *RHS = CS->getRHS())
1170 Visit(RHS);
1171 }
Alex Lorenzee024992014-08-04 18:41:51 +00001172 Visit(S->getSubStmt());
1173 }
1174
1175 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001176 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001177 if (S->getInit())
1178 Visit(S->getInit());
1179
Justin Bogner055ebc32015-06-16 06:24:15 +00001180 // Extend into the condition before we propagate through it below - this is
1181 // needed to handle macros that generate the "if" but not the condition.
1182 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001183
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001184 Counter ParentCount = getRegion().getCounter();
1185 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001186
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001187 // Emitting a counter for the condition makes it easier to interpret the
1188 // counter for the body when looking at the coverage.
1189 propagateCounts(ParentCount, S->getCond());
1190
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001191 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001192 auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1193 if (Gap)
1194 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001195
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001196 extendRegion(S->getThen());
1197 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1198
1199 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1200 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001201 // The 'else' count applies to the area immediately after the 'then'.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001202 Gap = findGapAreaBetween(S->getThen(), Else);
1203 if (Gap)
1204 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001205 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001206 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1207 } else
1208 OutCount = addCounters(OutCount, ElseCount);
1209
1210 if (OutCount != ParentCount)
1211 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001212 }
1213
1214 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001215 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001216 // Handle macros that generate the "try" but not the rest.
1217 extendRegion(S->getTryBlock());
1218
1219 Counter ParentCount = getRegion().getCounter();
1220 propagateCounts(ParentCount, S->getTryBlock());
1221
Alex Lorenzee024992014-08-04 18:41:51 +00001222 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1223 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001224
1225 Counter ExitCount = getRegionCounter(S);
1226 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001227 }
1228
1229 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001230 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001231 }
1232
1233 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001234 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001235
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001236 Counter ParentCount = getRegion().getCounter();
1237 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001238
Justin Bognere3654ce2015-04-24 23:37:57 +00001239 Visit(E->getCond());
1240
1241 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001242 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001243 auto Gap =
1244 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1245 if (Gap)
1246 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001247
Justin Bognere3654ce2015-04-24 23:37:57 +00001248 extendRegion(E->getTrueExpr());
1249 propagateCounts(TrueCount, E->getTrueExpr());
1250 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001251
Justin Bognere3654ce2015-04-24 23:37:57 +00001252 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001253 propagateCounts(subtractCounters(ParentCount, TrueCount),
1254 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001255 }
1256
1257 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001258 extendRegion(E->getLHS());
1259 propagateCounts(getRegion().getCounter(), E->getLHS());
1260 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001261
1262 extendRegion(E->getRHS());
1263 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001264 }
1265
1266 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001267 extendRegion(E->getLHS());
1268 propagateCounts(getRegion().getCounter(), E->getLHS());
1269 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001270
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001271 extendRegion(E->getRHS());
1272 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001273 }
Justin Bognerc1091022015-02-24 04:13:56 +00001274
1275 void VisitLambdaExpr(const LambdaExpr *LE) {
1276 // Lambdas are treated as their own functions for now, so we shouldn't
1277 // propagate counts into them.
1278 }
Alex Lorenzee024992014-08-04 18:41:51 +00001279};
Alex Lorenzee024992014-08-04 18:41:51 +00001280
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001281std::string normalizeFilename(StringRef Filename) {
1282 llvm::SmallString<256> Path(Filename);
1283 llvm::sys::fs::make_absolute(Path);
1284 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Jonas Devlieghere509e21a2020-01-29 21:27:46 -08001285 return std::string(Path);
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001286}
1287
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001288} // end anonymous namespace
1289
Justin Bognera432d172015-02-03 00:20:24 +00001290static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1291 ArrayRef<CounterExpression> Expressions,
1292 ArrayRef<CounterMappingRegion> Regions) {
1293 OS << FunctionName << ":\n";
1294 CounterMappingContext Ctx(Expressions);
1295 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001296 OS.indent(2);
1297 switch (R.Kind) {
1298 case CounterMappingRegion::CodeRegion:
1299 break;
1300 case CounterMappingRegion::ExpansionRegion:
1301 OS << "Expansion,";
1302 break;
1303 case CounterMappingRegion::SkippedRegion:
1304 OS << "Skipped,";
1305 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001306 case CounterMappingRegion::GapRegion:
1307 OS << "Gap,";
1308 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001309 }
1310
Justin Bogner4da909b2015-02-03 21:35:49 +00001311 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1312 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001313 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001314 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001315 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1316 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001317 }
1318}
1319
Vedant Kumar99317122019-10-21 11:48:38 -07001320static std::string getInstrProfSection(const CodeGenModule &CGM,
1321 llvm::InstrProfSectKind SK) {
1322 return llvm::getInstrProfSectionName(
1323 SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1324}
1325
1326void CoverageMappingModuleGen::emitFunctionMappingRecord(
1327 const FunctionInfo &Info, uint64_t FilenamesRef) {
1328 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1329
1330 // Assign a name to the function record. This is used to merge duplicates.
1331 std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1332
1333 // A dummy description for a function included-but-not-used in a TU can be
1334 // replaced by full description provided by a different TU. The two kinds of
1335 // descriptions play distinct roles: therefore, assign them different names
1336 // to prevent `linkonce_odr` merging.
1337 if (Info.IsUsed)
1338 FuncRecordName += "u";
1339
1340 // Create the function record type.
1341 const uint64_t NameHash = Info.NameHash;
1342 const uint64_t FuncHash = Info.FuncHash;
1343 const std::string &CoverageMapping = Info.CoverageMapping;
1344#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1345 llvm::Type *FunctionRecordTypes[] = {
1346#include "llvm/ProfileData/InstrProfData.inc"
1347 };
1348 auto *FunctionRecordTy =
1349 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1350 /*isPacked=*/true);
1351
1352 // Create the function record constant.
1353#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1354 llvm::Constant *FunctionRecordVals[] = {
1355 #include "llvm/ProfileData/InstrProfData.inc"
1356 };
1357 auto *FuncRecordConstant = llvm::ConstantStruct::get(
1358 FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1359
1360 // Create the function record global.
1361 auto *FuncRecord = new llvm::GlobalVariable(
1362 CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1363 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1364 FuncRecordName);
1365 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1366 FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1367 FuncRecord->setAlignment(llvm::Align(8));
1368 if (CGM.supportsCOMDAT())
1369 FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1370
1371 // Make sure the data doesn't get deleted.
1372 CGM.addUsedGlobal(FuncRecord);
1373}
1374
Alex Lorenzee024992014-08-04 18:41:51 +00001375void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001376 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001377 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001378 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Vedant Kumar99317122019-10-21 11:48:38 -07001379 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1380 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
Alex Lorenzee024992014-08-04 18:41:51 +00001381
Xinliang David Li848da132016-01-19 00:49:06 +00001382 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001383 FunctionNames.push_back(
1384 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001385
1386 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1387 // Dump the coverage mapping data for this function by decoding the
1388 // encoded data. This allows us to dump the mapping regions which were
1389 // also processed by the CoverageMappingWriter which performs
1390 // additional minimization operations such as reducing the number of
1391 // expressions.
1392 std::vector<StringRef> Filenames;
1393 std::vector<CounterExpression> Expressions;
1394 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001395 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001396 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001397 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001398 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001399 for (const auto &Entry : FileEntries) {
1400 auto I = Entry.second;
1401 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1402 FilenameRefs[I] = FilenameStrs[I];
1403 }
Justin Bognera432d172015-02-03 00:20:24 +00001404 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1405 Expressions, Regions);
1406 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001407 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001408 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001409 }
Alex Lorenzee024992014-08-04 18:41:51 +00001410}
1411
1412void CoverageMappingModuleGen::emit() {
1413 if (FunctionRecords.empty())
1414 return;
1415 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1416 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1417
1418 // Create the filenames and merge them with coverage mappings
1419 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001420 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001421 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001422 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001423 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001424 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001425 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001426 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001427 }
1428
Vedant Kumar99317122019-10-21 11:48:38 -07001429 std::string Filenames;
1430 {
1431 llvm::raw_string_ostream OS(Filenames);
1432 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001433 }
Vedant Kumar99317122019-10-21 11:48:38 -07001434 auto *FilenamesVal =
1435 llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1436 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001437
Vedant Kumar99317122019-10-21 11:48:38 -07001438 // Emit the function records.
1439 for (const FunctionInfo &Info : FunctionRecords)
1440 emitFunctionMappingRecord(Info, FilenamesRef);
Alex Lorenzee024992014-08-04 18:41:51 +00001441
Vedant Kumar99317122019-10-21 11:48:38 -07001442 const unsigned NRecords = 0;
1443 const size_t FilenamesSize = Filenames.size();
1444 const unsigned CoverageMappingSize = 0;
Xinliang David Li20b188c2016-01-03 19:25:54 +00001445 llvm::Type *CovDataHeaderTypes[] = {
1446#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1447#include "llvm/ProfileData/InstrProfData.inc"
1448 };
1449 auto CovDataHeaderTy =
1450 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1451 llvm::Constant *CovDataHeaderVals[] = {
1452#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1453#include "llvm/ProfileData/InstrProfData.inc"
1454 };
1455 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1456 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1457
Alex Lorenzee024992014-08-04 18:41:51 +00001458 // Create the coverage data record
Vedant Kumar99317122019-10-21 11:48:38 -07001459 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001460 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Vedant Kumar99317122019-10-21 11:48:38 -07001461 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001462 auto CovDataVal =
1463 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001464 auto CovData = new llvm::GlobalVariable(
Vedant Kumar99317122019-10-21 11:48:38 -07001465 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
Xinliang David Li20b188c2016-01-03 19:25:54 +00001466 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001467
Vedant Kumar99317122019-10-21 11:48:38 -07001468 CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001469 CovData->setAlignment(llvm::Align(8));
Alex Lorenzee024992014-08-04 18:41:51 +00001470
1471 // Make sure the data doesn't get deleted.
1472 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001473 // Create the deferred function records array
1474 if (!FunctionNames.empty()) {
1475 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1476 FunctionNames.size());
1477 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1478 // This variable will *NOT* be emitted to the object file. It is used
1479 // to pass the list of names referenced to codegen.
1480 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1481 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001482 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001483 }
Alex Lorenzee024992014-08-04 18:41:51 +00001484}
1485
1486unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1487 auto It = FileEntries.find(File);
1488 if (It != FileEntries.end())
1489 return It->second;
1490 unsigned FileID = FileEntries.size();
1491 FileEntries.insert(std::make_pair(File, FileID));
1492 return FileID;
1493}
1494
1495void CoverageMappingGen::emitCounterMapping(const Decl *D,
1496 llvm::raw_ostream &OS) {
1497 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001498 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001499 Walker.VisitDecl(D);
1500 Walker.write(OS);
1501}
1502
1503void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1504 llvm::raw_ostream &OS) {
1505 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1506 Walker.VisitDecl(D);
1507 Walker.write(OS);
1508}