blob: cdbfc88e7b7072063859623bfa9e63ff7f37fc0f [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 Kumardd1ea9d2019-10-21 11:48:38 -070016#include "clang/Basic/Diagnostic.h"
Reid Klecknere08464f2020-02-29 09:10:42 -080017#include "clang/Basic/FileManager.h"
Vedant Kumardd1ea9d2019-10-21 11:48:38 -070018#include "clang/Frontend/FrontendDiagnostic.h"
Alex Lorenzee024992014-08-04 18:41:51 +000019#include "clang/Lex/Lexer.h"
Reid Klecknere08464f2020-02-29 09:10:42 -080020#include "llvm/ADT/Optional.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000021#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000022#include "llvm/ADT/StringExtras.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000023#include "llvm/ProfileData/Coverage/CoverageMapping.h"
24#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000027#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000028#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000029
Vedant Kumardd1ea9d2019-10-21 11:48:38 -070030// This selects the coverage mapping format defined when `InstrProfData.inc`
31// is textually included.
32#define COVMAP_V3
33
Alex Lorenzee024992014-08-04 18:41:51 +000034using namespace clang;
35using namespace CodeGen;
36using namespace llvm::coverage;
37
Vedant Kumar3919a502017-09-11 20:47:42 +000038void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Alex Lorenzee024992014-08-04 18:41:51 +000039 SkippedRanges.push_back(Range);
40}
41
42namespace {
43
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000045class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000046 Counter Count;
47
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048 /// The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000049 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000051 /// The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000052 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000053
Vedant Kumar747b0e22017-09-08 18:44:56 +000054 /// Whether this region should be emitted after its parent is emitted.
55 bool DeferRegion;
56
Vedant Kumara1c4deb2017-09-18 23:37:30 +000057 /// Whether this region is a gap region. The count from a gap region is set
58 /// as the line execution count if there are no other regions on the line.
59 bool GapRegion;
60
Justin Bogner09c71792014-10-01 03:33:49 +000061public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000062 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara1c4deb2017-09-18 23:37:30 +000063 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
64 bool GapRegion = false)
Vedant Kumar747b0e22017-09-08 18:44:56 +000065 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
Vedant Kumara1c4deb2017-09-18 23:37:30 +000066 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000067
Justin Bogner09c71792014-10-01 03:33:49 +000068 const Counter &getCounter() const { return Count; }
69
Justin Bognerbf42cfd2015-02-18 21:24:51 +000070 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000071
Justin Bognerbf42cfd2015-02-18 21:24:51 +000072 bool hasStartLoc() const { return LocStart.hasValue(); }
73
74 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
75
Stephen Kelly3cffc4c2018-08-09 20:05:18 +000076 SourceLocation getBeginLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000077 assert(LocStart && "Region has no start location");
78 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000079 }
80
Justin Bognerbf42cfd2015-02-18 21:24:51 +000081 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000082
Vedant Kumara14a1f92018-01-17 18:53:51 +000083 void setEndLoc(SourceLocation Loc) {
84 assert(Loc.isValid() && "Setting an invalid end location");
85 LocEnd = Loc;
86 }
Alex Lorenzee024992014-08-04 18:41:51 +000087
Craig Topper462c77b2015-09-26 05:10:14 +000088 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000089 assert(LocEnd && "Region has no end location");
90 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000091 }
Vedant Kumar747b0e22017-09-08 18:44:56 +000092
93 bool isDeferred() const { return DeferRegion; }
94
95 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Vedant Kumara1c4deb2017-09-18 23:37:30 +000096
97 bool isGap() const { return GapRegion; }
98
99 void setGap(bool Gap) { GapRegion = Gap; }
Alex Lorenzee024992014-08-04 18:41:51 +0000100};
101
Vedant Kumard7369642017-07-27 02:20:25 +0000102/// Spelling locations for the start and end of a source region.
103struct SpellingRegion {
104 /// The line where the region starts.
105 unsigned LineStart;
106
107 /// The column where the region starts.
108 unsigned ColumnStart;
109
110 /// The line where the region ends.
111 unsigned LineEnd;
112
113 /// The column where the region ends.
114 unsigned ColumnEnd;
115
116 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
117 SourceLocation LocEnd) {
118 LineStart = SM.getSpellingLineNumber(LocStart);
119 ColumnStart = SM.getSpellingColumnNumber(LocStart);
120 LineEnd = SM.getSpellingLineNumber(LocEnd);
121 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
122 }
123
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000124 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
Stephen Kellya6e43582018-08-09 21:05:56 +0000125 : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000126
Vedant Kumard7369642017-07-27 02:20:25 +0000127 /// Check if the start and end locations appear in source order, i.e
128 /// top->bottom, left->right.
129 bool isInSourceOrder() const {
130 return (LineStart < LineEnd) ||
131 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
132 }
133};
134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000135/// Provides the common functionality for the different
Alex Lorenzee024992014-08-04 18:41:51 +0000136/// coverage mapping region builders.
137class CoverageMappingBuilder {
138public:
139 CoverageMappingModuleGen &CVM;
140 SourceManager &SM;
141 const LangOptions &LangOpts;
142
143private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000144 /// Map of clang's FileIDs to IDs used for coverage mapping.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000145 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
146 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000147
148public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000149 /// The coverage mapping regions for this function
Alex Lorenzee024992014-08-04 18:41:51 +0000150 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000151 /// The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000152 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000153
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000154 /// A set of regions which can be used as a filter.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000155 ///
156 /// It is produced by emitExpansionRegions() and is used in
157 /// emitSourceRegions() to suppress producing code regions if
158 /// the same area is covered by expansion regions.
159 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
160 SourceRegionFilter;
161
Alex Lorenzee024992014-08-04 18:41:51 +0000162 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
163 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000164 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000165
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000166 /// Return the precise end location for the given token.
Alex Lorenzee024992014-08-04 18:41:51 +0000167 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000168 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
169 // macro locations, which we just treat as expanded files.
170 unsigned TokLen =
171 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
172 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000173 }
174
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000175 /// Return the start location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000176 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
177 if (Loc.isMacroID())
178 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
179 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000180 }
181
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000182 /// Return the end location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000183 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
184 if (Loc.isMacroID())
185 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000186 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000187 return SM.getLocForEndOfFile(SM.getFileID(Loc));
188 }
189
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000190 /// Find out where the current file is included or macro is expanded.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000191 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
Richard Smithb5f81712018-04-30 05:25:48 +0000192 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000193 : SM.getIncludeLoc(SM.getFileID(Loc));
194 }
195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000196 /// Return true if \c Loc is a location in a built-in macro.
Justin Bogner682bfbf2015-05-14 22:14:10 +0000197 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000198 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000199 }
200
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000201 /// Check whether \c Loc is included or expanded from \c Parent.
Igor Kudrind9e1a612016-06-07 10:07:51 +0000202 bool isNestedIn(SourceLocation Loc, FileID Parent) {
203 do {
204 Loc = getIncludeOrExpansionLoc(Loc);
205 if (Loc.isInvalid())
206 return false;
207 } while (!SM.isInFileID(Loc, Parent));
208 return true;
209 }
210
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000211 /// Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000212 SourceLocation getStart(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000213 SourceLocation Loc = S->getBeginLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000214 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000215 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000216 return Loc;
217 }
218
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000219 /// Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000220 SourceLocation getEnd(const Stmt *S) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000221 SourceLocation Loc = S->getEndLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000222 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000223 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerf14b2072015-03-25 04:13:49 +0000224 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000225 }
226
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000227 /// Find the set of files we have regions for and assign IDs
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000228 ///
229 /// Fills \c Mapping with the virtual file mapping needed to write out
230 /// coverage and collects the necessary file information to emit source and
231 /// expansion regions.
232 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
233 FileIDMapping.clear();
234
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000235 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000236 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
237 for (const auto &Region : SourceRegions) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000238 SourceLocation Loc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000239 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000240 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000241 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000242
Vedant Kumar93205af2016-07-11 22:57:46 +0000243 // Do not map FileID's associated with system headers.
244 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
245 continue;
246
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000247 unsigned Depth = 0;
248 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000249 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000250 ++Depth;
251 FileLocs.push_back(std::make_pair(Loc, Depth));
252 }
Fangrui Song899d1392019-04-24 14:43:05 +0000253 llvm::stable_sort(FileLocs, llvm::less_second());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000254
255 for (const auto &FL : FileLocs) {
256 SourceLocation Loc = FL.first;
257 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
258 auto Entry = SM.getFileEntryForID(SpellingFile);
259 if (!Entry)
260 continue;
261
262 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
263 Mapping.push_back(CVM.getFileID(Entry));
264 }
265 }
266
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000267 /// Get the coverage mapping file ID for \c Loc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000268 ///
269 /// If such file id doesn't exist, return None.
270 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
271 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000272 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000273 return Mapping->second.first;
274 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000275 }
276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000277 /// Gather all the regions that were skipped by the preprocessor
Alex Lorenzee024992014-08-04 18:41:51 +0000278 /// using the constructs like #if.
279 void gatherSkippedRegions() {
280 /// An array of the minimum lineStarts and the maximum lineEnds
281 /// for mapping regions from the appropriate source files.
282 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
283 FileLineRanges.resize(
284 FileIDMapping.size(),
285 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
286 for (const auto &R : MappingRegions) {
287 FileLineRanges[R.FileID].first =
288 std::min(FileLineRanges[R.FileID].first, R.LineStart);
289 FileLineRanges[R.FileID].second =
290 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
291 }
292
293 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
294 for (const auto &I : SkippedRanges) {
295 auto LocStart = I.getBegin();
296 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000297 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
298 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000299
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000300 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000301 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000302 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000303 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000304 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000305 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000306 // Make sure that we only collect the regions that are inside
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000307 // the source code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000308 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
309 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000310 MappingRegions.push_back(Region);
311 }
312 }
313
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000314 /// Generate the coverage counter mapping regions from collected
Alex Lorenzee024992014-08-04 18:41:51 +0000315 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000316 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000317 for (const auto &Region : SourceRegions) {
318 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000319
Stephen Kellya6e43582018-08-09 21:05:56 +0000320 SourceLocation LocStart = Region.getBeginLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000321 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000322
Vedant Kumar93205af2016-07-11 22:57:46 +0000323 // Ignore regions from system headers.
324 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
325 continue;
326
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000327 auto CovFileID = getCoverageFileID(LocStart);
328 // Ignore regions that don't have a file, such as builtin macros.
329 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000330 continue;
331
Justin Bognerf14b2072015-03-25 04:13:49 +0000332 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000333 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
334 "region spans multiple files");
335
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000336 // Don't add code regions for the area covered by expansion regions.
337 // This not only suppresses redundant regions, but sometimes prevents
338 // creating regions with wrong counters if, for example, a statement's
339 // body ends at the end of a nested macro.
340 if (Filter.count(std::make_pair(LocStart, LocEnd)))
341 continue;
342
Vedant Kumard7369642017-07-27 02:20:25 +0000343 // Find the spelling locations for the mapping region.
344 SpellingRegion SR{SM, LocStart, LocEnd};
345 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000346
347 if (Region.isGap()) {
348 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
349 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
350 SR.LineEnd, SR.ColumnEnd));
351 } else {
352 MappingRegions.push_back(CounterMappingRegion::makeRegion(
353 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
354 SR.LineEnd, SR.ColumnEnd));
355 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000356 }
357 }
358
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000359 /// Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000360 SourceRegionFilter emitExpansionRegions() {
361 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000362 for (const auto &FM : FileIDMapping) {
363 SourceLocation ExpandedLoc = FM.second.second;
364 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
365 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000366 continue;
367
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000368 auto ParentFileID = getCoverageFileID(ParentLoc);
369 if (!ParentFileID)
370 continue;
371 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
372 assert(ExpandedFileID && "expansion in uncovered file");
373
374 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
375 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
376 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000377 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000378
Vedant Kumard7369642017-07-27 02:20:25 +0000379 SpellingRegion SR{SM, ParentLoc, LocEnd};
380 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000381 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000382 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
383 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000384 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000385 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000386 }
387};
388
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000389/// Creates unreachable coverage regions for the functions that
Alex Lorenzee024992014-08-04 18:41:51 +0000390/// are not emitted.
391struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
392 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
393 const LangOptions &LangOpts)
394 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
395
396 void VisitDecl(const Decl *D) {
397 if (!D->hasBody())
398 return;
399 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000400 SourceLocation Start = getStart(Body);
401 SourceLocation End = getEnd(Body);
402 if (!SM.isWrittenInSameFile(Start, End)) {
403 // Walk up to find the common ancestor.
404 // Correct the locations accordingly.
405 FileID StartFileID = SM.getFileID(Start);
406 FileID EndFileID = SM.getFileID(End);
407 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
408 Start = getIncludeOrExpansionLoc(Start);
409 assert(Start.isValid() &&
410 "Declaration start location not nested within a known region");
411 StartFileID = SM.getFileID(Start);
412 }
413 while (StartFileID != EndFileID) {
414 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
415 assert(End.isValid() &&
416 "Declaration end location not nested within a known region");
417 EndFileID = SM.getFileID(End);
418 }
419 }
420 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000421 }
422
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000423 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000424 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000425 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000426 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000427 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000428
Vedant Kumarefd319a2016-07-26 00:24:59 +0000429 if (MappingRegions.empty())
430 return;
431
Craig Topper5fc8fc22014-08-27 06:28:36 +0000432 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000433 Writer.write(OS);
434 }
435};
436
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437/// A StmtVisitor that creates coverage mapping regions which map
Alex Lorenzee024992014-08-04 18:41:51 +0000438/// from the source code locations to the PGO counters.
439struct CounterCoverageMappingBuilder
440 : public CoverageMappingBuilder,
441 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000442 /// The map of statements to count values.
Alex Lorenzee024992014-08-04 18:41:51 +0000443 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
444
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// A stack of currently live regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000446 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000447
Vedant Kumar747b0e22017-09-08 18:44:56 +0000448 /// The currently deferred region: its end location and count can be set once
449 /// its parent has been popped from the region stack.
450 Optional<SourceMappingRegion> DeferredRegion;
451
Alex Lorenzee024992014-08-04 18:41:51 +0000452 CounterExpressionBuilder Builder;
453
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000454 /// A location in the most recently visited file or macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000455 ///
456 /// This is used to adjust the active source regions appropriately when
457 /// expressions cross file or macro boundaries.
458 SourceLocation MostRecentLocation;
459
Vedant Kumar8046d222017-11-09 02:33:39 +0000460 /// Location of the last terminated region.
461 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
462
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000463 /// Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000464 Counter subtractCounters(Counter LHS, Counter RHS) {
465 return Builder.subtract(LHS, RHS);
466 }
467
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000468 /// Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000469 Counter addCounters(Counter LHS, Counter RHS) {
470 return Builder.add(LHS, RHS);
471 }
472
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000473 Counter addCounters(Counter C1, Counter C2, Counter C3) {
474 return addCounters(addCounters(C1, C2), C3);
475 }
476
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000477 /// Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000478 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000479 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000480 Counter getRegionCounter(const Stmt *S) {
481 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000482 }
483
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000484 /// Push a region onto the stack.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000485 ///
486 /// Returns the index on the stack where the region was pushed. This can be
487 /// used with popRegions to exit a "scope", ending the region that was pushed.
488 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
489 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000490 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000491 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000492 completeDeferred(Count, MostRecentLocation);
493 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000494 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000495
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000496 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000497 }
498
Vedant Kumar747b0e22017-09-08 18:44:56 +0000499 /// Complete any pending deferred region by setting its end location and
500 /// count, and then pushing it onto the region stack.
501 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
502 size_t Index = RegionStack.size();
503 if (!DeferredRegion)
504 return Index;
505
506 // Consume the pending region.
507 SourceMappingRegion DR = DeferredRegion.getValue();
508 DeferredRegion = None;
509
510 // If the region ends in an expansion, find the expansion site.
Stephen Kellya6e43582018-08-09 21:05:56 +0000511 FileID StartFile = SM.getFileID(DR.getBeginLoc());
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000512 if (SM.getFileID(DeferredEndLoc) != StartFile) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000513 if (isNestedIn(DeferredEndLoc, StartFile)) {
514 do {
515 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
516 } while (StartFile != SM.getFileID(DeferredEndLoc));
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000517 } else {
518 return Index;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000519 }
520 }
521
522 // The parent of this deferred region ends where the containing decl ends,
523 // so the region isn't useful.
Stephen Kellya6e43582018-08-09 21:05:56 +0000524 if (DR.getBeginLoc() == DeferredEndLoc)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000525 return Index;
526
527 // If we're visiting statements in non-source order (e.g switch cases or
528 // a loop condition) we can't construct a sensible deferred region.
Stephen Kellya6e43582018-08-09 21:05:56 +0000529 if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000530 return Index;
531
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000532 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000533 DR.setCounter(Count);
534 DR.setEndLoc(DeferredEndLoc);
535 handleFileExit(DeferredEndLoc);
536 RegionStack.push_back(DR);
537 return Index;
538 }
539
Vedant Kumar8046d222017-11-09 02:33:39 +0000540 /// Complete a deferred region created after a terminated region at the
541 /// top-level.
542 void completeTopLevelDeferredRegion(Counter Count,
543 SourceLocation DeferredEndLoc) {
544 if (DeferredRegion || !LastTerminatedRegion)
545 return;
546
547 if (LastTerminatedRegion->second != RegionStack.size())
548 return;
549
550 SourceLocation Start = LastTerminatedRegion->first;
551 if (SM.getFileID(Start) != SM.getMainFileID())
552 return;
553
554 SourceMappingRegion DR = RegionStack.back();
555 DR.setStartLoc(Start);
556 DR.setDeferred(false);
557 DeferredRegion = DR;
558 completeDeferred(Count, DeferredEndLoc);
559 }
560
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000561 size_t locationDepth(SourceLocation Loc) {
562 size_t Depth = 0;
563 while (Loc.isValid()) {
564 Loc = getIncludeOrExpansionLoc(Loc);
565 Depth++;
566 }
567 return Depth;
568 }
569
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000570 /// Pop regions from the stack into the function's list of regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000571 ///
572 /// Adds all regions from \c ParentIndex to the top of the stack to the
573 /// function's \c SourceRegions.
574 void popRegions(size_t ParentIndex) {
575 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000576 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000577 while (RegionStack.size() > ParentIndex) {
578 SourceMappingRegion &Region = RegionStack.back();
579 if (Region.hasStartLoc()) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000580 SourceLocation StartLoc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000581 SourceLocation EndLoc = Region.hasEndLoc()
582 ? Region.getEndLoc()
583 : RegionStack[ParentIndex].getEndLoc();
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000584 size_t StartDepth = locationDepth(StartLoc);
585 size_t EndDepth = locationDepth(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000586 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000587 bool UnnestStart = StartDepth >= EndDepth;
588 bool UnnestEnd = EndDepth >= StartDepth;
589 if (UnnestEnd) {
590 // The region ends in a nested file or macro expansion. Create a
591 // separate region for each expansion.
592 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
593 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000594
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000595 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
596 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000597
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000598 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
599 if (EndLoc.isInvalid())
600 llvm::report_fatal_error("File exit not handled before popRegions");
601 EndDepth--;
602 }
603 if (UnnestStart) {
604 // The region begins in a nested file or macro expansion. Create a
605 // separate region for each expansion.
606 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
607 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
608
609 if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
610 SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
611
612 StartLoc = getIncludeOrExpansionLoc(StartLoc);
613 if (StartLoc.isInvalid())
614 llvm::report_fatal_error("File exit not handled before popRegions");
615 StartDepth--;
616 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000617 }
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000618 Region.setStartLoc(StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000619 Region.setEndLoc(EndLoc);
620
621 MostRecentLocation = EndLoc;
622 // If this region happens to span an entire expansion, we need to make
623 // sure we don't overlap the parent region with it.
624 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
625 EndLoc == getEndOfFileOrMacro(EndLoc))
626 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
627
Stephen Kellya6e43582018-08-09 21:05:56 +0000628 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000629 assert(SpellingRegion(SM, Region).isInSourceOrder());
Craig Topperf36a5c42015-09-26 05:10:16 +0000630 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000631
632 if (ParentOfDeferredRegion) {
633 ParentOfDeferredRegion = false;
634
635 // If there's an existing deferred region, keep the old one, because
636 // it means there are two consecutive returns (or a similar pattern).
637 if (!DeferredRegion.hasValue() &&
638 // File IDs aren't gathered within macro expansions, so it isn't
639 // useful to try and create a deferred region inside of one.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000640 !EndLoc.isMacroID())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000641 DeferredRegion =
642 SourceMappingRegion(Counter::getZero(), EndLoc, None);
643 }
644 } else if (Region.isDeferred()) {
645 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
646 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000647 }
648 RegionStack.pop_back();
Vedant Kumar8046d222017-11-09 02:33:39 +0000649
650 // If the zero region pushed after the last terminated region no longer
651 // exists, clear its cached information.
652 if (LastTerminatedRegion &&
653 RegionStack.size() < LastTerminatedRegion->second)
654 LastTerminatedRegion = None;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000655 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000656 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000657 }
658
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000659 /// Return the currently active region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000660 SourceMappingRegion &getRegion() {
661 assert(!RegionStack.empty() && "statement has no region");
662 return RegionStack.back();
663 }
Alex Lorenzee024992014-08-04 18:41:51 +0000664
Vedant Kumar7225a262018-11-28 20:48:07 +0000665 /// Propagate counts through the children of \p S if \p VisitChildren is true.
666 /// Otherwise, only emit a count for \p S itself.
667 Counter propagateCounts(Counter TopCount, const Stmt *S,
668 bool VisitChildren = true) {
Vedant Kumar78386962017-07-27 02:20:20 +0000669 SourceLocation StartLoc = getStart(S);
670 SourceLocation EndLoc = getEnd(S);
671 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Vedant Kumar7225a262018-11-28 20:48:07 +0000672 if (VisitChildren)
673 Visit(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000674 Counter ExitCount = getRegion().getCounter();
675 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000676
677 // The statement may be spanned by an expansion. Make sure we handle a file
678 // exit out of this expansion before moving to the next statement.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000679 if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
Vedant Kumar78386962017-07-27 02:20:20 +0000680 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000681
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000682 return ExitCount;
683 }
Alex Lorenzee024992014-08-04 18:41:51 +0000684
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000685 /// Check whether a region with bounds \c StartLoc and \c EndLoc
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000686 /// is already added to \c SourceRegions.
687 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
688 return SourceRegions.rend() !=
689 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
690 [&](const SourceMappingRegion &Region) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000691 return Region.getBeginLoc() == StartLoc &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000692 Region.getEndLoc() == EndLoc;
693 });
694 }
695
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000696 /// Adjust the most recently visited location to \c EndLoc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000697 ///
698 /// This should be used after visiting any statements in non-source order.
699 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
700 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000701 // The code region for a whole macro is created in handleFileExit() when
702 // it detects exiting of the virtual file of that macro. If we visited
703 // statements in non-source order, we might already have such a region
704 // added, for example, if a body of a loop is divided among multiple
705 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000706 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000707 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
708 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
709 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000710 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
711 }
Alex Lorenzee024992014-08-04 18:41:51 +0000712
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000713 /// Adjust regions and state when \c NewLoc exits a file.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000714 ///
715 /// If moving from our most recently tracked location to \c NewLoc exits any
716 /// files, this adjusts our current region stack and creates the file regions
717 /// for the exited file.
718 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000719 if (NewLoc.isInvalid() ||
720 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000721 return;
722
723 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
724 // find the common ancestor.
725 SourceLocation LCA = NewLoc;
726 FileID ParentFile = SM.getFileID(LCA);
727 while (!isNestedIn(MostRecentLocation, ParentFile)) {
728 LCA = getIncludeOrExpansionLoc(LCA);
729 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
730 // Since there isn't a common ancestor, no file was exited. We just need
731 // to adjust our location to the new file.
732 MostRecentLocation = NewLoc;
733 return;
734 }
735 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000736 }
737
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000738 llvm::SmallSet<SourceLocation, 8> StartLocs;
739 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000740 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
741 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000742 continue;
Stephen Kellya6e43582018-08-09 21:05:56 +0000743 SourceLocation Loc = I.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000744 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000745 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000746 break;
747 }
Alex Lorenzee024992014-08-04 18:41:51 +0000748
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000749 while (!SM.isInFileID(Loc, ParentFile)) {
750 // The most nested region for each start location is the one with the
751 // correct count. We avoid creating redundant regions by stopping once
752 // we've seen this region.
753 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000754 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000755 getEndOfFileOrMacro(Loc));
756 Loc = getIncludeOrExpansionLoc(Loc);
757 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000758 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000759 }
760
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000761 if (ParentCounter) {
762 // If the file is contained completely by another region and doesn't
763 // immediately start its own region, the whole file gets a region
764 // corresponding to the parent.
765 SourceLocation Loc = MostRecentLocation;
766 while (isNestedIn(Loc, ParentFile)) {
767 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000768 if (StartLocs.insert(FileStart).second) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000769 SourceRegions.emplace_back(*ParentCounter, FileStart,
770 getEndOfFileOrMacro(Loc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000771 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
772 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000773 Loc = getIncludeOrExpansionLoc(Loc);
774 }
Alex Lorenzee024992014-08-04 18:41:51 +0000775 }
776
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000777 MostRecentLocation = NewLoc;
778 }
Alex Lorenzee024992014-08-04 18:41:51 +0000779
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000780 /// Ensure that \c S is included in the current region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000781 void extendRegion(const Stmt *S) {
782 SourceMappingRegion &Region = getRegion();
783 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000784
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000785 handleFileExit(StartLoc);
786 if (!Region.hasStartLoc())
787 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000788
789 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000790 }
791
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000792 /// Mark \c S as a terminator, starting a zero region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000793 void terminateRegion(const Stmt *S) {
794 extendRegion(S);
795 SourceMappingRegion &Region = getRegion();
Vedant Kumar8046d222017-11-09 02:33:39 +0000796 SourceLocation EndLoc = getEnd(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000797 if (!Region.hasEndLoc())
Vedant Kumar8046d222017-11-09 02:33:39 +0000798 Region.setEndLoc(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000799 pushRegion(Counter::getZero());
Vedant Kumar8046d222017-11-09 02:33:39 +0000800 auto &ZeroRegion = getRegion();
801 ZeroRegion.setDeferred(true);
802 LastTerminatedRegion = {EndLoc, RegionStack.size()};
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000803 }
Alex Lorenzee024992014-08-04 18:41:51 +0000804
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000805 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
806 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
807 SourceLocation BeforeLoc) {
808 // If the start and end locations of the gap are both within the same macro
809 // file, the range may not be in source order.
810 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
811 return None;
812 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
813 return None;
814 return {{AfterLoc, BeforeLoc}};
815 }
816
817 /// Find the source range after \p AfterStmt and before \p BeforeStmt.
818 Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
819 const Stmt *BeforeStmt) {
820 return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
821 getStart(BeforeStmt));
822 }
823
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000824 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
825 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
826 Counter Count) {
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000827 if (StartLoc == EndLoc)
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000828 return;
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000829 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000830 handleFileExit(StartLoc);
831 size_t Index = pushRegion(Count, StartLoc, EndLoc);
832 getRegion().setGap(true);
833 handleFileExit(EndLoc);
834 popRegions(Index);
835 }
836
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000837 /// Keep counts of breaks and continues inside loops.
Alex Lorenzee024992014-08-04 18:41:51 +0000838 struct BreakContinue {
839 Counter BreakCount;
840 Counter ContinueCount;
841 };
842 SmallVector<BreakContinue, 8> BreakContinueStack;
843
844 CounterCoverageMappingBuilder(
845 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000846 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000847 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000848 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
849 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000850
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000851 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000852 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000853 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000854 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000855 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000856 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000857 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000858 gatherSkippedRegions();
859
Vedant Kumarefd319a2016-07-26 00:24:59 +0000860 if (MappingRegions.empty())
861 return;
862
Justin Bogner4da909b2015-02-03 21:35:49 +0000863 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
864 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000865 Writer.write(OS);
866 }
867
Alex Lorenzee024992014-08-04 18:41:51 +0000868 void VisitStmt(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000869 if (S->getBeginLoc().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000870 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000871 for (const Stmt *Child : S->children())
872 if (Child)
873 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000874 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000875 }
876
Alex Lorenzee024992014-08-04 18:41:51 +0000877 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000878 assert(!DeferredRegion && "Deferred region never completed");
879
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000880 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000881
882 // Do not propagate region counts into system headers.
883 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
884 return;
885
Vedant Kumar7225a262018-11-28 20:48:07 +0000886 // Do not visit the artificial children nodes of defaulted methods. The
887 // lexer may not be able to report back precise token end locations for
888 // these children nodes (llvm.org/PR39822), and moreover users will not be
889 // able to see coverage for them.
890 bool Defaulted = false;
891 if (auto *Method = dyn_cast<CXXMethodDecl>(D))
892 Defaulted = Method->isDefaulted();
893
894 propagateCounts(getRegionCounter(Body), Body,
895 /*VisitChildren=*/!Defaulted);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000896 assert(RegionStack.empty() && "Regions entered but never exited");
897
Vedant Kumar61763b62018-05-30 23:35:44 +0000898 // Discard the last uncompleted deferred region in a decl, if one exists.
899 // This prevents lines at the end of a function containing only whitespace
900 // or closing braces from being marked as uncovered.
901 DeferredRegion = None;
Alex Lorenzee024992014-08-04 18:41:51 +0000902 }
903
904 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000905 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000906 if (S->getRetValue())
907 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000908 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000909 }
910
Justin Bognerf959feb2015-04-28 06:31:55 +0000911 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
912 extendRegion(E);
913 if (E->getSubExpr())
914 Visit(E->getSubExpr());
915 terminateRegion(E);
916 }
917
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000918 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000919
920 void VisitLabelStmt(const LabelStmt *S) {
Vedant Kumar8046d222017-11-09 02:33:39 +0000921 Counter LabelCount = getRegionCounter(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000922 SourceLocation Start = getStart(S);
Vedant Kumar8046d222017-11-09 02:33:39 +0000923 completeTopLevelDeferredRegion(LabelCount, Start);
Vedant Kumard781d972018-06-01 00:37:13 +0000924 completeDeferred(LabelCount, Start);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000925 // We can't extendRegion here or we risk overlapping with our new region.
926 handleFileExit(Start);
Vedant Kumar8046d222017-11-09 02:33:39 +0000927 pushRegion(LabelCount, Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000928 Visit(S->getSubStmt());
929 }
930
931 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000932 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
933 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000934 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000935 // FIXME: a break in a switch should terminate regions for all preceding
936 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000937 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000938 }
939
940 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000941 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
942 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000943 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
944 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000945 }
946
Eli Friedman181dfe42017-08-08 20:10:14 +0000947 void VisitCallExpr(const CallExpr *E) {
948 VisitStmt(E);
949
950 // Terminate the region when we hit a noreturn function.
951 // (This is helpful dealing with switch statements.)
952 QualType CalleeType = E->getCallee()->getType();
953 if (getFunctionExtInfo(*CalleeType).getNoReturn())
954 terminateRegion(E);
955 }
956
Alex Lorenzee024992014-08-04 18:41:51 +0000957 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000958 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000959
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000960 Counter ParentCount = getRegion().getCounter();
961 Counter BodyCount = getRegionCounter(S);
962
963 // Handle the body first so that we can get the backedge count.
964 BreakContinueStack.push_back(BreakContinue());
965 extendRegion(S->getBody());
966 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000967 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000968
969 // Go back to handle the condition.
970 Counter CondCount =
971 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
972 propagateCounts(CondCount, S->getCond());
973 adjustForOutOfOrderTraversal(getEnd(S));
974
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000975 // The body count applies to the area immediately after the increment.
976 auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
977 if (Gap)
978 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
979
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000980 Counter OutCount =
981 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
982 if (OutCount != ParentCount)
983 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000984 }
985
986 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000987 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000988
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000989 Counter ParentCount = getRegion().getCounter();
990 Counter BodyCount = getRegionCounter(S);
991
992 BreakContinueStack.push_back(BreakContinue());
993 extendRegion(S->getBody());
994 Counter BackedgeCount =
995 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000996 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000997
998 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
999 propagateCounts(CondCount, S->getCond());
1000
1001 Counter OutCount =
1002 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1003 if (OutCount != ParentCount)
1004 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001005 }
1006
1007 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001008 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001009 if (S->getInit())
1010 Visit(S->getInit());
1011
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001012 Counter ParentCount = getRegion().getCounter();
1013 Counter BodyCount = getRegionCounter(S);
1014
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001015 // The loop increment may contain a break or continue.
1016 if (S->getInc())
1017 BreakContinueStack.emplace_back();
1018
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001019 // Handle the body first so that we can get the backedge count.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001020 BreakContinueStack.emplace_back();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001021 extendRegion(S->getBody());
1022 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001023 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +00001024
1025 // The increment is essentially part of the body but it needs to include
1026 // the count for all the continue statements.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001027 BreakContinue IncrementBC;
1028 if (const Stmt *Inc = S->getInc()) {
1029 propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1030 IncrementBC = BreakContinueStack.pop_back_val();
1031 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001032
1033 // Go back to handle the condition.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001034 Counter CondCount = addCounters(
1035 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1036 IncrementBC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001037 if (const Expr *Cond = S->getCond()) {
1038 propagateCounts(CondCount, Cond);
1039 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +00001040 }
1041
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001042 // The body count applies to the area immediately after the increment.
1043 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1044 getStart(S->getBody()));
1045 if (Gap)
1046 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1047
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001048 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1049 subtractCounters(CondCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001050 if (OutCount != ParentCount)
1051 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001052 }
1053
1054 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001055 extendRegion(S);
Richard Smith8baa5002018-09-28 18:44:09 +00001056 if (S->getInit())
1057 Visit(S->getInit());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001058 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +00001059 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001060
1061 Counter ParentCount = getRegion().getCounter();
1062 Counter BodyCount = getRegionCounter(S);
1063
Alex Lorenzee024992014-08-04 18:41:51 +00001064 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001065 extendRegion(S->getBody());
1066 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001067 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001068
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001069 // The body count applies to the area immediately after the range.
1070 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1071 getStart(S->getBody()));
1072 if (Gap)
1073 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1074
Justin Bogner15874322015-04-30 21:31:02 +00001075 Counter LoopCount =
1076 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1077 Counter OutCount =
1078 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001079 if (OutCount != ParentCount)
1080 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001081 }
1082
1083 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001084 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001085 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001086
1087 Counter ParentCount = getRegion().getCounter();
1088 Counter BodyCount = getRegionCounter(S);
1089
Alex Lorenzee024992014-08-04 18:41:51 +00001090 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001091 extendRegion(S->getBody());
1092 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001093 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001094
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001095 // The body count applies to the area immediately after the collection.
1096 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1097 getStart(S->getBody()));
1098 if (Gap)
1099 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1100
Justin Bogner15874322015-04-30 21:31:02 +00001101 Counter LoopCount =
1102 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1103 Counter OutCount =
1104 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001105 if (OutCount != ParentCount)
1106 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001107 }
1108
1109 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001110 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +00001111 if (S->getInit())
1112 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +00001113 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001114
Alex Lorenzee024992014-08-04 18:41:51 +00001115 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001116
1117 const Stmt *Body = S->getBody();
1118 extendRegion(Body);
1119 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1120 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001121 // Make a region for the body of the switch. If the body starts with
1122 // a case, that case will reuse this region; otherwise, this covers
1123 // the unreachable code at the beginning of the switch body.
Vedant Kumar859bf4d2019-11-21 14:17:04 -08001124 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1125 getRegion().setGap(true);
Richard Trieub5841332015-04-15 01:21:42 +00001126 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001127 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001128
1129 // Set the end for the body of the switch, if it isn't already set.
1130 for (size_t i = RegionStack.size(); i != Index; --i) {
1131 if (!RegionStack[i - 1].hasEndLoc())
1132 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1133 }
1134
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001135 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001136 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001137 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001138 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001139 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001140
Alex Lorenzee024992014-08-04 18:41:51 +00001141 if (!BreakContinueStack.empty())
1142 BreakContinueStack.back().ContinueCount = addCounters(
1143 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001144
1145 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001146 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001147 pushRegion(ExitCount);
1148
1149 // Ensure that handleFileExit recognizes when the end location is located
1150 // in a different file.
1151 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001152 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001153 }
1154
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001155 void VisitSwitchCase(const SwitchCase *S) {
1156 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001157
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001158 SourceMappingRegion &Parent = getRegion();
1159
1160 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1161 // Reuse the existing region if it starts at our label. This is typical of
1162 // the first case in a switch.
Stephen Kellya6e43582018-08-09 21:05:56 +00001163 if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001164 Parent.setCounter(Count);
1165 else
1166 pushRegion(Count, getStart(S));
1167
Sanjay Patel376c06c2015-12-24 21:11:29 +00001168 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001169 Visit(CS->getLHS());
1170 if (const Expr *RHS = CS->getRHS())
1171 Visit(RHS);
1172 }
Alex Lorenzee024992014-08-04 18:41:51 +00001173 Visit(S->getSubStmt());
1174 }
1175
1176 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001177 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001178 if (S->getInit())
1179 Visit(S->getInit());
1180
Justin Bogner055ebc32015-06-16 06:24:15 +00001181 // Extend into the condition before we propagate through it below - this is
1182 // needed to handle macros that generate the "if" but not the condition.
1183 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001184
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001185 Counter ParentCount = getRegion().getCounter();
1186 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001187
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001188 // Emitting a counter for the condition makes it easier to interpret the
1189 // counter for the body when looking at the coverage.
1190 propagateCounts(ParentCount, S->getCond());
1191
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001192 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001193 auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1194 if (Gap)
1195 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001196
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001197 extendRegion(S->getThen());
1198 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1199
1200 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1201 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001202 // The 'else' count applies to the area immediately after the 'then'.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001203 Gap = findGapAreaBetween(S->getThen(), Else);
1204 if (Gap)
1205 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001206 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001207 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1208 } else
1209 OutCount = addCounters(OutCount, ElseCount);
1210
1211 if (OutCount != ParentCount)
1212 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001213 }
1214
1215 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001216 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001217 // Handle macros that generate the "try" but not the rest.
1218 extendRegion(S->getTryBlock());
1219
1220 Counter ParentCount = getRegion().getCounter();
1221 propagateCounts(ParentCount, S->getTryBlock());
1222
Alex Lorenzee024992014-08-04 18:41:51 +00001223 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1224 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001225
1226 Counter ExitCount = getRegionCounter(S);
1227 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001228 }
1229
1230 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001231 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001232 }
1233
1234 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001235 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001236
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001237 Counter ParentCount = getRegion().getCounter();
1238 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001239
Justin Bognere3654ce2015-04-24 23:37:57 +00001240 Visit(E->getCond());
1241
1242 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001243 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001244 auto Gap =
1245 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1246 if (Gap)
1247 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001248
Justin Bognere3654ce2015-04-24 23:37:57 +00001249 extendRegion(E->getTrueExpr());
1250 propagateCounts(TrueCount, E->getTrueExpr());
1251 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001252
Justin Bognere3654ce2015-04-24 23:37:57 +00001253 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001254 propagateCounts(subtractCounters(ParentCount, TrueCount),
1255 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001256 }
1257
1258 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001259 extendRegion(E->getLHS());
1260 propagateCounts(getRegion().getCounter(), E->getLHS());
1261 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001262
1263 extendRegion(E->getRHS());
1264 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001265 }
1266
1267 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001268 extendRegion(E->getLHS());
1269 propagateCounts(getRegion().getCounter(), E->getLHS());
1270 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001271
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001272 extendRegion(E->getRHS());
1273 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001274 }
Justin Bognerc1091022015-02-24 04:13:56 +00001275
1276 void VisitLambdaExpr(const LambdaExpr *LE) {
1277 // Lambdas are treated as their own functions for now, so we shouldn't
1278 // propagate counts into them.
1279 }
Alex Lorenzee024992014-08-04 18:41:51 +00001280};
Alex Lorenzee024992014-08-04 18:41:51 +00001281
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001282std::string normalizeFilename(StringRef Filename) {
1283 llvm::SmallString<256> Path(Filename);
1284 llvm::sys::fs::make_absolute(Path);
1285 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Jonas Devlieghere509e21a2020-01-29 21:27:46 -08001286 return std::string(Path);
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001287}
1288
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001289} // end anonymous namespace
1290
Justin Bognera432d172015-02-03 00:20:24 +00001291static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1292 ArrayRef<CounterExpression> Expressions,
1293 ArrayRef<CounterMappingRegion> Regions) {
1294 OS << FunctionName << ":\n";
1295 CounterMappingContext Ctx(Expressions);
1296 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001297 OS.indent(2);
1298 switch (R.Kind) {
1299 case CounterMappingRegion::CodeRegion:
1300 break;
1301 case CounterMappingRegion::ExpansionRegion:
1302 OS << "Expansion,";
1303 break;
1304 case CounterMappingRegion::SkippedRegion:
1305 OS << "Skipped,";
1306 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001307 case CounterMappingRegion::GapRegion:
1308 OS << "Gap,";
1309 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001310 }
1311
Justin Bogner4da909b2015-02-03 21:35:49 +00001312 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1313 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001314 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001315 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001316 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1317 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001318 }
1319}
1320
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001321static std::string getInstrProfSection(const CodeGenModule &CGM,
1322 llvm::InstrProfSectKind SK) {
1323 return llvm::getInstrProfSectionName(
1324 SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1325}
1326
1327void CoverageMappingModuleGen::emitFunctionMappingRecord(
1328 const FunctionInfo &Info, uint64_t FilenamesRef) {
1329 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1330
1331 // Assign a name to the function record. This is used to merge duplicates.
1332 std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1333
1334 // A dummy description for a function included-but-not-used in a TU can be
1335 // replaced by full description provided by a different TU. The two kinds of
1336 // descriptions play distinct roles: therefore, assign them different names
1337 // to prevent `linkonce_odr` merging.
1338 if (Info.IsUsed)
1339 FuncRecordName += "u";
1340
1341 // Create the function record type.
1342 const uint64_t NameHash = Info.NameHash;
1343 const uint64_t FuncHash = Info.FuncHash;
1344 const std::string &CoverageMapping = Info.CoverageMapping;
1345#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1346 llvm::Type *FunctionRecordTypes[] = {
1347#include "llvm/ProfileData/InstrProfData.inc"
1348 };
1349 auto *FunctionRecordTy =
1350 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1351 /*isPacked=*/true);
1352
1353 // Create the function record constant.
1354#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1355 llvm::Constant *FunctionRecordVals[] = {
1356 #include "llvm/ProfileData/InstrProfData.inc"
1357 };
1358 auto *FuncRecordConstant = llvm::ConstantStruct::get(
1359 FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1360
1361 // Create the function record global.
1362 auto *FuncRecord = new llvm::GlobalVariable(
1363 CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1364 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1365 FuncRecordName);
1366 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1367 FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1368 FuncRecord->setAlignment(llvm::Align(8));
1369 if (CGM.supportsCOMDAT())
1370 FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1371
1372 // Make sure the data doesn't get deleted.
1373 CGM.addUsedGlobal(FuncRecord);
1374}
1375
Alex Lorenzee024992014-08-04 18:41:51 +00001376void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001377 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001378 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001379 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001380 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1381 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
Alex Lorenzee024992014-08-04 18:41:51 +00001382
Xinliang David Li848da132016-01-19 00:49:06 +00001383 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001384 FunctionNames.push_back(
1385 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001386
1387 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1388 // Dump the coverage mapping data for this function by decoding the
1389 // encoded data. This allows us to dump the mapping regions which were
1390 // also processed by the CoverageMappingWriter which performs
1391 // additional minimization operations such as reducing the number of
1392 // expressions.
1393 std::vector<StringRef> Filenames;
1394 std::vector<CounterExpression> Expressions;
1395 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001396 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001397 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001398 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001399 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001400 for (const auto &Entry : FileEntries) {
1401 auto I = Entry.second;
1402 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1403 FilenameRefs[I] = FilenameStrs[I];
1404 }
Justin Bognera432d172015-02-03 00:20:24 +00001405 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1406 Expressions, Regions);
1407 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001408 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001409 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001410 }
Alex Lorenzee024992014-08-04 18:41:51 +00001411}
1412
1413void CoverageMappingModuleGen::emit() {
1414 if (FunctionRecords.empty())
1415 return;
1416 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1417 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1418
1419 // Create the filenames and merge them with coverage mappings
1420 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001421 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001422 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001423 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001424 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001425 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001426 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001427 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001428 }
1429
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001430 std::string Filenames;
1431 {
1432 llvm::raw_string_ostream OS(Filenames);
1433 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001434 }
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001435 auto *FilenamesVal =
1436 llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1437 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001438
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001439 // Emit the function records.
1440 for (const FunctionInfo &Info : FunctionRecords)
1441 emitFunctionMappingRecord(Info, FilenamesRef);
Alex Lorenzee024992014-08-04 18:41:51 +00001442
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001443 const unsigned NRecords = 0;
1444 const size_t FilenamesSize = Filenames.size();
1445 const unsigned CoverageMappingSize = 0;
Xinliang David Li20b188c2016-01-03 19:25:54 +00001446 llvm::Type *CovDataHeaderTypes[] = {
1447#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1448#include "llvm/ProfileData/InstrProfData.inc"
1449 };
1450 auto CovDataHeaderTy =
1451 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1452 llvm::Constant *CovDataHeaderVals[] = {
1453#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1454#include "llvm/ProfileData/InstrProfData.inc"
1455 };
1456 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1457 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1458
Alex Lorenzee024992014-08-04 18:41:51 +00001459 // Create the coverage data record
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001460 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001461 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001462 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001463 auto CovDataVal =
1464 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001465 auto CovData = new llvm::GlobalVariable(
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001466 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
Xinliang David Li20b188c2016-01-03 19:25:54 +00001467 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001468
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001469 CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001470 CovData->setAlignment(llvm::Align(8));
Alex Lorenzee024992014-08-04 18:41:51 +00001471
1472 // Make sure the data doesn't get deleted.
1473 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001474 // Create the deferred function records array
1475 if (!FunctionNames.empty()) {
1476 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1477 FunctionNames.size());
1478 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1479 // This variable will *NOT* be emitted to the object file. It is used
1480 // to pass the list of names referenced to codegen.
1481 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1482 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001483 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001484 }
Alex Lorenzee024992014-08-04 18:41:51 +00001485}
1486
1487unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1488 auto It = FileEntries.find(File);
1489 if (It != FileEntries.end())
1490 return It->second;
1491 unsigned FileID = FileEntries.size();
1492 FileEntries.insert(std::make_pair(File, FileID));
1493 return FileID;
1494}
1495
1496void CoverageMappingGen::emitCounterMapping(const Decl *D,
1497 llvm::raw_ostream &OS) {
1498 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001499 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001500 Walker.VisitDecl(D);
1501 Walker.write(OS);
1502}
1503
1504void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1505 llvm::raw_ostream &OS) {
1506 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1507 Walker.VisitDecl(D);
1508 Walker.write(OS);
1509}